Skip to content

Commit

Permalink
Use MockNetworkConnection in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mscwilson committed Nov 26, 2024
1 parent c00f3d6 commit d046ec7
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 70 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import android.content.Context
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.snowplowanalytics.core.constants.Parameters
import com.snowplowanalytics.core.constants.TrackerConstants
import com.snowplowanalytics.core.emitter.Executor
import com.snowplowanalytics.core.tracker.TrackerWebViewInterfaceV2
import com.snowplowanalytics.snowplow.Snowplow.createTracker
Expand All @@ -26,8 +27,11 @@ import com.snowplowanalytics.snowplow.configuration.PluginConfiguration
import com.snowplowanalytics.snowplow.configuration.TrackerConfiguration
import com.snowplowanalytics.snowplow.controller.TrackerController
import com.snowplowanalytics.snowplow.network.HttpMethod
import com.snowplowanalytics.snowplow.network.Request
import org.json.JSONException
import org.json.JSONObject
import org.junit.After
import org.junit.Assert
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
Expand All @@ -36,7 +40,7 @@ import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class TrackerWebViewInterfaceV2Test {
private var webInterface: TrackerWebViewInterfaceV2? = null
private val trackedEvents: MutableList<InspectableEvent> = mutableListOf()
private var networkConnection = MockNetworkConnection(HttpMethod.GET, 200)
private var tracker: TrackerController? = null

@Before
Expand All @@ -50,7 +54,6 @@ class TrackerWebViewInterfaceV2Test {
tracker?.pause()
tracker = null
removeAllTrackers()
trackedEvents.clear()
Executor.shutdown()
}

Expand All @@ -71,21 +74,23 @@ class TrackerWebViewInterfaceV2Test {
)

Thread.sleep(200)
waitForEvents(networkConnection, 1)

assertEquals(1, trackedEvents.size)
assertEquals("webViewEvent", trackedEvents.first().name)
assertEquals(1, networkConnection.countRequests())

val request = networkConnection.allRequests[0]
val payload = request.payload.map

val payload = trackedEvents.first().payload
assertEquals("pp", payload[Parameters.EVENT])
assertEquals("webview", payload[Parameters.TRACKER_VERSION])
assertEquals("Firefox", payload[Parameters.USERAGENT])
assertEquals("http://snowplow.com", payload[Parameters.PAGE_URL])
assertEquals("Snowplow", payload[Parameters.PAGE_TITLE])
assertEquals("http://google.com", payload[Parameters.PAGE_REFR])
assertEquals(10, payload[Parameters.PING_XOFFSET_MIN])
assertEquals(20, payload[Parameters.PING_XOFFSET_MAX])
assertEquals(30, payload[Parameters.PING_YOFFSET_MIN])
assertEquals(40, payload[Parameters.PING_YOFFSET_MAX])
assertEquals("10", payload[Parameters.PING_XOFFSET_MIN])
assertEquals("20", payload[Parameters.PING_XOFFSET_MAX])
assertEquals("30", payload[Parameters.PING_YOFFSET_MIN])
assertEquals("40", payload[Parameters.PING_YOFFSET_MAX])
}

@Test
Expand All @@ -103,57 +108,53 @@ class TrackerWebViewInterfaceV2Test {
)

Thread.sleep(200)
waitForEvents(networkConnection, 1)

assertEquals(1, networkConnection.countRequests())

assertEquals(1, trackedEvents.size)
assertEquals("webViewEvent", trackedEvents.first().name)
val request = networkConnection.allRequests[0]
val payload = request.payload.map

val payload = trackedEvents.first().payload
assertEquals("se", payload[Parameters.EVENT])
assertEquals("webview2", payload[Parameters.TRACKER_VERSION])
assertEquals("Firefox", payload[Parameters.USERAGENT])
assertEquals("cat", payload[Parameters.SE_CATEGORY])
assertEquals("act", payload[Parameters.SE_ACTION])
assertEquals("prop", payload[Parameters.SE_PROPERTY])
assertEquals("lbl", payload[Parameters.SE_LABEL])
assertEquals(10.0, payload[Parameters.SE_VALUE])
assertEquals("10.0", payload[Parameters.SE_VALUE])
}

