From 1c81cc7d777e422093c2bbcfad17c35cc6edb2a1 Mon Sep 17 00:00:00 2001 From: Gio Lodi Date: Thu, 28 Nov 2024 10:43:46 +1100 Subject: [PATCH] Track result of running `make format` --- Demo/ParselyDemo/AppDelegate.swift | 6 +-- Demo/ParselyDemo/FirstViewController.swift | 8 ++-- Sources/EngagedTime.swift | 12 ++--- Sources/Event.swift | 10 ++-- Sources/EventQueue.swift | 14 +++--- Sources/HttpClient.swift | 8 ++-- Sources/Metadata.swift | 28 +++++------ Sources/ParselyTracker.swift | 50 ++++++++++---------- Sources/Pixel.swift | 4 +- Sources/RequestBuilder.swift | 14 +++--- Sources/Sampler.swift | 55 +++++++++++----------- Sources/Session.swift | 6 +-- Sources/Storage.swift | 8 ++-- Sources/Track.swift | 34 ++++++------- Sources/Video.swift | 18 +++---- Sources/Visitor.swift | 18 +++---- Tests/EngagedTimeTests.swift | 32 ++++++------- Tests/EventTests.swift | 8 ++-- Tests/MetadataTests.swift | 38 +++++++-------- Tests/ParselyTrackerTests.swift | 2 +- Tests/RequestBuilderTests.swift | 10 ++-- Tests/SamplerTests.swift | 18 +++---- Tests/SessionTests.swift | 16 +++---- Tests/StorageTests.swift | 8 ++-- Tests/TrackTests.swift | 10 ++-- Tests/VisitorTests.swift | 8 ++-- 26 files changed, 221 insertions(+), 222 deletions(-) diff --git a/Demo/ParselyDemo/AppDelegate.swift b/Demo/ParselyDemo/AppDelegate.swift index 40465730..b431e26c 100644 --- a/Demo/ParselyDemo/AppDelegate.swift +++ b/Demo/ParselyDemo/AppDelegate.swift @@ -3,7 +3,7 @@ import ParselyAnalytics @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { - + // This is unused but necessary in a Storyboard without UISceneDelegate setup. // Without it, the app will show a black screen and log: // @@ -11,11 +11,11 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var parsely: Parsely! - + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { self.parsely = Parsely.sharedInstance self.parsely.configure(siteId: "parsely-configured-default.com") - + return true } } diff --git a/Demo/ParselyDemo/FirstViewController.swift b/Demo/ParselyDemo/FirstViewController.swift index ef520bc4..0a2f03c0 100644 --- a/Demo/ParselyDemo/FirstViewController.swift +++ b/Demo/ParselyDemo/FirstViewController.swift @@ -4,18 +4,18 @@ import ParselyAnalytics class FirstViewController: UIViewController { let delegate = UIApplication.shared.delegate as! AppDelegate - + @IBAction func didTouchButton(_ sender: Any) { os_log("didTouchButton", log: OSLog.default, type: .debug) let demoMetas = ParselyMetadata(authors: ["Yogi Berr"]) delegate.parsely.trackPageView(url: "http://parsely.com/path/cool-blog-post/1?qsarg=nawp&anotherone=yup", metadata: demoMetas, extraData: ["product-id": "12345"], siteId: "subdomain.parsely-test.com") } - + @IBAction func didStartEngagement(_ sender: Any) { os_log("didStartEngagement", log: OSLog.default, type: .debug) - delegate.parsely.startEngagement(url: "http://parsely.com/very-not-real", urlref:"http://parsely.com/not-real", extraData: ["product-id": "12345"], siteId: "engaged.parsely-test.com") + delegate.parsely.startEngagement(url: "http://parsely.com/very-not-real", urlref: "http://parsely.com/not-real", extraData: ["product-id": "12345"], siteId: "engaged.parsely-test.com") } - + @IBAction func didStopEngagement(_ sender: Any) { os_log("didStopEngagement", log: OSLog.default, type: .debug) delegate.parsely.stopEngagement() diff --git a/Sources/EngagedTime.swift b/Sources/EngagedTime.swift index fea01a26..ce3d2297 100644 --- a/Sources/EngagedTime.swift +++ b/Sources/EngagedTime.swift @@ -2,7 +2,7 @@ import Foundation import os.log class EngagedTime: Sampler { - override func sampleFn(key : String) -> Bool { + override func sampleFn(key: String) -> Bool { guard let trackedData = accumulators[key] else { os_log("No accumulator found for key %s. Skipping sampling.", log: OSLog.tracker, type: .debug, key) return false @@ -10,7 +10,7 @@ class EngagedTime: Sampler { return trackedData.isEngaged } - + override func heartbeatFn(data: Accumulator, enableHeartbeats: Bool) { if enableHeartbeats != true { return @@ -32,20 +32,20 @@ class EngagedTime: Sampler { parselyTracker.track.event(event: event) } - + func startInteraction(url: String, urlref: String = "", extra_data: Dictionary?, idsite: String) { endInteraction() os_log("Starting Interaction", log: OSLog.tracker, type: .debug) let eventArgs = generateEventArgs(url: url, urlref: urlref, extra_data: extra_data, idsite: idsite) - trackKey(key: url, contentDuration: nil, eventArgs: eventArgs, resetOnExisting: true); + trackKey(key: url, contentDuration: nil, eventArgs: eventArgs, resetOnExisting: true) accumulators[url]!.isEngaged = true } - + func endInteraction() { os_log("Ending Interaction", log: OSLog.tracker, type: .debug) for (url, _) in accumulators { guard var _ = accumulators[url] else { - os_log("No accumulator found for %s, skipping endInteraction", log: OSLog.tracker, type:.debug, url) + os_log("No accumulator found for %s, skipping endInteraction", log: OSLog.tracker, type: .debug, url) return } accumulators[url]!.isEngaged = false diff --git a/Sources/Event.swift b/Sources/Event.swift index 4534bca2..9371f577 100644 --- a/Sources/Event.swift +++ b/Sources/Event.swift @@ -14,7 +14,7 @@ class Event { private(set) var last_session_timestamp: UInt64? private(set) var parsely_site_uuid: String? let rand: UInt64 - + init(_ action: String, url: String, urlref: String?, @@ -58,21 +58,21 @@ class Event { parsely_site_uuid = visitor } - func toDict() -> Dictionary { + func toDict() -> Dictionary { var params: Dictionary = [ "url": self.url, "urlref": self.urlref, "action": self.action, "idsite": self.idsite, ] - + var data: [String: Any] = extra_data data["ts"] = self.rand - + if let parsely_site_uuid { data["parsely_site_uuid"] = parsely_site_uuid } - + params["data"] = data if let metas = self.metadata { diff --git a/Sources/EventQueue.swift b/Sources/EventQueue.swift index 3da58001..a2b0547b 100644 --- a/Sources/EventQueue.swift +++ b/Sources/EventQueue.swift @@ -15,17 +15,17 @@ extension Array { struct EventQueue { var list = [T]() - - mutating func push(_ element:T) { + + mutating func push(_ element: T) { os_log("Event pushed into queue", log: OSLog.tracker, type: .debug) list.append(element) } - mutating func push(contentsOf elements:Collection) where T == Collection.Element, Collection: Sequence { + mutating func push(contentsOf elements: Collection) where T == Collection.Element, Collection: Sequence { os_log("Events pushed into queue", log: OSLog.tracker, type: .debug) list.append(contentsOf: elements) } - + mutating func pop() -> T? { if list.isEmpty { return nil @@ -33,8 +33,8 @@ struct EventQueue { os_log("Event popped from queue", log: OSLog.tracker, type: .debug) return list.removeFirst() } - - mutating func get(count:Int = 0) -> [T] { + + mutating func get(count: Int = 0) -> [T] { if count == 0 { os_log("Got %zd events from queue", log: OSLog.tracker, type: .debug, list.count) return list.take(list.count) @@ -42,7 +42,7 @@ struct EventQueue { os_log("Got %zd events from queue", log: OSLog.tracker, type: .debug, count) return list.take(count) } - + func length() -> Int { return list.count } diff --git a/Sources/HttpClient.swift b/Sources/HttpClient.swift index 84aae5a0..2dfb44e2 100644 --- a/Sources/HttpClient.swift +++ b/Sources/HttpClient.swift @@ -4,21 +4,21 @@ import os.log class HttpClient { static func sendRequest(request: ParselyRequest, queue: DispatchQueue, completion: ((Error?) -> Void)? = nil) { os_log("Sending request to %s", log: OSLog.tracker, type: .debug, request.url) - + guard let url = URL(string: request.url) else { os_log("Failed to create URL from %s", log: OSLog.tracker, type: .error, request.url) return } - + var urlRequest = URLRequest(url: url) urlRequest.httpMethod = "POST" urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: request.params) urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") - + request.headers.forEach { key, value in urlRequest.setValue(value, forHTTPHeaderField: key) } - + URLSession.shared.dataTask(with: urlRequest) { _, _, error in if let err = error { os_log("Request failed: %s", log: OSLog.tracker, type: .error, err.localizedDescription) diff --git a/Sources/Metadata.swift b/Sources/Metadata.swift index bc906bad..396affd9 100644 --- a/Sources/Metadata.swift +++ b/Sources/Metadata.swift @@ -9,11 +9,11 @@ public class ParselyMetadata { var section: String? var tags: Array? var duration: TimeInterval? - + /** A class to manage and re-use metadata. Metadata contained in an instance of this class will conform to Parsely's schema. - + - Parameter canonical_url: A post's canonical url. For videos, it is overridden with the vId and thus can be omitted. - Parameter pub_date: Date this piece of content was published. - Parameter title: Title of the content. @@ -22,15 +22,15 @@ public class ParselyMetadata { - Parameter section: Same as section for website integration. - Parameter tags: Up to 20 tags on an event are allowed. - Parameter duration: Durations passed explicitly to trackVideoStart take precedence over any in metadata. - */ + */ public init(canonical_url: String? = nil, - pub_date: Date? = nil, - title: String? = nil, - authors: Array? = nil, - image_url: String? = nil, - section: String? = nil, - tags: Array? = nil, - duration: TimeInterval? = nil) { + pub_date: Date? = nil, + title: String? = nil, + authors: Array? = nil, + image_url: String? = nil, + section: String? = nil, + tags: Array? = nil, + duration: TimeInterval? = nil) { self.canonical_url = canonical_url self.pub_date = pub_date self.title = title @@ -40,15 +40,15 @@ public class ParselyMetadata { self.tags = tags self.duration = duration } - + func toDict() -> Dictionary { var metas: Dictionary = [:] - + if let canonical_url { metas["link"] = canonical_url } if let pub_date { - metas["pub_date"] = String(format:"%i", pub_date.millisecondsSince1970) + metas["pub_date"] = String(format: "%i", pub_date.millisecondsSince1970) } if let title { metas["title"] = title @@ -68,7 +68,7 @@ public class ParselyMetadata { if let duration { metas["duration"] = duration } - + return metas } } diff --git a/Sources/ParselyTracker.swift b/Sources/ParselyTracker.swift index 6d84dfb2..57d3936c 100644 --- a/Sources/ParselyTracker.swift +++ b/Sources/ParselyTracker.swift @@ -43,11 +43,11 @@ public class Parsely { /** Configure the Parsely tracking SDK. Should be called once per application load, before other Parsely SDK functions are called - + - Parameter siteId: The Parsely site ID for which the pageview event should be counted. Can be overridden - on individual tracking method calls. + on individual tracking method calls. - Parameter handleLifecycle: If true, set up listeners to handle tracking across application lifecycle events. - Defaults to true. + Defaults to true. */ public func configure(siteId: String, handleLifecycle: Bool = true) { os_log("Configuring ParselyTracker", log: OSLog.tracker, type: .debug) @@ -61,7 +61,7 @@ public class Parsely { /** Track a pageview event - + - Parameter url: The url of the page that was viewed - Parameter urlref: The url of the page that linked to the viewed page - Parameter metadata: Metadata for the viewed page @@ -88,7 +88,7 @@ public class Parsely { siteId: String ) { var _siteId = siteId - if (_siteId == "") { + if _siteId == "" { _siteId = self.apikey } os_log("Tracking PageView", log: OSLog.tracker, type: .debug) @@ -99,7 +99,7 @@ public class Parsely { Start tracking engaged time for a given url. Once called, heartbeat events will be sent periodically for this url until engaged time tracking is stopped. Stops tracking engaged time for any urls currently being tracked for engaged time. - + - Parameter url: The url of the page being engaged with - Parameter urlref: The url of the page that linked to the page being engaged with - Parameter extraData: A dictionary of additional information to send with generated heartbeat events @@ -123,7 +123,7 @@ public class Parsely { siteId: String ) { var _siteId = siteId - if (_siteId == "") { + if _siteId == "" { _siteId = self.apikey } track.startEngagement(url: url, urlref: urlref, extra_data: extraData, idsite: _siteId) @@ -143,7 +143,7 @@ public class Parsely { Start tracking view time for a given video being viewed at a given url. Sends a videostart event for the given url/video combination. Once called, vheartbeat events will be sent periodically for this url/video combination until video view tracking is stopped. Stops tracking view time for any url/video combinations currently being tracked for view time. - + - Parameter url: The url at which the video is being viewed. Equivalent to the url of the page on which the video is embedded - Parameter urlref: The url of the page that linked to the page on which the video is being viewed - Parameter videoID: A string uniquely identifying the video within your Parsely account @@ -176,7 +176,7 @@ public class Parsely { siteId: String ) { var _siteId = siteId - if (_siteId == "") { + if _siteId == "" { _siteId = self.apikey } track.videoStart(url: url, urlref: urlref, vId: videoID, duration: duration, metadata: metadata, extra_data: extraData, idsite: _siteId) @@ -191,15 +191,15 @@ public class Parsely { self.track.videoPause() } } - + /** Unset tracking data for the given url/video combination. The next time trackPlay is called for that combination, it will behave as if it had never been tracked before during this run of the app. - + - Parameter url: The url at which the video wss being viewed. Equivalent to the url of the page on which the video is embedded - Parameter videoId: The video ID string for the video being reset */ - public func resetVideo(url:String, videoID:String) { + public func resetVideo(url: String, videoID: String) { eventProcessor.async { self.track.videoReset(url: url, vId: videoID) } @@ -225,9 +225,9 @@ public class Parsely { let task = BackgroundTask.begin() - os_log("Flushing event queue", log: OSLog.tracker, type:.debug) + os_log("Flushing event queue", log: OSLog.tracker, type: .debug) let events = eventQueue.get() - os_log("Got %s events", log: OSLog.tracker, type:.debug, String(describing: events.count)) + os_log("Got %s events", log: OSLog.tracker, type: .debug, String(describing: events.count)) let request = RequestBuilder.buildRequest(events: events) HttpClient.sendRequest(request: request, queue: eventProcessor) { error in if let error = error as? URLError, error.code == .notConnectedToInternet { @@ -239,21 +239,21 @@ public class Parsely { task.end() } } - + internal func startFlushTimer() { - os_log("Flush timer starting", log: OSLog.tracker, type:.debug) + os_log("Flush timer starting", log: OSLog.tracker, type: .debug) if flushTimer == nil && active { flushTimer = scheduleEventProcessing(inSeconds: flushInterval, target: self, selector: #selector(flush)) - os_log("Flush timer started", log: OSLog.tracker, type:.debug) + os_log("Flush timer started", log: OSLog.tracker, type: .debug) } } - + internal func pauseFlushTimer() { - os_log("Flush timer stopping", log: OSLog.tracker, type:.debug) + os_log("Flush timer stopping", log: OSLog.tracker, type: .debug) if flushTimer != nil && !active { flushTimer?.cancel() flushTimer = nil - os_log("Flush timer stopped", log: OSLog.tracker, type:.debug) + os_log("Flush timer stopped", log: OSLog.tracker, type: .debug) } } @@ -273,24 +273,24 @@ public class Parsely { return } self.active = true - os_log("Resuming execution after foreground/active", log:OSLog.tracker, type:.info) + os_log("Resuming execution after foreground/active", log: OSLog.tracker, type: .info) startFlushTimer() track.resume() } - + @objc private func suspendExecution(_ notification: Notification) { if !active { return } self.active = false - os_log("Stopping execution before background/inactive/terminate", log:OSLog.tracker, type:.info) + os_log("Stopping execution before background/inactive/terminate", log: OSLog.tracker, type: .info) hardShutdown() - os_log("Flushing queue in background", log:OSLog.tracker, type:.info) + os_log("Flushing queue in background", log: OSLog.tracker, type: .info) self.track.sendHeartbeats() self.flush() } - + internal func hardShutdown() { pauseFlushTimer() track.pause() diff --git a/Sources/Pixel.swift b/Sources/Pixel.swift index 735f8848..652663bc 100644 --- a/Sources/Pixel.swift +++ b/Sources/Pixel.swift @@ -4,7 +4,7 @@ import os.log class Pixel { var sessionManager: SessionManager private let parselyTracker: Parsely - + init(trackerInstance: Parsely) { parselyTracker = trackerInstance sessionManager = SessionManager(trackerInstance: parselyTracker) @@ -18,7 +18,7 @@ class Pixel { } os_log("Fired beacon: action = %s", log: OSLog.tracker, type: .debug, event.action) let session: Dictionary = sessionManager.get(url: event.url, urlref: event.urlref, - shouldExtendExisting: true) + shouldExtendExisting: true) event.setSessionInfo(session: session) let visitorInfo = parselyTracker.visitorManager.getVisitorInfo(shouldExtendExisting: true) event.setVisitorInfo(visitorInfo: visitorInfo as Dictionary) diff --git a/Sources/RequestBuilder.swift b/Sources/RequestBuilder.swift index d77efdd9..44e4f29f 100644 --- a/Sources/RequestBuilder.swift +++ b/Sources/RequestBuilder.swift @@ -9,17 +9,17 @@ struct ParselyRequest { } class RequestBuilder { - + static var _baseURL: String? = nil static var userAgent: String? = nil - + internal static func getHardwareString() -> String { var mib = [CTL_HW, HW_MACHINE] var len: size_t = 0 sysctl(&mib, 2, nil, &len, nil, 0) - let machine = UnsafeMutablePointer.allocate(capacity:len) + let machine = UnsafeMutablePointer.allocate(capacity: len) sysctl(&mib, 2, machine, &len, nil, 0) - let platform: String = String(cString:machine, encoding:String.Encoding.ascii) ?? "" + let platform: String = String(cString: machine, encoding: String.Encoding.ascii) ?? "" machine.deallocate() return platform } @@ -42,14 +42,14 @@ class RequestBuilder { return userAgent } - + static func buildRequest(events: Array) -> ParselyRequest { let request = ParselyRequest.init( url: buildPixelEndpoint(), headers: buildHeadersDict(events: events), params: buildParamsDict(events: events) ) - os_log("Built request", log: OSLog.tracker, type:.debug) + os_log("Built request", log: OSLog.tracker, type: .debug) return request } @@ -58,7 +58,7 @@ class RequestBuilder { _baseURL = endpoint return endpoint } - + internal static func buildHeadersDict(events: Array) -> Dictionary { let userAgent: String = getUserAgent() return ["User-Agent": userAgent] diff --git a/Sources/Sampler.swift b/Sources/Sampler.swift index 2eae5932..b745ef22 100644 --- a/Sources/Sampler.swift +++ b/Sources/Sampler.swift @@ -36,10 +36,10 @@ class Sampler { var samplerTimer: Cancellable? var heartbeatsTimer: Cancellable? internal let parselyTracker: Parsely - + init(trackerInstance: Parsely) { parselyTracker = trackerInstance - + if let secondsBetweenHeartbeats: TimeInterval = parselyTracker.secondsBetweenHeartbeats { if secondsBetweenHeartbeats >= MIN_TIME_BETWEEN_HEARTBEATS && secondsBetweenHeartbeats <= MAX_TIME_BETWEEN_HEARTBEATS { baseHeartbeatInterval = secondsBetweenHeartbeats @@ -67,17 +67,17 @@ class Sampler { if isNew || shouldReset { heartbeatInterval = baseHeartbeatInterval let newTrackedData = Accumulator.init( - key: key, - accumulatedTime: TimeInterval(0), - totalTime: TimeInterval(0), - firstSampleTime: Date(), - lastSampleTime: Date(), - lastPositiveSampleTime: nil, - heartbeatTimeout: heartbeatInterval, - contentDuration: contentDuration, - isEngaged: false, - eventArgs: eventArgs - ) + key: key, + accumulatedTime: TimeInterval(0), + totalTime: TimeInterval(0), + firstSampleTime: Date(), + lastSampleTime: Date(), + lastPositiveSampleTime: nil, + heartbeatTimeout: heartbeatInterval, + contentDuration: contentDuration, + isEngaged: false, + eventArgs: eventArgs + ) accumulators[key] = newTrackedData } @@ -86,7 +86,7 @@ class Sampler { restartTimers() } } - + private func restartTimers() { os_log("Restarted Timers in %@", log: OSLog.tracker, type: .debug, String(describing: self)) if samplerTimer != nil { @@ -100,17 +100,17 @@ class Sampler { } func dropKey(key: String) -> Void { - os_log("Dropping Sampler key: %s", log: OSLog.tracker, type:.debug, key) + os_log("Dropping Sampler key: %s", log: OSLog.tracker, type: .debug, key) sendHeartbeat(key: key) accumulators.removeValue(forKey: key) } func generateEventArgs(url: String, urlref: String, metadata: ParselyMetadata? = nil, extra_data: Dictionary?, idsite: String) -> Dictionary { var eventArgs: [String: Any] = ["urlref": urlref, "url": url, "idsite": idsite] - if (metadata != nil) { + if metadata != nil { eventArgs["metadata"] = metadata! } - if (extra_data != nil) { + if extra_data != nil { eventArgs["extra_data"] = extra_data! } return eventArgs @@ -119,7 +119,7 @@ class Sampler { @objc private func sample() -> Void { let currentTime = Date() var shouldCountSample: Bool, increment: TimeInterval - + for var (_, trackedData) in accumulators { shouldCountSample = sampleFn(key: trackedData.key) if shouldCountSample { @@ -132,10 +132,9 @@ class Sampler { } samplerTimer = parselyTracker.scheduleEventProcessing(inSeconds: SAMPLE_RATE, target: self, selector: #selector(sample)) } - + private func getHeartbeatInterval(existingTimeout: TimeInterval, - totalTrackedTime: TimeInterval) -> TimeInterval - { + totalTrackedTime: TimeInterval) -> TimeInterval { let totalWithOffset: TimeInterval = totalTrackedTime + offsetMatchingBaseInterval let newInterval: TimeInterval = totalWithOffset * backoffProportion let clampedNewInterval: TimeInterval = min(MAX_TIME_BETWEEN_HEARTBEATS, newInterval) @@ -144,16 +143,16 @@ class Sampler { private func sendHeartbeat(key: String) -> Void { guard var trackedData = accumulators[key] else { - os_log("No accumulator found for %s, skipping sendHeartbeat", log: OSLog.tracker, type:.debug, key) + os_log("No accumulator found for %s, skipping sendHeartbeat", log: OSLog.tracker, type: .debug, key) return } let incSecs: TimeInterval = trackedData.accumulatedTime if incSecs > 0 { - os_log("Sending heartbeat for %s", log: OSLog.tracker, type:.debug, key) + os_log("Sending heartbeat for %s", log: OSLog.tracker, type: .debug, key) heartbeatFn(data: trackedData, enableHeartbeats: true) } trackedData.accumulatedTime = 0 - let totalTrackedTime: TimeInterval = Date().timeIntervalSince(trackedData.firstSampleTime!); + let totalTrackedTime: TimeInterval = Date().timeIntervalSince(trackedData.firstSampleTime!) trackedData.heartbeatTimeout = self.getHeartbeatInterval( existingTimeout: trackedData.heartbeatTimeout!, totalTrackedTime: totalTrackedTime) @@ -172,9 +171,9 @@ class Sampler { private func updateAccumulator(acc: Accumulator) -> Void { accumulators[acc.key] = acc } - + internal func pause() { - os_log("Paused from %@", log:OSLog.tracker, type:.debug, String(describing: self)) + os_log("Paused from %@", log: OSLog.tracker, type: .debug, String(describing: self)) if samplerTimer != nil { samplerTimer!.cancel() samplerTimer = nil @@ -184,9 +183,9 @@ class Sampler { heartbeatsTimer = nil } } - + internal func resume() { - os_log("Resumed from %@", log:OSLog.tracker, type:.debug, String(describing: self)) + os_log("Resumed from %@", log: OSLog.tracker, type: .debug, String(describing: self)) if hasStartedSampling { restartTimers() } diff --git a/Sources/Session.swift b/Sources/Session.swift index 9d160bc7..2af4bdc3 100644 --- a/Sources/Session.swift +++ b/Sources/Session.swift @@ -26,14 +26,14 @@ class SessionManager { if let previousCount = visitorInfo["session_count"] as? Int { visitorInfo["session_count"] = previousCount + 1 } - + session = [:] session["session_id"] = visitorInfo["session_count"] session["session_url"] = url session["session_referrer"] = urlref session["session_ts"] = Date().millisecondsSince1970 session["last_session_ts"] = visitorInfo["last_session_ts"] - + visitorInfo["last_session_ts"] = session["session_ts"] let _ = visitorManager.setVisitorInfo(visitorInfo: visitorInfo) session = storage.set(key: sessionKey, value: session as Dictionary, expires: Date.init(timeIntervalSinceNow: SESSION_TIMEOUT)) @@ -42,7 +42,7 @@ class SessionManager { } return session } - + internal func extendExpiry() -> Dictionary { let expiry = Date.init(timeIntervalSinceNow: self.SESSION_TIMEOUT) let result = storage.extendExpiry(key: self.sessionKey, expires: expiry) ?? [:] diff --git a/Sources/Storage.swift b/Sources/Storage.swift index 5c5cc5c4..1bb67cd7 100644 --- a/Sources/Storage.swift +++ b/Sources/Storage.swift @@ -1,11 +1,11 @@ import Foundation extension Date { - var millisecondsSince1970:UInt64 { + var millisecondsSince1970: UInt64 { return UInt64(floor(self.timeIntervalSince1970 * 1000)) } - - init(milliseconds:UInt64) { + + init(milliseconds: UInt64) { self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000) } } @@ -32,7 +32,7 @@ class Storage { func set(key: String, value: Dictionary, expires: Date?) -> Dictionary { var data = value if expires != nil { - data[self.expiryDateKey] = expires + data[self.expiryDateKey] = expires } self.defaults.set(data, forKey: key) return data diff --git a/Sources/Track.swift b/Sources/Track.swift index 94ae2e8a..ba29c889 100644 --- a/Sources/Track.swift +++ b/Sources/Track.swift @@ -16,11 +16,11 @@ class Track { func event(event: Event) { if event.idsite.isEmpty { - os_log("idsite not specified. Use ParselyTracker.configure or specify it as an argument to tracking functions.", log: OSLog.tracker, type:.error) + os_log("idsite not specified. Use ParselyTracker.configure or specify it as an argument to tracking functions.", log: OSLog.tracker, type: .error) return } - parselyTracker.startFlushTimer(); - + parselyTracker.startFlushTimer() + pixel.beacon(event: event) os_log_sending_event(event) } @@ -35,48 +35,48 @@ class Track { idsite: idsite ) - os_log("Sending a pageview from Track", log: OSLog.tracker, type:.debug) + os_log("Sending a pageview from Track", log: OSLog.tracker, type: .debug) event(event: event_) } func videoStart(url: String, urlref: String, vId: String, duration: TimeInterval, metadata: ParselyMetadata?, extra_data: Dictionary?, idsite: String) { videoManager.trackPlay(url: url, urlref: urlref, vId: vId, duration: duration, metadata: metadata, extra_data: extra_data, idsite: idsite) - os_log("Tracked videoStart from Track", log: OSLog.tracker, type:.debug) + os_log("Tracked videoStart from Track", log: OSLog.tracker, type: .debug) } func videoPause() { videoManager.trackPause() - os_log("Tracked videoPause from Track", log: OSLog.tracker, type:.debug) + os_log("Tracked videoPause from Track", log: OSLog.tracker, type: .debug) } - - func videoReset(url:String, vId:String) { - videoManager.reset(url:url, vId:vId) + + func videoReset(url: String, vId: String) { + videoManager.reset(url: url, vId: vId) } func startEngagement(url: String, urlref: String = "", extra_data: Dictionary?, idsite: String) { engagedTime.startInteraction(url: url, urlref: urlref, extra_data: extra_data, idsite: idsite) - os_log("track start engagement from Track", log: OSLog.tracker, type:.debug) + os_log("track start engagement from Track", log: OSLog.tracker, type: .debug) } func stopEngagement() { engagedTime.endInteraction() - os_log("track stop engagement from Track", log: OSLog.tracker, type:.debug) + os_log("track stop engagement from Track", log: OSLog.tracker, type: .debug) } - + internal func pause() { - os_log("Pausing from track", log:OSLog.tracker, type:.debug) + os_log("Pausing from track", log: OSLog.tracker, type: .debug) engagedTime.pause() videoManager.pause() } - + internal func resume() { - os_log("Resuming from track", log:OSLog.tracker, type:.debug) + os_log("Resuming from track", log: OSLog.tracker, type: .debug) engagedTime.resume() videoManager.resume() } - + internal func sendHeartbeats() { - os_log("Sending heartbeats from track", log:OSLog.tracker, type:.debug) + os_log("Sending heartbeats from track", log: OSLog.tracker, type: .debug) engagedTime.sendHeartbeats() videoManager.sendHeartbeats() } diff --git a/Sources/Video.swift b/Sources/Video.swift index bde1035d..ef816d86 100644 --- a/Sources/Video.swift +++ b/Sources/Video.swift @@ -27,7 +27,7 @@ class VideoManager: Sampler { let totalMs: Int = Int(data.totalTime.milliseconds()) guard var curVideo = trackedVideos[data.key] else { - os_log("Skipping heartbeat for video %s because it is not in the tracked videos list", log: OSLog.tracker, type:.debug, data.key) + os_log("Skipping heartbeat for video %s because it is not in the tracked videos list", log: OSLog.tracker, type: .debug, data.key) return } @@ -42,7 +42,7 @@ class VideoManager: Sampler { idsite: curVideo.eventArgs["idsite"] as? String ) parselyTracker.track.event(event: event) - os_log("Sent vheartbeat for video %s", log: OSLog.tracker, type:.debug, data.key) + os_log("Sent vheartbeat for video %s", log: OSLog.tracker, type: .debug, data.key) curVideo._heartbeatsSent += 1 trackedVideos[curVideo.key] = curVideo } @@ -51,7 +51,7 @@ class VideoManager: Sampler { trackPause() let eventArgs = generateEventArgs(url: url, urlref: urlref, metadata: metadata, extra_data: extra_data, idsite: idsite) var curVideo = self.updateVideoData(vId: vId, url: url, duration: duration, eventArgs: eventArgs) - if (curVideo.hasStartedPlaying != true) { + if curVideo.hasStartedPlaying != true { curVideo.hasStartedPlaying = true let event = Event( "videostart", @@ -68,7 +68,7 @@ class VideoManager: Sampler { } func trackPause() -> Void { - os_log("Pausing all tracked videos", log: OSLog.tracker, type:.debug) + os_log("Pausing all tracked videos", log: OSLog.tracker, type: .debug) for (key, _) in trackedVideos { var curVideo = trackedVideos[key] curVideo!.isPlaying = false @@ -77,24 +77,24 @@ class VideoManager: Sampler { } func reset(url: String, vId: String) { - os_log("Reset video accumulator for url %s and vId %s", log: OSLog.tracker, type:.debug, url, vId) + os_log("Reset video accumulator for url %s and vId %s", log: OSLog.tracker, type: .debug, url, vId) trackPause() let key: String = createVideoTrackingKey(vId: vId, url: url) - trackedVideos.removeValue(forKey:key) + trackedVideos.removeValue(forKey: key) } private func updateVideoData(vId: String, url: String, duration: TimeInterval, eventArgs: Dictionary?) -> TrackedVideo { var _eventArgs: [String: Any] = eventArgs ?? [String: Any]() let metadata = _eventArgs["metadata"] as? ParselyMetadata - if (metadata != nil) { + if metadata != nil { metadata!.canonical_url = vId metadata!.duration = duration } _eventArgs["metadata"] = metadata let key: String = createVideoTrackingKey(vId: vId, url: url) - if (trackedVideos[key] != nil) { + if trackedVideos[key] != nil { trackedVideos[key]!.eventArgs = _eventArgs } else { trackedVideos[key] = TrackedVideo.init( @@ -106,7 +106,7 @@ class VideoManager: Sampler { eventArgs: _eventArgs, _heartbeatsSent: 0) - trackKey(key: key, contentDuration: duration, eventArgs:_eventArgs) + trackKey(key: key, contentDuration: duration, eventArgs: _eventArgs) } return trackedVideos[key]! diff --git a/Sources/Visitor.swift b/Sources/Visitor.swift index 1427c442..8aea21fc 100644 --- a/Sources/Visitor.swift +++ b/Sources/Visitor.swift @@ -7,26 +7,26 @@ class VisitorManager { internal func getVisitorInfo(shouldExtendExisting: Bool = false) -> Dictionary { var visitorInfo = self.storage.get(key: self.visitorKey) ?? [:] - if (visitorInfo.isEmpty) { + if visitorInfo.isEmpty { visitorInfo = self.initVisitor(visitorId: UUID().uuidString) - } else if (shouldExtendExisting) { + } else if shouldExtendExisting { visitorInfo = extendVisitorExpiry() } return visitorInfo } private func initVisitor(visitorId: String) -> Dictionary { - return self.setVisitorInfo(visitorInfo: [ - "id": visitorId, - "session_count": 0, - "last_session_ts": 0 - ]) + return self.setVisitorInfo(visitorInfo: [ + "id": visitorId, + "session_count": 0, + "last_session_ts": 0 + ]) } - + internal func setVisitorInfo(visitorInfo: Dictionary) -> Dictionary { return storage.set(key: visitorKey, value: visitorInfo, expires: Date.init(timeIntervalSinceNow: self.VISITOR_TIMEOUT)) } - + private func extendVisitorExpiry() -> Dictionary { return storage.extendExpiry(key: visitorKey, expires: Date.init(timeIntervalSinceNow: self.VISITOR_TIMEOUT)) ?? [:] } diff --git a/Tests/EngagedTimeTests.swift b/Tests/EngagedTimeTests.swift index fa4bd27e..6ccb78d6 100644 --- a/Tests/EngagedTimeTests.swift +++ b/Tests/EngagedTimeTests.swift @@ -24,31 +24,31 @@ class EngagedTimeTests: ParselyTestCase { func testStartInteraction() { let engagedTime = makeEngagedTime() engagedTime.startInteraction(url: testUrl, urlref: "", extra_data: nil, - idsite: Parsely.testAPIKey) - let internalAccumulators:Dictionary = engagedTime.accumulators + idsite: Parsely.testAPIKey) + let internalAccumulators: Dictionary = engagedTime.accumulators let testUrlAccumulator: Accumulator = internalAccumulators[testUrl]! XCTAssert(testUrlAccumulator.isEngaged, "After a call to EngagedTime.startInteraction, the internal accumulator for the engaged " + - "url should exist and its isEngaged flag should be set") + "url should exist and its isEngaged flag should be set") } func testEndInteraction() { let engagedTime = makeEngagedTime() engagedTime.startInteraction(url: testUrl, urlref: "", extra_data: nil, - idsite: Parsely.testAPIKey) + idsite: Parsely.testAPIKey) engagedTime.endInteraction() - let internalAccumulators:Dictionary = engagedTime.accumulators + let internalAccumulators: Dictionary = engagedTime.accumulators let testUrlAccumulator: Accumulator = internalAccumulators[testUrl]! XCTAssertFalse(testUrlAccumulator.isEngaged, "After a call to EngagedTime.startInteraction followed by a call to " + - "EngagedTime.stopInteraction, the internal accumulator for the engaged " + - "url should exist and its isEngaged flag should be unset") + "EngagedTime.stopInteraction, the internal accumulator for the engaged " + + "url should exist and its isEngaged flag should be unset") } func testSampleFn() { let engagedTime = makeEngagedTime() engagedTime.startInteraction(url: testUrl, urlref: "", extra_data: nil, - idsite: Parsely.testAPIKey) + idsite: Parsely.testAPIKey) let sampleResult: Bool = engagedTime.sampleFn(key: testUrl) XCTAssert(sampleResult, "After a call to EngagedTime.startInteraction, EngagedTime.sample should return true for the interacting key") @@ -57,12 +57,12 @@ class EngagedTimeTests: ParselyTestCase { func testSampleFnPaused() { let engagedTime = makeEngagedTime() engagedTime.startInteraction(url: testUrl, urlref: "", extra_data: nil, - idsite: Parsely.testAPIKey) + idsite: Parsely.testAPIKey) engagedTime.endInteraction() let sampleResult: Bool = engagedTime.sampleFn(key: testUrl) XCTAssertFalse(sampleResult, "After a call to EngagedTime.startInteraction followed by a call to " + - "EngagedTime.stopInteraction, EngagedTime.sample should return false for the interacting key") + "EngagedTime.stopInteraction, EngagedTime.sample should return false for the interacting key") } @@ -71,8 +71,8 @@ class EngagedTimeTests: ParselyTestCase { // This is call to configure required for the start-stop mechanism to work parsely.configure(siteId: Parsely.testAPIKey) - let assertionTimeout:TimeInterval = TimeInterval(3) - let acceptableDifference:TimeInterval = TimeInterval(0.2) + let assertionTimeout: TimeInterval = TimeInterval(3) + let acceptableDifference: TimeInterval = TimeInterval(0.2) parsely.startEngagement(url: testUrl, urlref: "", extraData: nil, siteId: Parsely.testAPIKey) // sleep for three seconds @@ -84,10 +84,10 @@ class EngagedTimeTests: ParselyTestCase { // put application in background if #available(iOS 13.0, *) { NotificationCenter.default.post(name: UIScene.didEnterBackgroundNotification, object: nil) - } else{ + } else { NotificationCenter.default.post(name: UIApplication.didEnterBackgroundNotification, object: nil) } - let accumulatedTime:TimeInterval = parsely.track.engagedTime.accumulators[testUrl]!.accumulatedTime + let accumulatedTime: TimeInterval = parsely.track.engagedTime.accumulators[testUrl]!.accumulatedTime XCTAssert(accumulatedTime <= 3, "Engaged time should be less than or equal to 3 seconds but it was \(accumulatedTime)") // sleep for three more seconds @@ -102,9 +102,9 @@ class EngagedTimeTests: ParselyTestCase { // stop tracking engaged time parsely.stopEngagement() - let accumulatedTimeSecond:TimeInterval = parsely.track.engagedTime.accumulators[testUrl]!.accumulatedTime + let accumulatedTimeSecond: TimeInterval = parsely.track.engagedTime.accumulators[testUrl]!.accumulatedTime XCTAssert(accumulatedTimeSecond == 0.0, - "The accumulated time should be zero and it was \(accumulatedTimeSecond)") + "The accumulated time should be zero and it was \(accumulatedTimeSecond)") } diff --git a/Tests/EventTests.swift b/Tests/EventTests.swift index 2de649b9..add5144b 100644 --- a/Tests/EventTests.swift +++ b/Tests/EventTests.swift @@ -138,13 +138,13 @@ class EventTests: XCTestCase { let expectedMetadata: Dictionary = testMetadata.toDict() let result: Bool = NSDictionary(dictionary: actualMetadata).isEqual(to: expectedMetadata) XCTAssert(result, "The metadata field of the result of Event.toDict should be a dict representation of the " + - "given metadata") + "given metadata") let idKeyExists: Bool = actualExtraData["parsely_site_uuid"] != nil XCTAssert(idKeyExists, "After a call to Event.setVisitorInfo that " + - "passes a visitor dictionary, the parsely_site_uuid key should exist in the extra_data dictionary.") + "passes a visitor dictionary, the parsely_site_uuid key should exist in the extra_data dictionary.") XCTAssertEqual(actualExtraData["parsely_site_uuid"] as! String, expectedVisitorID, "A visitor ID provided via Event.setVisitorInfo should be accessible in the result of " + - "Event.toDict as data[\"parsely_site_uuid\"]") + "Event.toDict as data[\"parsely_site_uuid\"]") XCTAssert((actualExtraData["ts"] as! UInt64) > timestampInThePast, "The data.ts field of the result of Event.toDict should be a non-ancient timestamp") } @@ -153,7 +153,7 @@ class EventTests: XCTestCase { let eventUnderTest = Event(expectedStrings["action"]!, url: expectedStrings["url"]!, urlref: expectedStrings["urlref"], metadata: testMetadata, extra_data: extraData, idsite: expectedStrings["idsite"]!) - eventUnderTest.setSessionInfo(session:[ + eventUnderTest.setSessionInfo(session: [ "session_id": expectedInts["sid"], "session_ts": expectedUInt64s["sts"], "last_session_ts": expectedUInt64s["slts"], diff --git a/Tests/MetadataTests.swift b/Tests/MetadataTests.swift index e3dd6f5a..4c4d47b1 100644 --- a/Tests/MetadataTests.swift +++ b/Tests/MetadataTests.swift @@ -25,7 +25,7 @@ class MetadataTests: XCTestCase { let actual = metas.toDict() XCTAssertEqual(expected as NSObject, actual as NSObject, "Creating a ParselyMetadata object with one parameter results in a valid object containing " + - "a representation of that parameter") + "a representation of that parameter") } func testToDictFields() { @@ -40,33 +40,33 @@ class MetadataTests: XCTestCase { duration: expected["duration"] as? TimeInterval ) let actual: Dictionary = metasUnderTest.toDict() - let pubDateUnix: String = String(format:"%i", (expected["pub_date"]! as! Date).millisecondsSince1970) + let pubDateUnix: String = String(format: "%i", (expected["pub_date"]! as! Date).millisecondsSince1970) XCTAssertFalse(actual.isEmpty, "Creating a ParselyMetadataobject with many parameters results in a " + - "non-empty object") + "non-empty object") XCTAssertEqual(actual["link"]! as! String, expected["canonical_url"]! as! String, "The link field in the result of ParselyMetadata.toDict should match the canonical_url argument " + - "used at initialization") + "used at initialization") XCTAssertEqual(actual["pub_date"]! as! String, pubDateUnix, "The pub_date field in the result of ParselyMetadata.toDict should match the pub_date argument " + - "used at initialization") + "used at initialization") XCTAssertEqual(actual["title"]! as! String, expected["title"]! as! String, "The title field in the result of ParselyMetadata.toDict should match the title argument " + - "used at initialization") + "used at initialization") XCTAssertEqual(actual["authors"]! as! Array, expected["authors"]! as! Array, "The authors field in the result of ParselyMetadata.toDict should match the authors argument " + - "used at initialization") + "used at initialization") XCTAssertEqual(actual["image_url"]! as! String, expected["image_url"]! as! String, "The image_url field in the result of ParselyMetadata.toDict should match the image_url argument " + - "used at initialization") + "used at initialization") XCTAssertEqual(actual["section"]! as! String, expected["section"]! as! String, "The section field in the result of ParselyMetadata.toDict should match the section argument " + - "used at initialization") + "used at initialization") XCTAssertEqual(actual["tags"]! as! Array, expected["tags"]! as! Array, "The tags field in the result of ParselyMetadata.toDict should match the tags argument " + - "used at initialization") + "used at initialization") XCTAssertEqual(actual["duration"]! as! TimeInterval, expected["duration"]! as! TimeInterval, "The duration field in the result of ParselyMetadata.toDict should match the duration argument " + - "used at initialization") + "used at initialization") } func testMetadata() { @@ -82,27 +82,27 @@ class MetadataTests: XCTestCase { ) XCTAssertEqual(metasUnderTest.canonical_url, expected["canonical_url"]! as? String, "The canonical_url field on ParselyMetadata should match the canonical_url argument " + - "used at initialization") + "used at initialization") XCTAssertEqual(metasUnderTest.pub_date, expected["pub_date"]! as? Date, "The pub_date field on ParselyMetadata should match the pub_date argument " + - "used at initialization") + "used at initialization") XCTAssertEqual(metasUnderTest.title, expected["title"]! as? String, "The title field on ParselyMetadata should match the title argument " + - "used at initialization") + "used at initialization") XCTAssertEqual(metasUnderTest.authors, expected["authors"]! as? Array, "The authors field on ParselyMetadata should match the authors argument " + - "used at initialization") + "used at initialization") XCTAssertEqual(metasUnderTest.image_url, expected["image_url"]! as? String, "The image_url field on ParselyMetadata should match the image_url argument " + - "used at initialization") + "used at initialization") XCTAssertEqual(metasUnderTest.section, expected["section"]! as? String, "The section field on ParselyMetadata should match the section argument " + - "used at initialization") + "used at initialization") XCTAssertEqual(metasUnderTest.tags, expected["tags"]! as? Array, "The tags field on ParselyMetadata should match the tags argument " + - "used at initialization") + "used at initialization") XCTAssertEqual(metasUnderTest.duration, expected["duration"]! as? TimeInterval, "The duration field on ParselyMetadata should match the duration argument " + - "used at initialization") + "used at initialization") } } diff --git a/Tests/ParselyTrackerTests.swift b/Tests/ParselyTrackerTests.swift index 476606f2..3b5ecfec 100644 --- a/Tests/ParselyTrackerTests.swift +++ b/Tests/ParselyTrackerTests.swift @@ -15,7 +15,7 @@ class ParselyTrackerTests: ParselyTestCase { func testConfigure() { XCTAssertEqual(parselyTestTracker.apikey, Parsely.testAPIKey, "After a call to Parsely.configure, Parsely.apikey should be the value used in the call's " + - "siteId argument") + "siteId argument") } func testTrackPageView() { diff --git a/Tests/RequestBuilderTests.swift b/Tests/RequestBuilderTests.swift index 4c0301fe..c58e70e0 100644 --- a/Tests/RequestBuilderTests.swift +++ b/Tests/RequestBuilderTests.swift @@ -6,7 +6,7 @@ class RequestBuilderTests: XCTestCase { private func makeEvents() -> Array { let exampleMetadata: ParselyMetadata = ParselyMetadata( - canonical_url:"http://parsely-test.com", + canonical_url: "http://parsely-test.com", pub_date: Date(timeIntervalSince1970: 3), title: "a title.", authors: ["Yogi Berra"], @@ -21,7 +21,7 @@ class RequestBuilderTests: XCTestCase { urlref: nil, metadata: exampleMetadata, extra_data: nil - )] + )] } func testBuildPixelEndpoint() { @@ -32,7 +32,7 @@ class RequestBuilderTests: XCTestCase { let events: Array = makeEvents() let actual: Dictionary = RequestBuilder.buildHeadersDict(events: events) XCTAssert(actual["User-Agent"] != nil, "buildHeadersDict should return a dictionary containing a non-nil " + - "user agent string") + "user agent string") } func testBuildRequest() { @@ -49,7 +49,7 @@ class RequestBuilderTests: XCTestCase { let actualEvents: Array> = request.params["events"] as! Array> XCTAssertEqual(actualEvents.count, events.count, "RequestBuilder.buildRequest should return a request with an events array containing all " + - "relevant revents") + "relevant revents") } func testParamsJson() { @@ -66,7 +66,7 @@ class RequestBuilderTests: XCTestCase { let result = RequestBuilder.getHardwareString() let expected = Set(["x86_64", "arm64"]) XCTAssertTrue(expected.contains(result), - "The result of RequestBuilder.getHardwareString should accurately represent the simulator hardware" + "The result of RequestBuilder.getHardwareString should accurately represent the simulator hardware" ) } diff --git a/Tests/SamplerTests.swift b/Tests/SamplerTests.swift index 78b791ef..db5f6b68 100644 --- a/Tests/SamplerTests.swift +++ b/Tests/SamplerTests.swift @@ -31,8 +31,8 @@ class SamplerTests: ParselyTestCase { } func testSampleFn() { - let assertionTimeout:TimeInterval = TimeInterval(3) - let acceptableDifference:TimeInterval = TimeInterval(0.2) + let assertionTimeout: TimeInterval = TimeInterval(3) + let acceptableDifference: TimeInterval = TimeInterval(0.2) samplerUnderTest!.trackKey(key: "sampler-test", contentDuration: nil, eventArgs: [:]) @@ -42,7 +42,7 @@ class SamplerTests: ParselyTestCase { } waitForExpectations(timeout: assertionTimeout + acceptableDifference, handler: nil) - let accumulatedTime:TimeInterval = samplerUnderTest!.accumulators["sampler-test"]!.totalTime + let accumulatedTime: TimeInterval = samplerUnderTest!.accumulators["sampler-test"]!.totalTime XCTAssert(accumulatedTime >= assertionTimeout - acceptableDifference, "The sampler should accumulate time constantly after a call to trackKey") } @@ -110,9 +110,9 @@ class SamplerTests: ParselyTestCase { url: testUrl, urlref: testUrl, metadata: testMetadata, extra_data: extraData, idsite: Parsely.testAPIKey) XCTAssertEqual(eventArgs["url"] as! String, testUrl, "The url returned in the result of Sampler.generateEventArgs " + - "should match the one passed to the call") + "should match the one passed to the call") XCTAssertEqual(eventArgs["urlref"] as! String, testUrl, "The urlref returned in the result of " + - "Sampler.generateEventArgs should match the one passed to the call") + "Sampler.generateEventArgs should match the one passed to the call") XCTAssertEqual(eventArgs["idsite"] as! String, Parsely.testAPIKey, "The idsite returned in the result of Sampler.generateEventArgs should match the one passed to the call") let actualExtraData: Dictionary = eventArgs["extra_data"] as! Dictionary @@ -124,7 +124,7 @@ class SamplerTests: ParselyTestCase { let expectedMetadata: Dictionary = testMetadata.toDict() let result: Bool = NSDictionary(dictionary: actualMetadata.toDict()).isEqual(to: expectedMetadata) XCTAssert(result, "The metadata field of the result of Sampler.generateEventArgs should be a dict representation " + - "of the given metadata") + "of the given metadata") } func testPause() { @@ -149,8 +149,8 @@ class SamplerTests: ParselyTestCase { } func testPauseStopsCounting() { - let assertionTimeout:TimeInterval = TimeInterval(3) - let acceptableDifference:TimeInterval = TimeInterval(0.2) + let assertionTimeout: TimeInterval = TimeInterval(3) + let acceptableDifference: TimeInterval = TimeInterval(0.2) samplerUnderTest!.trackKey(key: "sampler-test", contentDuration: nil, eventArgs: [:]) @@ -160,7 +160,7 @@ class SamplerTests: ParselyTestCase { } waitForExpectations(timeout: assertionTimeout + acceptableDifference, handler: nil) - let accumulatedTime:TimeInterval = samplerUnderTest!.accumulators["sampler-test"]!.accumulatedTime + let accumulatedTime: TimeInterval = samplerUnderTest!.accumulators["sampler-test"]!.accumulatedTime samplerUnderTest!.pause() XCTAssertEqual( accumulatedTime, diff --git a/Tests/SessionTests.swift b/Tests/SessionTests.swift index 9380e603..664f1b29 100644 --- a/Tests/SessionTests.swift +++ b/Tests/SessionTests.swift @@ -7,7 +7,7 @@ class SessionTests: ParselyTestCase { let sessionStorageKey = "_parsely_session_identifier" let testInitialUrl = "http://parsely-test.com/123" let testSubsequentUrl = "http://parsely-test.com/" - let epochTimeInThePast:UInt64 = 1626963869621 + let epochTimeInThePast: UInt64 = 1626963869621 override func setUp() { super.setUp() @@ -37,8 +37,8 @@ class SessionTests: ParselyTestCase { let subsequentSession = sessions.get(url: testSubsequentUrl, urlref: testInitialUrl, shouldExtendExisting: true) XCTAssertEqual(session["session_id"] as! Int, subsequentSession["session_id"] as! Int, "Sequential calls to SessionManager.get within the session timeout that have " + - "shouldExtendExisting:true should return a session object with the same session ID as the " + - "preexisting session object") + "shouldExtendExisting:true should return a session object with the same session ID as the " + + "preexisting session object") XCTAssertEqual(session["session_url"] as! String, testInitialUrl, "The url of a session that has been extended with a different url should not have changed") } @@ -55,7 +55,7 @@ class SessionTests: ParselyTestCase { "The visitor's session_count should have been incremented after a call to SessionManager.get") XCTAssertEqual(mutatedVisitor["last_session_ts"] as! UInt64, UInt64(expectedLastSessionTs), "The visitor's last_session_ts should have been set to the session's session_ts after a call to " + - "SessionManager.get") + "SessionManager.get") } func testShouldExtendExisting() { @@ -63,8 +63,8 @@ class SessionTests: ParselyTestCase { let subsequentSession = sessions.get(url: testInitialUrl, urlref: "", shouldExtendExisting: true) XCTAssert(subsequentSession["expires"] as! Date > session["expires"] as! Date, "Sequential calls to SessionManager.get within the session timeout that have " + - "shouldExtendExisting:true should return a session object with an extended expiry value " + - "compared to the original expiry of the session") + "shouldExtendExisting:true should return a session object with an extended expiry value " + + "compared to the original expiry of the session") } func testExtendExpiry() { @@ -74,9 +74,9 @@ class SessionTests: ParselyTestCase { let sessionUnderTest = sessions.get(url: testInitialUrl, urlref: "") XCTAssertGreaterThan(extendSessionExpiryResult["expires"] as! Date, initialSessionExpiry, "A call to extendSessionExpiry after a call to SessionManager.get should extend the session's " + - "expiry by the expected amount and return the corresponding value.") + "expiry by the expected amount and return the corresponding value.") XCTAssertGreaterThan(sessionUnderTest["expires"] as! Date, initialSessionExpiry, "A call to extendSessionExpiry after a call to SessionManager.get should extend the session's " + - "expiry by the expected amount.") + "expiry by the expected amount.") } } diff --git a/Tests/StorageTests.swift b/Tests/StorageTests.swift index a284a31f..f7196957 100644 --- a/Tests/StorageTests.swift +++ b/Tests/StorageTests.swift @@ -22,7 +22,7 @@ class StorageTests: ParselyTestCase { expected["expires"] = expires XCTAssertEqual(expected as NSObject, retrievedData! as NSObject, "Sequential calls to Storage.set and Storage.get should preserve the stored object and its " + - "expiry information") + "expiry information") } func testGetSetWithNegativeExpires() { @@ -33,7 +33,7 @@ class StorageTests: ParselyTestCase { let retrievedData = storage.get(key: "baz") ?? [:] XCTAssert(retrievedData.isEmpty, "After a call to Storage.set with a negative expires argument, calls to Storage.get for the set key " + - "should return nil") + "should return nil") } func testDataTypes() { @@ -41,7 +41,7 @@ class StorageTests: ParselyTestCase { "foo": "bar", "baz": 10, "bzz": 10.5, - "lol": ["huh": "yah", "right": 10, "yup": 10.5] as [String : Any], + "lol": ["huh": "yah", "right": 10, "yup": 10.5] as [String: Any], "millis": Date().millisecondsSince1970 ] let fifteenMinutes = Double(1000 * 15 * 60) @@ -52,7 +52,7 @@ class StorageTests: ParselyTestCase { expected["expires"] = expires XCTAssertEqual(expected as NSObject, retrievedData as NSObject, "Sequential calls to Storage.set and Storage.get storing and retrieving varied datatypes should " + - "preserve the stored object and its expiry information") + "preserve the stored object and its expiry information") } func testExtendExpiry() { diff --git a/Tests/TrackTests.swift b/Tests/TrackTests.swift index 99aab76f..11b8b6ac 100644 --- a/Tests/TrackTests.swift +++ b/Tests/TrackTests.swift @@ -50,7 +50,7 @@ class TrackTests: ParselyTestCase { let trackedVideos: Dictionary = videoManager.trackedVideos XCTAssertEqual(trackedVideos.count, 1, "After a call to Track.videoStart followed by a call to track.videoPause, there should be " + - "exactly one video being tracked") + "exactly one video being tracked") let testVideo: TrackedVideo = trackedVideos.values.first! XCTAssertFalse(testVideo.isPlaying, "After a call to Track.videoStart, the tracked video should have its isPlaying flag unset") @@ -70,21 +70,21 @@ class TrackTests: ParselyTestCase { func testStartEngagement() { track!.startEngagement(url: testUrl, urlref: testUrl, extra_data: nil, idsite: Parsely.testAPIKey) - let internalAccumulators:Dictionary = track!.engagedTime.accumulators + let internalAccumulators: Dictionary = track!.engagedTime.accumulators let testUrlAccumulator: Accumulator = internalAccumulators[testUrl]! XCTAssert(testUrlAccumulator.isEngaged, "After a call to Track.startEngagement, the internal accumulator for the engaged url should exist " + - "and its isEngaged flag should be set") + "and its isEngaged flag should be set") } func testStopEngagement() { track!.startEngagement(url: testUrl, urlref: testUrl, extra_data: nil, idsite: Parsely.testAPIKey) track!.stopEngagement() - let internalAccumulators:Dictionary = track!.engagedTime.accumulators + let internalAccumulators: Dictionary = track!.engagedTime.accumulators let testUrlAccumulator: Accumulator = internalAccumulators[testUrl]! XCTAssertFalse(testUrlAccumulator.isEngaged, "After a call to Track.startEngagement followed by a call to Track.stopEngagement, the internal " + - "accumulator for the engaged url should exist and its isEngaged flag should be unset") + "accumulator for the engaged url should exist and its isEngaged flag should be unset") } func testPause() { diff --git a/Tests/VisitorTests.swift b/Tests/VisitorTests.swift index 9e9221f9..f91a2945 100644 --- a/Tests/VisitorTests.swift +++ b/Tests/VisitorTests.swift @@ -14,13 +14,13 @@ class VisitorTests: XCTestCase { let subsequentVisitor = visitors.getVisitorInfo() XCTAssertEqual(visitor["id"] as! String, subsequentVisitor["id"] as! String, "Sequential calls to VisitorManager.getVisitorInfo within the default expiry should return objects " + - "with the same visitor ID") + "with the same visitor ID") XCTAssertEqual(visitor["session_count"] as! Int, subsequentVisitor["session_count"] as! Int, "Sequential calls to VisitorManager.getVisitorInfo within the default expiry should return objects " + - "with the same session count") + "with the same session count") XCTAssertEqual(visitor["last_session_ts"] as! UInt64, subsequentVisitor["last_session_ts"] as! UInt64, "Sequential calls to VisitorManager.getVisitorInfo within the default expiry should return objects " + - "with the same last session timestamp") + "with the same last session timestamp") } func testExtendVisitorExpiry() { @@ -31,6 +31,6 @@ class VisitorTests: XCTestCase { let capturedExpiryTwo = subsequentVisitor["expires"] as! Date XCTAssert(capturedExpiryOne < capturedExpiryTwo, "Given an existing visitor, a call to VisitorManager.getVisitorInfo with shouldExtendExisting:true " + - "should return an object with a later expiry than the preexisting one") + "should return an object with a later expiry than the preexisting one") } }