Skip to content
Merged
82 changes: 43 additions & 39 deletions Tests/EngagedTimeTests.swift
Original file line number Diff line number Diff line change
@@ -1,80 +1,80 @@
import XCTest
import os.log
@testable import ParselyAnalytics
import XCTest

class EngagedTimeTests: ParselyTestCase {
var engagedTime: EngagedTime?
var sharedInstance: Parsely?

let testUrl: String = "http://parsely-stuff.com"

override func setUp() {
super.setUp()
engagedTime = EngagedTime(trackerInstance: parselyTestTracker)
sharedInstance = Parsely.sharedInstance
}


func testHeartbeatFn() {
let dummyEventArgs: Dictionary<String, Any> = engagedTime!.generateEventArgs(
url: testUrl, urlref: "", extra_data: nil, idsite: ParselyTestCase.testApikey)
let parsely = makePareslyTracker()
let engagedTime = EngagedTime(trackerInstance: parsely)
let dummyEventArgs: Dictionary<String, Any> = engagedTime.generateEventArgs(
url: testUrl, urlref: "", extra_data: nil, idsite: Parsely.testAPIKey)
let dummyAccumulator: Accumulator = Accumulator(key: "", accumulatedTime: 0, totalTime: 0,
firstSampleTime: Date(),
lastSampleTime: Date(), lastPositiveSampleTime: Date(),
heartbeatTimeout: 0, contentDuration: 0, isEngaged: false,
eventArgs: dummyEventArgs)
engagedTime!.heartbeatFn(data: dummyAccumulator, enableHeartbeats: true)
XCTAssertEqual(parselyTestTracker.eventQueue.length(), 1,
engagedTime.heartbeatFn(data: dummyAccumulator, enableHeartbeats: true)
XCTAssertEqual(parsely.eventQueue.length(), 1,
"A call to EngagedTime.heartbeatFn should add an event to eventQueue")
}

func testStartInteraction() {
engagedTime!.startInteraction(url: testUrl, urlref: "", extra_data: nil,
idsite: ParselyTestCase.testApikey)
let internalAccumulators:Dictionary<String, Accumulator> = engagedTime!.accumulators
let engagedTime = makeEngagedTime()
engagedTime.startInteraction(url: testUrl, urlref: "", extra_data: nil,
idsite: Parsely.testAPIKey)
let internalAccumulators:Dictionary<String, Accumulator> = 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")
}

func testEndInteraction() {
engagedTime!.startInteraction(url: testUrl, urlref: "", extra_data: nil,
idsite: ParselyTestCase.testApikey)
engagedTime!.endInteraction()
let internalAccumulators:Dictionary<String, Accumulator> = engagedTime!.accumulators
let engagedTime = makeEngagedTime()
engagedTime.startInteraction(url: testUrl, urlref: "", extra_data: nil,
idsite: Parsely.testAPIKey)
engagedTime.endInteraction()
let internalAccumulators:Dictionary<String, Accumulator> = 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")
}

func testSampleFn() {
engagedTime!.startInteraction(url: testUrl, urlref: "", extra_data: nil,
idsite: ParselyTestCase.testApikey)
let sampleResult: Bool = engagedTime!.sampleFn(key: testUrl)
let engagedTime = makeEngagedTime()
engagedTime.startInteraction(url: testUrl, urlref: "", extra_data: nil,
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")
}

func testSampleFnPaused() {
engagedTime!.startInteraction(url: testUrl, urlref: "", extra_data: nil,
idsite: ParselyTestCase.testApikey)
engagedTime!.endInteraction()
let sampleResult: Bool = engagedTime!.sampleFn(key: testUrl)
let engagedTime = makeEngagedTime()
engagedTime.startInteraction(url: testUrl, urlref: "", extra_data: nil,
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")
}


func testGlobalPause() {
let parsely = makePareslyTracker()
// This is call to configure required for the start-stop mechanism to work
sharedInstance?.configure(siteId: ParselyTestCase.testApikey)
parsely.configure(siteId: Parsely.testAPIKey)

let assertionTimeout:TimeInterval = TimeInterval(3)
let acceptableDifference:TimeInterval = TimeInterval(0.2)

sharedInstance!.startEngagement(url: testUrl, urlref: "", extraData: nil, siteId: ParselyTestCase.testApikey)
parsely.startEngagement(url: testUrl, urlref: "", extraData: nil, siteId: Parsely.testAPIKey)
// sleep for three seconds
let expectation = self.expectation(description: "Sampling")
Timer.scheduledTimer(withTimeInterval: assertionTimeout, repeats: false) { timer in
Expand All @@ -87,7 +87,7 @@ class EngagedTimeTests: ParselyTestCase {
} else{
NotificationCenter.default.post(name: UIApplication.didEnterBackgroundNotification, object: nil)
}
let accumulatedTime:TimeInterval = sharedInstance!.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
Expand All @@ -101,10 +101,14 @@ class EngagedTimeTests: ParselyTestCase {
NotificationCenter.default.post(name: UIApplication.willEnterForegroundNotification, object: nil)

// stop tracking engaged time
sharedInstance!.stopEngagement()
let accumulatedTimeSecond:TimeInterval = sharedInstance!.track.engagedTime.accumulators[testUrl]!.accumulatedTime
parsely.stopEngagement()
let accumulatedTimeSecond:TimeInterval = parsely.track.engagedTime.accumulators[testUrl]!.accumulatedTime
XCTAssert(accumulatedTimeSecond == 0.0,
"The accumulated time should be zero and it was \(accumulatedTimeSecond)")

}

func makeEngagedTime() -> EngagedTime {
EngagedTime(trackerInstance: makePareslyTracker())
}
}
92 changes: 51 additions & 41 deletions Tests/EventQueueTests.swift
Original file line number Diff line number Diff line change
@@ -1,58 +1,68 @@
import XCTest
import Nimble
@testable import ParselyAnalytics
import XCTest

class EventQueueTests: XCTestCase {

class EventQueueTests: ParselyTestCase {
var queue = ParselyAnalytics.EventQueue<Int>()

override func setUp() {
super.setUp()
for i:Int in 0...30 {
self.queue.push(i)
}
}

override func tearDown() {
super.tearDown()
}

func testPush() {
self.queue.push(31)
XCTAssert(self.queue.list.count == 32)
var queue = makeQueue(loadedWithNumberOfItems: 30)
queue.push(1)
expect(queue.list).to(haveCount(31))
}

func testPushContentsOf() {
self.queue.push(contentsOf: [31])
XCTAssert(self.queue.list.count == 32)
self.queue.push(contentsOf: [32, 33])
XCTAssert(self.queue.list.count == 34)
self.queue.push(contentsOf: [34, 35].prefix(1))
XCTAssert(self.queue.list.count == 35)
XCTAssert(self.queue.list.suffix(4) == [31, 32, 33, 34])
}

var queue = makeQueue(loadedWithNumberOfItems: 0)
queue.push(contentsOf: [1])
expect(queue.list).to(haveCount(1))

queue.push(contentsOf: [2, 3])
expect(queue.list).to(haveCount(3))

queue.push(contentsOf: [4, 5].prefix(1))
expect(queue.list).to(haveCount((4)))

expect(queue.list.suffix(3)) == [2, 3, 4]
}

func testPop() {
XCTAssert(self.queue.pop() == 0)
var queue = makeQueue(loadedWithNumberOfItems: 2)
expect(queue.pop()) == 0
expect(queue.list).to(haveCount(1))
}

func testGet() {
XCTAssert(self.queue.get(count:5) == [0,1,2,3,4])
XCTAssert(self.queue.get(count:5) == [5,6,7,8,9])
XCTAssert(self.queue.get(count:21) == [10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30])
XCTAssert(self.queue.get(count:5) == [])
var queue = makeQueue(loadedWithNumberOfItems: 30)

expect(queue.get(count: 5)) == [0, 1, 2, 3, 4]
expect(queue.list).to(haveCount(25))

expect(queue.get(count: 5)) == [5, 6, 7, 8, 9]
expect(queue.list).to(haveCount(20))

expect(queue.get(count: 21)) == (10...29).map { $0 }
expect(queue.list).to(beEmpty())

expect(queue.get(count: 5)) == []
}

func testGetAll() {
XCTAssert(self.queue.get() == [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30])
var queue = makeQueue(loadedWithNumberOfItems: 5)
expect(queue.get()) == [0, 1, 2, 3, 4]
}

func testGetTooMany() {
XCTAssert(self.queue.get(count:2147483647) == [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30])
var queue = makeQueue(loadedWithNumberOfItems: 5)
expect(queue.get(count: 1_000)) == [0, 1, 2, 3, 4]
}

func testNegativeCount() {
let invalidGetResult = self.queue.get(count:-42)
XCTAssert(invalidGetResult == [])
var queue = makeQueue(loadedWithNumberOfItems: 5)
expect(queue.get(count: -1)) == []
}

}

func makeQueue(loadedWithNumberOfItems numberOfItem: Int = 30) -> EventQueue<Int> {
var queue = EventQueue<Int>()
(0..<numberOfItem).forEach { queue.push($0) }
return queue
}
}
27 changes: 16 additions & 11 deletions Tests/EventTests.swift
Original file line number Diff line number Diff line change
@@ -1,37 +1,42 @@
import XCTest
@testable import ParselyAnalytics
import XCTest

class EventTests: XCTestCase {

class EventTests: ParselyTestCase {
let testInc: Int = 5
let testTT: Int = 15
let expectedVisitorID: String = "12345fdffff"
let timestampInThePast: UInt64 = 1626963869621

let expectedStrings: Dictionary<String, String> = [
"action": "pageview",
"url": "http://parsely-stuff.com",
"urlref": "http://testt.com",
"idsite": testApikey,
"idsite": "apikey",
"surl": "http://parsely-stuff.com",
"sref": "http://parsely-test.com",
]
]

let expectedInts: Dictionary<String, Int> = [
"sid": 0,
]

let expectedUInt64s: Dictionary<String, UInt64> = [
"sts": 1626963869621,
"slts": 1626963869621
]

let extraData: Dictionary<String, String> = [
"arbitraryParameter1": "testValue",
"arbitraryParameter2": "testValue2"
]

let testMetadata: ParselyMetadata = ParselyMetadata(
canonical_url: "http://parsely-test.com", pub_date: Date.init(), title: "a title.", authors: ["Yogi Berra"],
image_url: "http://parsely-test.com/image2", section: "Things my mother says", tags: ["tag1", "tag2"],
duration: TimeInterval(100)
)

func testEvent() {
let eventUnderTest = Event(expectedStrings["action"]!, url: expectedStrings["url"]!,
urlref: expectedStrings["urlref"], metadata: testMetadata,
Expand Down Expand Up @@ -64,7 +69,7 @@ class EventTests: ParselyTestCase {
let extraDataIsEquivalent: Bool = NSDictionary(dictionary: eventUnderTest.extra_data!).isEqual(to: extraData)
XCTAssert(extraDataIsEquivalent, "The extra_data procided in Event initialization should be stored properly")
}

func testHeartbeatEvents() {
let event = Heartbeat(
"heartbeat",
Expand All @@ -80,10 +85,10 @@ class EventTests: ParselyTestCase {
XCTAssertEqual(event.url, expectedStrings["url"],
"The url used to initialize a heartbeat event should be stored properly")
XCTAssertEqual(event.inc, testInc, "The inc parameter used to initialize a heartbeat event should be stored properly")
XCTAssertEqual(event.idsite, ParselyTestCase.testApikey,
XCTAssertEqual(event.idsite, "apikey",
"The idsite parameter used to initialize a heartbeat event should be stored properly")
}

func testToDict() {
let eventUnderTest = Event(expectedStrings["action"]!, url: expectedStrings["url"]!,
urlref: expectedStrings["urlref"], metadata: testMetadata,
Expand Down Expand Up @@ -120,7 +125,7 @@ class EventTests: ParselyTestCase {
XCTAssert((actualExtraData["ts"] as! UInt64) > timestampInThePast,
"The data.ts field of the result of Event.toDict should be a non-ancient timestamp")
}

func testSetSessionInfo() {
let eventUnderTest = Event(expectedStrings["action"]!, url: expectedStrings["url"]!,
urlref: expectedStrings["urlref"], metadata: testMetadata,
Expand All @@ -143,7 +148,7 @@ class EventTests: ParselyTestCase {
XCTAssertEqual(eventUnderTest.session_url, expectedStrings["surl"],
"The surl set via setSessionInfo should be stored properly")
}

func testSetVisitorInfo() {
let eventUnderTest = Event(expectedStrings["action"]!, url: expectedStrings["url"]!,
urlref: expectedStrings["urlref"], metadata: testMetadata,
Expand Down
11 changes: 6 additions & 5 deletions Tests/MetadataTests.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
@testable import ParselyAnalytics
import XCTest

class MetadataTests: ParselyTestCase {
class MetadataTests: XCTestCase {

let expected: Dictionary<String, Any> = [
"canonical_url": "http://parsely-test.com",
"pub_date": Date(),
Expand All @@ -12,12 +13,12 @@ class MetadataTests: ParselyTestCase {
"tags": ["tag1", "tag2"],
"duration": TimeInterval(100)
]

func testToDictEmpty() {
let metas = ParselyMetadata()
XCTAssert(metas.toDict().isEmpty, "Creating a ParselyMetadata object with no parameters results in an empty object")
}

func testToDictBasic() {
let metas = ParselyMetadata(canonical_url: "http://test.com")
let expected = ["link": "http://test.com"]
Expand All @@ -26,7 +27,7 @@ class MetadataTests: ParselyTestCase {
"Creating a ParselyMetadata object with one parameter results in a valid object containing " +
"a representation of that parameter")
}

func testToDictFields() {
let metasUnderTest = ParselyMetadata(
canonical_url: expected["canonical_url"] as? String,
Expand Down Expand Up @@ -67,7 +68,7 @@ class MetadataTests: ParselyTestCase {
"The duration field in the result of ParselyMetadata.toDict should match the duration argument " +
"used at initialization")
}

func testMetadata() {
let metasUnderTest = ParselyMetadata(
canonical_url: expected["canonical_url"] as? String,
Expand Down
Loading