@Test
@Throws(JSONException::class, InterruptedException::class)
fun tracksSelfDescribingEvent() {
val data = "[{\"schema\":\"http://schema.com\",\"data\":{\"key\":\"val\"}}]"
webInterface!!.trackWebViewEvent(
eventName = "ue",
trackerVersion = "webview2",
useragent = "Firefox",
selfDescribingEventData = data
)

Thread.sleep(200)

assertEquals(1, trackedEvents.size)
assertEquals("webViewEvent", trackedEvents.first().name)

val payload = trackedEvents.first().payload
assertEquals(data, payload["changeThis"])
// val data = "[{\"schema\":\"http://schema.com\",\"data\":{\"key\":\"val\"}}]"
// webInterface!!.trackWebViewEvent(
// eventName = "ue",
// trackerVersion = "webview2",
// useragent = "Firefox",
// selfDescribingEventData = data
// )
//
// Thread.sleep(200)
//
// assertEquals(1, trackedEvents.size)
// assertEquals("webViewEvent", trackedEvents.first().name)
//
// val payload = trackedEvents.first().payload
// assertEquals(data, payload["changeThis"])
}

@Test
@Throws(JSONException::class, InterruptedException::class)
fun tracksEventWithCorrectTracker() {
// create the second tracker
val trackedEvents2: MutableList<InspectableEvent> = mutableListOf()
val networkConfig = NetworkConfiguration(MockNetworkConnection(HttpMethod.POST, 200))
val plugin2 = PluginConfiguration("plugin2")
plugin2.afterTrack {
trackedEvents2.add(it)
}
val networkConnection2 = MockNetworkConnection(HttpMethod.GET, 200)
createTracker(
context,
namespace = "ns2",
network = networkConfig,
TrackerConfiguration("appId"),
plugin2
NetworkConfiguration(networkConnection2),
TrackerConfiguration("appId")
)

// track an event using the second tracker
Expand All @@ -165,27 +166,29 @@ class TrackerWebViewInterfaceV2Test {
trackers = arrayOf("ns2")
)
Thread.sleep(200)
waitForEvents(networkConnection2, 1)

assertEquals(0, trackedEvents.size)
assertEquals(1, trackedEvents2.size)
assertEquals(0, networkConnection.countRequests())
assertEquals(1, networkConnection2.countRequests())

// track an event using default tracker if not specified
// tracks using default tracker if not specified
webInterface!!.trackWebViewEvent(
eventName = "pp",
trackerVersion = "webview",
useragent = "Chrome",
pageUrl = "http://snowplow.com",
)
Thread.sleep(200)
waitForEvents(networkConnection, 1)

assertEquals(1, trackedEvents.size)
assertEquals(1, trackedEvents2.size)
assertEquals(1, networkConnection.countRequests())
assertEquals(1, networkConnection2.countRequests())
}

@Test
@Throws(JSONException::class, InterruptedException::class)
fun tracksEventWithEntity() {
val entities = "[{\"schema\":\"http://schema.com\",\"data\":{\"key\":\"val\"}},{\"schema\":\"http://example.com\",\"data\":{\"anotherKey\":\"anotherValue\"}}]"
val entities = "[{\"schema\":\"iglu:com.example/etc\",\"data\":{\"key\":\"val\"}}]"
webInterface!!.trackWebViewEvent(
eventName = "pp",
trackerVersion = "webview",
Expand All @@ -194,44 +197,47 @@ class TrackerWebViewInterfaceV2Test {
entities = entities
)
Thread.sleep(200)
waitForEvents(networkConnection, 1)

assertEquals(1, trackedEvents.size)
val entity1 = trackedEvents.first().entities[0]
val entity2 = trackedEvents.first().entities[1]
assertEquals(1, networkConnection.countRequests())

assertEquals("http://schema.com", entity1.map["schema"] as? String)
assertEquals("val", (entity1.map["data"] as? Map<*, *>)?.get("key"))
assertEquals("http://example.com", entity2.map["schema"] as? String)
assertEquals("anotherValue", (entity2.map["data"] as? Map<*, *>)?.get("anotherKey"))
val relevantEntities = ArrayList<JSONObject>()
val allEntities = JSONObject(networkConnection.allRequests[0].payload.map["co"] as String)
.getJSONArray("data")
for (i in 0 until allEntities.length()) {
if (allEntities.getJSONObject(i).getString("schema") == "iglu:com.example/etc") {
relevantEntities.add(allEntities.getJSONObject(i).getJSONObject("data"))
}
}
assertEquals(1, relevantEntities.size)
assertEquals("val", relevantEntities[0].get("key") as? String)
}


// --- PRIVATE
private val context: Context
get() = InstrumentationRegistry.getInstrumentation().targetContext

private fun createTracker(): TrackerController {
val namespace = "ns" + Math.random().toString()
val networkConfig = NetworkConfiguration(MockNetworkConnection(HttpMethod.POST, 200))
val trackerConfig = TrackerConfiguration("appId")
.installAutotracking(false)
.lifecycleAutotracking(false)
.platformContext(false)
.base64encoding(false)

val plugin = PluginConfiguration("plugin")
plugin.afterTrack {
if (namespace == this.tracker?.namespace) {
trackedEvents.add(it)
}
}

return createTracker(
context,
namespace = namespace,
network = networkConfig,
trackerConfig,
plugin
"ns${Math.random()}",
NetworkConfiguration(networkConnection),
trackerConfig
)
}

@Throws(Exception::class)
fun waitForEvents(networkConnection: MockNetworkConnection, eventsExpected: Int) {
var i = 0
while (i < 10 && networkConnection.countRequests() == eventsExpected - 1) {
Thread.sleep(1000)
i++
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
package com.snowplowanalytics.core.event

import com.snowplowanalytics.core.constants.Parameters
import com.snowplowanalytics.snowplow.event.AbstractPrimitive
import com.snowplowanalytics.snowplow.event.AbstractEvent

/**
* A PageView event. This event has been designed for web trackers, and is not suitable for mobile apps.
Expand All @@ -36,7 +36,7 @@ class WebViewReader(
val pingXOffsetMax: Int? = null,
val pingYOffsetMin: Int? = null,
val pingYOffsetMax: Int? = null
) : AbstractPrimitive() {
) : AbstractEvent() {


// Public methods
Expand All @@ -46,7 +46,9 @@ class WebViewReader(
payload[Parameters.EVENT] = eventName
payload[Parameters.TRACKER_VERSION] = trackerVersion
payload[Parameters.USERAGENT] = useragent
if (selfDescribingEventData != null) payload["changeThis"] = selfDescribingEventData

if (selfDescribingEventData != null) payload["selfDescribingEventData"] = selfDescribingEventData

if (pageUrl != null) payload[Parameters.PAGE_URL] = pageUrl
if (pageTitle != null) payload[Parameters.PAGE_TITLE] = pageTitle
if (referrer != null) payload[Parameters.PAGE_REFR] = referrer
Expand All @@ -62,6 +64,4 @@ class WebViewReader(
return payload
}

override val name: String
get() = "webViewEvent"
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ package com.snowplowanalytics.core.tracker

import com.snowplowanalytics.core.constants.Parameters
import com.snowplowanalytics.core.constants.TrackerConstants
import com.snowplowanalytics.core.event.WebViewReader
import com.snowplowanalytics.core.statemachine.StateMachineEvent
import com.snowplowanalytics.core.statemachine.TrackerState
import com.snowplowanalytics.core.statemachine.TrackerStateSnapshot
Expand All @@ -39,6 +40,7 @@ class TrackerEvent @JvmOverloads constructor(event: Event, state: TrackerStateSn
var trueTimestamp: Long?
var isPrimitive = false
var isService: Boolean
var isWebView = false

init {
entities = event.entities.toMutableList()
Expand All @@ -56,7 +58,11 @@ class TrackerEvent @JvmOverloads constructor(event: Event, state: TrackerStateSn
}

isService = event is TrackerError
if (event is AbstractPrimitive) {
if (event is WebViewReader) {
name = payload[Parameters.EVENT]?.toString()
isPrimitive = true
isWebView = true
} else if (event is AbstractPrimitive) {
name = event.name
isPrimitive = true
} else {
Expand Down

0 comments on commit d046ec7

Please sign in to comment.