diff --git a/build.gradle b/build.gradle
index 3b94e35..dbafdc0 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,5 +1,5 @@
buildscript {
- ext.kotlin_version = '1.8.10'
+ ext.kotlin_version = '2.0.20'
if (!project.hasProperty('version') || project.version.equals('unspecified')) {
project.version = '+'
}
@@ -9,8 +9,9 @@ buildscript {
mavenLocal()
mavenCentral()
}
+
dependencies {
- classpath 'com.android.tools.build:gradle:7.4.1'
+ classpath 'com.android.tools.build:gradle:8.1.4'
classpath 'com.mparticle:android-kit-plugin:' + project.version
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
@@ -18,7 +19,7 @@ buildscript {
plugins {
id "org.sonarqube" version "3.5.0.2730"
- id "org.jlleitschuh.gradle.ktlint" version "11.2.0"
+ id "org.jlleitschuh.gradle.ktlint" version "13.0.0"
}
sonarqube {
@@ -30,13 +31,29 @@ sonarqube {
}
apply plugin: 'org.jlleitschuh.gradle.ktlint'
-apply plugin: 'com.mparticle.kit'
apply plugin: 'kotlin-android'
+apply plugin: 'com.mparticle.kit'
android {
+ namespace 'com.mparticle.kits.optimizely'
+ buildFeatures {
+ buildConfig = true
+ }
defaultConfig {
minSdkVersion 16
}
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_17
+ targetCompatibility JavaVersion.VERSION_17
+ }
+ kotlinOptions {
+ jvmTarget = '17'
+ }
+ testOptions {
+ unitTests.all {
+ jvmArgs += ['--add-opens', 'java.base/java.lang=ALL-UNNAMED']
+ }
+ }
}
dependencies {
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index ae04661..e1bef7e 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
diff --git a/src/main/AndroidManifest.xml b/src/main/AndroidManifest.xml
index 00a39a6..c4e6c98 100644
--- a/src/main/AndroidManifest.xml
+++ b/src/main/AndroidManifest.xml
@@ -1,2 +1 @@
-
+
diff --git a/src/main/kotlin/com/mparticle/kits/OptimizelyKit.kt b/src/main/kotlin/com/mparticle/kits/OptimizelyKit.kt
index cb0015f..4368c4e 100644
--- a/src/main/kotlin/com/mparticle/kits/OptimizelyKit.kt
+++ b/src/main/kotlin/com/mparticle/kits/OptimizelyKit.kt
@@ -13,26 +13,34 @@ import com.optimizely.ab.android.sdk.OptimizelyClient
import com.optimizely.ab.android.sdk.OptimizelyManager
import com.optimizely.ab.android.sdk.OptimizelyStartListener
import java.math.BigDecimal
-import java.util.*
+import java.util.ArrayList
+import java.util.HashMap
+import java.util.LinkedList
+import java.util.Queue
-open class OptimizelyKit : KitIntegration(), KitIntegration.EventListener, CommerceListener,
+open class OptimizelyKit :
+ KitIntegration(),
+ KitIntegration.EventListener,
+ CommerceListener,
OptimizelyStartListener {
@JvmField
val mEventQueue: Queue = LinkedList()
- override fun getName(): String = KIT_NAME
+ override fun getName(): String = KIT_NAME
@Throws(IllegalArgumentException::class)
public override fun onKitCreate(
map: Map,
- context: Context
+ context: Context,
): List {
val sdkKey = map[PROJECT_ID]
val eventInterval = tryParse(map[EVENT_INTERVAL])
val datafileDownloadInterval = tryParse(map[DATAFILE_INTERVAL])
if (!providedClient && (mOptimizelyClient == null || !mOptimizelyClient!!.isValid)) {
- val builder = OptimizelyManager.builder()
- .withSDKKey(sdkKey)
+ val builder =
+ OptimizelyManager
+ .builder()
+ .withSDKKey(sdkKey)
if (eventInterval != null) {
builder.withEventDispatchInterval(eventInterval)
}
@@ -47,19 +55,19 @@ open class OptimizelyKit : KitIntegration(), KitIntegration.EventListener, Comme
override fun setOptOut(b: Boolean): List = emptyList()
-
override fun leaveBreadcrumb(s: String): List = emptyList()
-
- override fun logError(s: String, map: Map): List = emptyList()
+ override fun logError(
+ s: String,
+ map: Map,
+ ): List = emptyList()
override fun logException(
e: Exception,
map: Map,
- s: String
+ s: String,
): List = emptyList()
-
override fun logEvent(mpEvent: MPEvent): List? {
val user = currentUser
var customUserId: String? = null
@@ -76,39 +84,44 @@ open class OptimizelyKit : KitIntegration(), KitIntegration.EventListener, Comme
}
val optimizelyCustomUserId = customUserId
val optimizelyValueString = valueString
- val eventCreated = getOptimizelyEvent(mpEvent, user, object : OptimizelyEventCallback {
- override fun onOptimizelyEventCreated(event: OptimizelyEvent) {
- if (!MPUtility.isEmpty(optimizelyValueString)) {
- try {
- val value = optimizelyValueString!!.toDouble()
- event.addEventAttribute("value", value)
- Logger.debug(
- String.format(
- "Applying custom value: \"%s\" to Optimizely Event based on customFlag",
- value.toString()
- )
- )
- } catch (ex: NumberFormatException) {
- Logger.error(
- String.format(
- "Unable to log Optimizely Value \"%s\", failed to parse as a Double",
- optimizelyValueString
+ val eventCreated =
+ getOptimizelyEvent(
+ mpEvent,
+ user,
+ object : OptimizelyEventCallback {
+ override fun onOptimizelyEventCreated(event: OptimizelyEvent) {
+ if (!MPUtility.isEmpty(optimizelyValueString)) {
+ try {
+ val value = optimizelyValueString!!.toDouble()
+ event.addEventAttribute("value", value)
+ Logger.debug(
+ String.format(
+ "Applying custom value: \"%s\" to Optimizely Event based on customFlag",
+ value.toString(),
+ ),
+ )
+ } catch (ex: NumberFormatException) {
+ Logger.error(
+ String.format(
+ "Unable to log Optimizely Value \"%s\", failed to parse as a Double",
+ optimizelyValueString,
+ ),
+ )
+ }
+ }
+ if (!MPUtility.isEmpty(optimizelyCustomUserId)) {
+ event.userId = optimizelyCustomUserId
+ Logger.debug(
+ String.format(
+ "Applying custom userId: \"%s\" to Optimizely Event based on customFlag",
+ optimizelyCustomUserId,
+ ),
)
- )
+ }
+ logOptimizelyEvent(event)
}
- }
- if (!MPUtility.isEmpty(optimizelyCustomUserId)) {
- event.userId = optimizelyCustomUserId
- Logger.debug(
- String.format(
- "Applying custom userId: \"%s\" to Optimizely Event based on customFlag",
- optimizelyCustomUserId
- )
- )
- }
- logOptimizelyEvent(event)
- }
- })
+ },
+ )
return if (!eventCreated) {
null
} else {
@@ -116,16 +129,18 @@ open class OptimizelyKit : KitIntegration(), KitIntegration.EventListener, Comme
}
}
- override fun logScreen(s: String, map: Map): List = emptyList()
+ override fun logScreen(
+ s: String,
+ map: Map,
+ ): List = emptyList()
override fun logLtvIncrease(
bigDecimal: BigDecimal,
bigDecimal1: BigDecimal,
s: String,
- map: Map
+ map: Map,
): List = emptyList()
-
override fun logEvent(commerceEvent: CommerceEvent): List {
val user = currentUser
var customEventName: String? = null
@@ -150,76 +165,84 @@ open class OptimizelyKit : KitIntegration(), KitIntegration.EventListener, Comme
val optimizelyCustomUserId = customUserId
val optimizelyValueString = valueString
for (event in events) {
- getOptimizelyEvent(event, user, object : OptimizelyEventCallback {
- override fun onOptimizelyEventCreated(optimizelyEvent: OptimizelyEvent) {
- //If the event is a Purchase or Refund expanded event
- if (commerceEvent.productAction != null && event.eventName == String.format(
- CommerceEventUtils.PLUSONE_NAME,
- commerceEvent.productAction
- )
- ) {
- //parse and apply the "revenue"
- val totalAmountString =
- event.customAttributeStrings?.get(CommerceEventUtils.Constants.ATT_TOTAL)
- if (!MPUtility.isEmpty(totalAmountString)) {
- try {
- val totalAmount = java.lang.Double.valueOf(totalAmountString)
- val revenueInCents =
- java.lang.Double.valueOf(totalAmount * 100).toInt()
- optimizelyEvent.eventAttributes?.set("revenue", revenueInCents)
+ getOptimizelyEvent(
+ event,
+ user,
+ object : OptimizelyEventCallback {
+ override fun onOptimizelyEventCreated(optimizelyEvent: OptimizelyEvent) {
+ // If the event is a Purchase or Refund expanded event
+ if (commerceEvent.productAction != null &&
+ event.eventName ==
+ String.format(
+ CommerceEventUtils.PLUSONE_NAME,
+ commerceEvent.productAction,
+ )
+ ) {
+ // parse and apply the "revenue"
+ val totalAmountString =
+ event.customAttributeStrings?.get(CommerceEventUtils.Constants.ATT_TOTAL)
+ if (!MPUtility.isEmpty(totalAmountString)) {
+ try {
+ val totalAmount = java.lang.Double.valueOf(totalAmountString)
+ val revenueInCents =
+ java.lang.Double
+ .valueOf(totalAmount * 100)
+ .toInt()
+ optimizelyEvent.eventAttributes?.set("revenue", revenueInCents)
+ Logger.debug(
+ String.format(
+ "Applying revenue: \"%s\" to Optimizely Event based on transactionAttributes",
+ revenueInCents,
+ ),
+ )
+ } catch (ex: NumberFormatException) {
+ Logger.error("Unable to parse Revenue value")
+ }
+ }
+ // And apply the custom name, if there is one
+ if (optimizelyCustomEventName != null) {
+ optimizelyEvent.eventName = optimizelyCustomEventName
Logger.debug(
String.format(
- "Applying revenue: \"%s\" to Optimizely Event based on transactionAttributes",
- revenueInCents
- )
+ "Applying custom eventName: \"%s\" to Optimizely Event based on customFlag",
+ optimizelyCustomEventName,
+ ),
)
- } catch (ex: NumberFormatException) {
- Logger.error("Unable to parse Revenue value")
}
}
- //And apply the custom name, if there is one
- if (optimizelyCustomEventName != null) {
- optimizelyEvent.eventName = optimizelyCustomEventName
+ // Apply customId, if there is one, to all expanded events
+ if (optimizelyCustomUserId != null) {
+ optimizelyEvent.userId = optimizelyCustomUserId
Logger.debug(
String.format(
- "Applying custom eventName: \"%s\" to Optimizely Event based on customFlag",
- optimizelyCustomEventName
- )
+ "Applying custom userId: \"%s\" to Optimizely Event based on customFlag",
+ optimizelyCustomUserId,
+ ),
)
}
- }
- //Apply customId, if there is one, to all expanded events
- if (optimizelyCustomUserId != null) {
- optimizelyEvent.userId = optimizelyCustomUserId
- Logger.debug(
- String.format(
- "Applying custom userId: \"%s\" to Optimizely Event based on customFlag",
- optimizelyCustomUserId
- )
- )
- }
- if (!MPUtility.isEmpty(optimizelyValueString)) {
- try {
- val value = optimizelyValueString?.toDouble()
- optimizelyEvent.addEventAttribute("value", value)
- Logger.debug(
- String.format(
- "Applying custom value: \"%s\" to Optimizely Event based on customFlag",
- value
+ if (!MPUtility.isEmpty(optimizelyValueString)) {
+ try {
+ val value = optimizelyValueString?.toDouble()
+ optimizelyEvent.addEventAttribute("value", value)
+ Logger.debug(
+ String.format(
+ "Applying custom value: \"%s\" to Optimizely Event based on customFlag",
+ value,
+ ),
)
- )
- } catch (ex: NumberFormatException) {
- Logger.error(
- String.format(
- "Unable to log Optimizely Value \"%s\", failed to parse as a Double",
- optimizelyValueString
+ } catch (ex: NumberFormatException) {
+ Logger.error(
+ String.format(
+ "Unable to log Optimizely Value \"%s\", failed to parse as a Double",
+ optimizelyValueString,
+ ),
)
- )
+ }
}
+ logOptimizelyEvent(optimizelyEvent)
}
- logOptimizelyEvent(optimizelyEvent)
- }
- })
+ },
+ )
}
return listOf(ReportingMessage.fromEvent(this, commerceEvent))
}
@@ -231,7 +254,7 @@ open class OptimizelyKit : KitIntegration(), KitIntegration.EventListener, Comme
}
override fun onStart(optimizelyClient: OptimizelyClient) {
- //check providedClient, so we don't override a client that the was set explicitly
+ // check providedClient, so we don't override a client that the was set explicitly
if (!providedClient && optimizelyClient.isValid) {
mOptimizelyClient = optimizelyClient
for (listener in mStartListeners) {
@@ -251,14 +274,14 @@ open class OptimizelyKit : KitIntegration(), KitIntegration.EventListener, Comme
mOptimizelyClient?.track(
trackEvent.eventName!!,
trackEvent.userId!!,
- trackEvent.userAttributes!!
+ trackEvent.userAttributes!!,
)
} else {
mOptimizelyClient?.track(
trackEvent.eventName!!,
trackEvent.userId!!,
trackEvent.userAttributes!!,
- trackEvent.eventAttributes!!
+ trackEvent.eventAttributes!!,
)
}
} else {
@@ -272,19 +295,19 @@ open class OptimizelyKit : KitIntegration(), KitIntegration.EventListener, Comme
val userIdField = settings[USER_ID_FIELD_KEY]
if (USER_ID_CUSTOMER_ID_VALUE.equals(userIdField, true)) {
userId = user.userIdentities[MParticle.IdentityType.CustomerId]
- } else if (USER_ID_EMAIL_VALUE.equals(userIdField, true)) {
+ } else if (USER_ID_EMAIL_VALUE.equals(userIdField, true)) {
userId = user.userIdentities[MParticle.IdentityType.Email]
- } else if (USER_ID_OTHER_VALUE.equals(userIdField, true)) {
+ } else if (USER_ID_OTHER_VALUE.equals(userIdField, true)) {
userId = user.userIdentities[MParticle.IdentityType.Other]
- } else if (USER_ID_OTHER2_VALUE.equals(userIdField, true)) {
+ } else if (USER_ID_OTHER2_VALUE.equals(userIdField, true)) {
userId = user.userIdentities[MParticle.IdentityType.Other2]
- } else if (USER_ID_OTHER3_VALUE.equals(userIdField, true)) {
+ } else if (USER_ID_OTHER3_VALUE.equals(userIdField, true)) {
userId = user.userIdentities[MParticle.IdentityType.Other3]
- } else if (USER_ID_OTHER4_VALUE.equals(userIdField, true)) {
+ } else if (USER_ID_OTHER4_VALUE.equals(userIdField, true)) {
userId = user.userIdentities[MParticle.IdentityType.Other4]
} else if (USER_ID_MPID_VALUE.equals(userIdField, true)) {
userId = user.id.toString()
- } else if (USER_ID_DAS_VALUE.equals(userIdField, true)) {
+ } else if (USER_ID_DAS_VALUE.equals(userIdField, true)) {
userId = MParticle.getInstance()!!.Identity().deviceApplicationStamp
}
}
@@ -298,31 +321,32 @@ open class OptimizelyKit : KitIntegration(), KitIntegration.EventListener, Comme
private fun getOptimizelyEvent(
mpEvent: MPEvent,
user: MParticleUser?,
- onEventCreated: OptimizelyEventCallback
- ): Boolean {
- return if (!MPUtility.isEmpty(getUserId(user))) {
- val listener: TypedUserAttributeListener = object : TypedUserAttributeListener {
- override fun onUserAttributesReceived(
- userAttributes: Map,
- map1: Map?>,
- mpid: Long
- ) {
- val attributes: MutableMap = HashMap()
- for ((key, value) in userAttributes) {
- attributes[key] = value
- }
- val event: OptimizelyEvent = OptimizelyEvent()
- val eventName = mpEvent.eventName
- val userId = getUserId(user)
- event.eventName = eventName
- event.userId = userId
- event.userAttributes = attributes
- if (mpEvent.customAttributes != null) {
- event.eventAttributes = mpEvent.customAttributes?.let { HashMap(it) }
+ onEventCreated: OptimizelyEventCallback,
+ ): Boolean =
+ if (!MPUtility.isEmpty(getUserId(user))) {
+ val listener: TypedUserAttributeListener =
+ object : TypedUserAttributeListener {
+ override fun onUserAttributesReceived(
+ userAttributes: Map,
+ map1: Map?>,
+ mpid: Long,
+ ) {
+ val attributes: MutableMap = HashMap()
+ for ((key, value) in userAttributes) {
+ attributes[key] = value
+ }
+ val event: OptimizelyEvent = OptimizelyEvent()
+ val eventName = mpEvent.eventName
+ val userId = getUserId(user)
+ event.eventName = eventName
+ event.userId = userId
+ event.userAttributes = attributes
+ if (mpEvent.customAttributes != null) {
+ event.eventAttributes = mpEvent.customAttributes?.let { HashMap(it) }
+ }
+ onEventCreated.onOptimizelyEventCreated(event)
}
- onEventCreated.onOptimizelyEventCreated(event)
}
- }
if (user != null) {
user.getUserAttributes(listener)
} else {
@@ -332,7 +356,6 @@ open class OptimizelyKit : KitIntegration(), KitIntegration.EventListener, Comme
} else {
false
}
- }
private fun queueEvent(event: OptimizelyEvent) {
mEventQueue.offer(event)
@@ -347,24 +370,30 @@ open class OptimizelyKit : KitIntegration(), KitIntegration.EventListener, Comme
}
}
- private fun tryParse(value: String?): Long? {
- return try {
+ private fun tryParse(value: String?): Long? =
+ try {
value!!.toLong()
} catch (e: Exception) {
null
}
- }
inner class OptimizelyEvent {
@JvmField
var eventName: String? = null
+
@JvmField
var userId: String? = null
+
@JvmField
var userAttributes: Map? = null
+
@JvmField
var eventAttributes: MutableMap? = null
- fun addEventAttribute(key: String, value: Any?) {
+
+ fun addEventAttribute(
+ key: String,
+ value: Any?,
+ ) {
if (eventAttributes == null) {
eventAttributes = HashMap()
}
@@ -399,7 +428,8 @@ open class OptimizelyKit : KitIntegration(), KitIntegration.EventListener, Comme
const val OPTIMIZELY_VALUE_KEY = "Optimizely.Value"
const val OPTIMIZELY_EVENT_NAME = "Optimizely.EventName"
const val OPTIMIZELY_USER_ID = "Optimizely.UserId"
- const val KIT_NAME = "Optimizely"
+ const val KIT_NAME = "Optimizely"
+
@JvmStatic
var optimizelyClient: OptimizelyClient?
get() = mOptimizelyClient
@@ -421,4 +451,4 @@ open class OptimizelyKit : KitIntegration(), KitIntegration.EventListener, Comme
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/test/kotlin/com/mparticle/kits/OptimizelyKitTest.kt b/src/test/kotlin/com/mparticle/kits/OptimizelyKitTests.kt
similarity index 61%
rename from src/test/kotlin/com/mparticle/kits/OptimizelyKitTest.kt
rename to src/test/kotlin/com/mparticle/kits/OptimizelyKitTests.kt
index 92be702..5b8a2ab 100644
--- a/src/test/kotlin/com/mparticle/kits/OptimizelyKitTest.kt
+++ b/src/test/kotlin/com/mparticle/kits/OptimizelyKitTests.kt
@@ -1,7 +1,11 @@
package com.mparticle.kits
-import com.mparticle.*
+import com.mparticle.MPEvent
+import com.mparticle.MParticle
import com.mparticle.MParticle.IdentityType
+import com.mparticle.TypedUserAttributeListener
+import com.mparticle.UserAttributeListener
+import com.mparticle.UserAttributeListenerType
import com.mparticle.audience.AudienceResponse
import com.mparticle.audience.AudienceTask
import com.mparticle.commerce.CommerceEvent
@@ -23,12 +27,14 @@ import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito
-import java.util.*
+import java.util.HashMap
+import java.util.Random
+import java.util.UUID
class OptimizelyKitTests {
var randomUtils = RandomUtils()
private val kit: KitIntegration
- get() = OptimizelyKit()
+ get() = OptimizelyKit()
@Before
fun before() {
@@ -99,47 +105,46 @@ class OptimizelyKitTests {
val product1 = Product.Builder("product1", "1234", 0.0).build()
val product2 = Product.Builder("product2", "9876", 1.0).build()
val product3 = Product.Builder("product3", "3333", 300.0).build()
- val commerceEvent = CommerceEvent.Builder(Product.ADD_TO_CART, product1)
- .addProduct(product2)
- .addProduct(product3)
- .build()
+ val commerceEvent =
+ CommerceEvent
+ .Builder(Product.ADD_TO_CART, product1)
+ .addProduct(product2)
+ .addProduct(product3)
+ .build()
val mpid = Random().nextLong()
val customerId = randomUtils.getAlphaNumericString(20)
val email = randomUtils.getAlphaNumericString(10)
val identities: MutableMap = HashMap()
identities[IdentityType.CustomerId] = customerId
identities[IdentityType.Email] = email
- val user: MParticleUser = object : EmptyMParticleUser() {
- override fun getUserIdentities(): Map {
- return identities
- }
+ val user: MParticleUser =
+ object : EmptyMParticleUser() {
+ override fun getUserIdentities(): Map = identities
- override fun getId(): Long {
- return mpid
+ override fun getId(): Long = mpid
}
- }
Mockito.`when`(MParticle.getInstance()?.Identity()?.currentUser).thenReturn(user)
val expectedUserId = Mutable("")
val count = Mutable(0)
val settings = Mutable(JSONObject())
- val optimizelyKit: OptimizelyKit = object : OptimizelyKit() {
- override fun logOptimizelyEvent(trackEvent: OptimizelyEvent) {
- count.value++
- Assert.assertEquals(expectedUserId.value, trackEvent.userId)
- }
-
- override fun getConfiguration(): KitConfiguration? {
- return try {
- MockKitConfiguration.createKitConfiguration(
- JSONObject()
- .put("id", MParticle.ServiceProviders.OPTIMIZELY)
- .put("as", settings.value)
- )
- } catch (e: JSONException) {
- null
+ val optimizelyKit: OptimizelyKit =
+ object : OptimizelyKit() {
+ override fun logOptimizelyEvent(trackEvent: OptimizelyEvent) {
+ count.value++
+ Assert.assertEquals(expectedUserId.value, trackEvent.userId)
}
+
+ override fun getConfiguration(): KitConfiguration? =
+ try {
+ MockKitConfiguration.createKitConfiguration(
+ JSONObject()
+ .put("id", MParticle.ServiceProviders.OPTIMIZELY)
+ .put("as", settings.value),
+ )
+ } catch (e: JSONException) {
+ null
+ }
}
- }
val expectedEventCount = CommerceEventUtils.expand(commerceEvent).size
settings.value =
JSONObject().put(OptimizelyKit.USER_ID_FIELD_KEY, OptimizelyKit.USER_ID_EMAIL_VALUE)
@@ -147,10 +152,11 @@ class OptimizelyKitTests {
optimizelyKit.logEvent(commerceEvent)
Assert.assertEquals(expectedEventCount, count.value)
count.value = 0
- settings.value = JSONObject().put(
- OptimizelyKit.USER_ID_FIELD_KEY,
- OptimizelyKit.USER_ID_CUSTOMER_ID_VALUE
- )
+ settings.value =
+ JSONObject().put(
+ OptimizelyKit.USER_ID_FIELD_KEY,
+ OptimizelyKit.USER_ID_CUSTOMER_ID_VALUE,
+ )
expectedUserId.value = customerId
optimizelyKit.logEvent(commerceEvent)
Assert.assertEquals(expectedEventCount, count.value)
@@ -170,20 +176,20 @@ class OptimizelyKitTests {
Assert.assertEquals(expectedEventCount, count.value)
count.value = 0
- //test default, should be das
+ // test default, should be das
settings.value = JSONObject()
expectedUserId.value = das
optimizelyKit.logEvent(commerceEvent)
- //Don't log events if there is no userId type present
+ // Don't log events if there is no userId type present
Assert.assertEquals(3, count.value.toLong())
count.value = 0
Mockito.`when`(MParticle.getInstance()!!.Identity().currentUser).thenReturn(null)
- //test default when no user is present, default to das
+ // test default when no user is present, default to das
settings.value = JSONObject()
expectedUserId.value = das
optimizelyKit.logEvent(MPEvent.Builder("an event", MParticle.EventType.Location).build())
optimizelyKit.logEvent(commerceEvent)
- //log events with das if there is no userId type present
+ // log events with das if there is no userId type present
Assert.assertEquals(4, count.value.toLong())
}
@@ -209,16 +215,17 @@ class OptimizelyKitTests {
fun testLogEventNoCustom() {
val event = MPEvent.Builder("An event", MParticle.EventType.Location).build()
val called = Mutable(false)
- val optimizelyKit: OptimizelyKit = object : MockOptimizelyKit() {
- override fun logOptimizelyEvent(trackEvent: OptimizelyEvent) {
- if (called.value) {
- Assert.fail("multiple events, expecting 1")
+ val optimizelyKit: OptimizelyKit =
+ object : MockOptimizelyKit() {
+ override fun logOptimizelyEvent(trackEvent: OptimizelyEvent) {
+ if (called.value) {
+ Assert.fail("multiple events, expecting 1")
+ }
+ Assert.assertEquals(trackEvent.eventName, "An event")
+ Assert.assertNull(trackEvent.eventAttributes)
+ called.value = true
}
- Assert.assertEquals(trackEvent.eventName, "An event")
- Assert.assertNull(trackEvent.eventAttributes)
- called.value = true
}
- }
optimizelyKit.logEvent(event)
Assert.assertTrue(called.value)
}
@@ -230,38 +237,43 @@ class OptimizelyKitTests {
@Test
fun testCommerceEventNoCustom() {
val userAttributes = randomUtils.getRandomAttributes(4)
- val user: MParticleUser = object : EmptyMParticleUser() {
- override fun getUserAttributes(userAttributeListener: UserAttributeListenerType?): Map? {
- (userAttributeListener as TypedUserAttributeListener?)!!.onUserAttributesReceived(
- HashMap(userAttributes),
- HashMap(),
- 1L
- )
- return null
+ val user: MParticleUser =
+ object : EmptyMParticleUser() {
+ override fun getUserAttributes(userAttributeListener: UserAttributeListenerType?): Map? {
+ (userAttributeListener as TypedUserAttributeListener?)!!.onUserAttributesReceived(
+ HashMap(userAttributes),
+ HashMap(),
+ 1L,
+ )
+ return null
+ }
}
- }
Mockito.`when`(MParticle.getInstance()!!.Identity().currentUser).thenReturn(user)
val product1 = Product.Builder("product1", "1234", 0.0).build()
val product2 = Product.Builder("product2", "9876", 1.0).build()
val product3 = Product.Builder("product3", "3333", 300.0).build()
- val commerceEvent = CommerceEvent.Builder(Product.ADD_TO_CART, product1)
- .addProduct(product2)
- .addProduct(product3)
- .build()
+ val commerceEvent =
+ CommerceEvent
+ .Builder(Product.ADD_TO_CART, product1)
+ .addProduct(product2)
+ .addProduct(product3)
+ .build()
val expectedCount = CommerceEventUtils.expand(commerceEvent).size
val count = Mutable(0)
- val optimizelyKit: OptimizelyKit = object : MockOptimizelyKit() {
- override fun logOptimizelyEvent(trackEvent: OptimizelyEvent) {
- count.value++
- Assert.assertEquals(
- String.format(
- "eCommerce - %s - Item",
- commerceEvent.productAction
- ), trackEvent.eventName
- )
- Assert.assertEquals(userAttributes, trackEvent.userAttributes)
+ val optimizelyKit: OptimizelyKit =
+ object : MockOptimizelyKit() {
+ override fun logOptimizelyEvent(trackEvent: OptimizelyEvent) {
+ count.value++
+ Assert.assertEquals(
+ String.format(
+ "eCommerce - %s - Item",
+ commerceEvent.productAction,
+ ),
+ trackEvent.eventName,
+ )
+ Assert.assertEquals(userAttributes, trackEvent.userAttributes)
+ }
}
- }
optimizelyKit.logEvent(commerceEvent)
Assert.assertEquals(expectedCount.toLong(), count.value.toLong())
}
@@ -272,16 +284,17 @@ class OptimizelyKitTests {
@Test
fun testCommerceEventRevenue() {
val userAttributes = randomUtils.getRandomAttributes(4)
- val user: MParticleUser = object : EmptyMParticleUser() {
- override fun getUserAttributes(userAttributeListener: UserAttributeListenerType?): Map? {
- (userAttributeListener as TypedUserAttributeListener?)!!.onUserAttributesReceived(
- HashMap(userAttributes),
- HashMap(),
- 1L
- )
- return null
+ val user: MParticleUser =
+ object : EmptyMParticleUser() {
+ override fun getUserAttributes(userAttributeListener: UserAttributeListenerType?): Map? {
+ (userAttributeListener as TypedUserAttributeListener?)!!.onUserAttributesReceived(
+ HashMap(userAttributes),
+ HashMap(),
+ 1L,
+ )
+ return null
+ }
}
- }
Mockito.`when`(MParticle.getInstance()!!.Identity().currentUser).thenReturn(user)
val customAttributes = randomUtils.getRandomAttributes(3)
customAttributes[OptimizelyKit.OPTIMIZELY_EVENT_NAME] = "myCustomName1"
@@ -293,44 +306,48 @@ class OptimizelyKitTests {
Product.Builder("product2", "9876", 1.0).customAttributes(customAttributes1).build()
val product3 = Product.Builder("product3", "3333", 300.0).build()
val transactionAttributes = TransactionAttributes("999").setRevenue(45.5)
- val commerceEvent = CommerceEvent.Builder(Product.PURCHASE, product1)
- .transactionAttributes(transactionAttributes)
- .addProduct(product2)
- .addProduct(product3)
- .build()
+ val commerceEvent =
+ CommerceEvent
+ .Builder(Product.PURCHASE, product1)
+ .transactionAttributes(transactionAttributes)
+ .addProduct(product2)
+ .addProduct(product3)
+ .build()
val count = Mutable(0)
val revenueEventFound = Mutable(false)
- val optimizelyKit: OptimizelyKit = object : MockOptimizelyKit() {
- override fun logOptimizelyEvent(trackEvent: OptimizelyEvent) {
- count.value++
- if (String.format(
- CommerceEventUtils.PLUSONE_NAME,
- commerceEvent.productAction
- ) == trackEvent.eventName
- ) {
- //make sure it is our revenue * 100 (we our dollars, they are cents)
- Assert.assertEquals(
- trackEvent.eventAttributes!!["revenue"].toString().toDouble(),
- 4550.0,
- 0.0
- )
- Assert.assertFalse(revenueEventFound.value)
- revenueEventFound.value = true
- } else {
- Assert.assertEquals(
- String.format(
- "eCommerce - %s - Item",
- commerceEvent.productAction
- ), trackEvent.eventName
- )
+ val optimizelyKit: OptimizelyKit =
+ object : MockOptimizelyKit() {
+ override fun logOptimizelyEvent(trackEvent: OptimizelyEvent) {
+ count.value++
+ if (String.format(
+ CommerceEventUtils.PLUSONE_NAME,
+ commerceEvent.productAction,
+ ) == trackEvent.eventName
+ ) {
+ // make sure it is our revenue * 100 (we our dollars, they are cents)
+ Assert.assertEquals(
+ trackEvent.eventAttributes!!["revenue"].toString().toDouble(),
+ 4550.0,
+ 0.0,
+ )
+ Assert.assertFalse(revenueEventFound.value)
+ revenueEventFound.value = true
+ } else {
+ Assert.assertEquals(
+ String.format(
+ "eCommerce - %s - Item",
+ commerceEvent.productAction,
+ ),
+ trackEvent.eventName,
+ )
+ }
+ Assert.assertEquals(userAttributes, trackEvent.userAttributes)
}
- Assert.assertEquals(userAttributes, trackEvent.userAttributes)
}
- }
optimizelyKit.logEvent(commerceEvent)
Assert.assertEquals(
CommerceEventUtils.expand(commerceEvent).size.toLong(),
- count.value.toLong()
+ count.value.toLong(),
)
Assert.assertTrue(revenueEventFound.value)
}
@@ -343,47 +360,53 @@ class OptimizelyKitTests {
val eventName = "custom name"
val product1 = Product.Builder("product1", "1234", 0.0).build()
val transactionAttributes = TransactionAttributes("999").setRevenue(20.5)
- val commerceEvent = CommerceEvent.Builder(Product.PURCHASE, product1)
- .transactionAttributes(transactionAttributes)
- .addCustomFlag(OptimizelyKit.OPTIMIZELY_EVENT_NAME, eventName)
- .build()
+ val commerceEvent =
+ CommerceEvent
+ .Builder(Product.PURCHASE, product1)
+ .transactionAttributes(transactionAttributes)
+ .addCustomFlag(OptimizelyKit.OPTIMIZELY_EVENT_NAME, eventName)
+ .build()
val count = Mutable(0)
val customNameFound = Mutable(false)
- val optimizelyKit: OptimizelyKit = object : MockOptimizelyKit() {
- override fun logOptimizelyEvent(trackEvent: OptimizelyEvent) {
- count.value++
- if (trackEvent.eventName == eventName) {
- Assert.assertEquals(
- trackEvent.eventAttributes!!["revenue"].toString().toFloat(),
- 2050f,
- 0f
- )
- Assert.assertFalse(customNameFound.value)
- customNameFound.value = true
+ val optimizelyKit: OptimizelyKit =
+ object : MockOptimizelyKit() {
+ override fun logOptimizelyEvent(trackEvent: OptimizelyEvent) {
+ count.value++
+ if (trackEvent.eventName == eventName) {
+ Assert.assertEquals(
+ trackEvent.eventAttributes!!["revenue"].toString().toFloat(),
+ 2050f,
+ 0f,
+ )
+ Assert.assertFalse(customNameFound.value)
+ customNameFound.value = true
+ }
}
}
- }
optimizelyKit.logEvent(commerceEvent)
Assert.assertEquals(
CommerceEventUtils.expand(commerceEvent).size.toLong(),
- count.value.toLong()
+ count.value.toLong(),
)
Assert.assertTrue(customNameFound.value)
}
@Test
fun testCustomValue() {
- val randomEvent = MPEvent.Builder(TestingUtils.getInstance().randomMPEventRich)
- .addCustomFlag(OptimizelyKit.OPTIMIZELY_VALUE_KEY, "40.1")
- .build()
+ val randomEvent =
+ MPEvent
+ .Builder(TestingUtils.getInstance().randomMPEventRich)
+ .addCustomFlag(OptimizelyKit.OPTIMIZELY_VALUE_KEY, "40.1")
+ .build()
val eventFound = Mutable(false)
- val optimizelyKit: OptimizelyKit = object : MockOptimizelyKit() {
- override fun logOptimizelyEvent(trackEvent: OptimizelyEvent) {
- Assert.assertFalse(eventFound.value)
- eventFound.value = true
- Assert.assertEquals((trackEvent.eventAttributes?.get("value") as Double), 40.1, 0.0)
+ val optimizelyKit: OptimizelyKit =
+ object : MockOptimizelyKit() {
+ override fun logOptimizelyEvent(trackEvent: OptimizelyEvent) {
+ Assert.assertFalse(eventFound.value)
+ eventFound.value = true
+ Assert.assertEquals((trackEvent.eventAttributes?.get("value") as Double), 40.1, 0.0)
+ }
}
- }
optimizelyKit.logEvent(randomEvent)
Assert.assertTrue(eventFound.value)
}
@@ -395,25 +418,30 @@ class OptimizelyKitTests {
@Test
fun testQueueWorking() {
val userAttributes = randomUtils.getRandomAttributes(4)
- val user: MParticleUser = object : EmptyMParticleUser() {
- override fun getUserAttributes(userAttributeListener: UserAttributeListenerType?): Map? {
- (userAttributeListener as TypedUserAttributeListener?)!!.onUserAttributesReceived(
- HashMap(userAttributes),
- HashMap(),
- 1L
- )
- return null
+ val user: MParticleUser =
+ object : EmptyMParticleUser() {
+ override fun getUserAttributes(userAttributeListener: UserAttributeListenerType?): Map? {
+ (userAttributeListener as TypedUserAttributeListener?)!!.onUserAttributesReceived(
+ HashMap(userAttributes),
+ HashMap(),
+ 1L,
+ )
+ return null
+ }
}
- }
Mockito.`when`(MParticle.getInstance()!!.Identity().currentUser).thenReturn(user)
val product1 = Product.Builder("product1", "1234", 0.0).build()
val product2 = Product.Builder("product2", "9876", 1.0).build()
val product3 = Product.Builder("product3", "3333", 300.0).build()
- val commerceEvent = CommerceEvent.Builder(Product.ADD_TO_CART, product1)
- .build()
- val commerceEvent1 = CommerceEvent.Builder(Product.CLICK, product2)
- .addProduct(product3)
- .build()
+ val commerceEvent =
+ CommerceEvent
+ .Builder(Product.ADD_TO_CART, product1)
+ .build()
+ val commerceEvent1 =
+ CommerceEvent
+ .Builder(Product.CLICK, product2)
+ .addProduct(product3)
+ .build()
val optimizelyKit: OptimizelyKit = MockOptimizelyKit()
optimizelyKit.logEvent(commerceEvent)
optimizelyKit.logEvent(commerceEvent1)
@@ -424,14 +452,17 @@ class OptimizelyKitTests {
Mockito.`when`(optimizelyClient.isValid).thenReturn(false)
optimizelyKit.onStart(optimizelyClient)
- //Events should NOT be dequeued if the OptimizelyClient is not valid
+ // Events should NOT be dequeued if the OptimizelyClient is not valid
Assert.assertEquals(expectedEvents.toLong(), optimizelyKit.mEventQueue.size.toLong())
var count = invocationCount(optimizelyClient, "track")
Assert.assertEquals(0, count.toLong())
Mockito.`when`(optimizelyClient.isValid).thenReturn(true)
optimizelyKit.onStart(optimizelyClient)
Mockito.verify(optimizelyClient, Mockito.times(expectedEvents)).track(
- Mockito.anyString(), Mockito.anyString(), Mockito.any>(), Mockito.any>()
+ Mockito.anyString(),
+ Mockito.anyString(),
+ Mockito.any>(),
+ Mockito.any>(),
)
count = invocationCount(optimizelyClient, "track")
Assert.assertEquals(expectedEvents.toLong(), count.toLong())
@@ -440,19 +471,21 @@ class OptimizelyKitTests {
@Test
fun testCustomUserId() {
- val event = MPEvent.Builder("Event Name", MParticle.EventType.Search)
- .addCustomFlag(OptimizelyKit.OPTIMIZELY_USER_ID, "44").build()
+ val event =
+ MPEvent
+ .Builder("Event Name", MParticle.EventType.Search)
+ .addCustomFlag(OptimizelyKit.OPTIMIZELY_USER_ID, "44")
+ .build()
val count = Mutable(0)
- val optimizelyKit: OptimizelyKit = object : MockOptimizelyKit() {
- override fun getUserId(user: MParticleUser?): String {
- return "should not be this userId"
- }
+ val optimizelyKit: OptimizelyKit =
+ object : MockOptimizelyKit() {
+ override fun getUserId(user: MParticleUser?): String = "should not be this userId"
- override fun logOptimizelyEvent(trackEvent: OptimizelyEvent) {
- count.value++
- Assert.assertEquals("44", trackEvent.userId)
+ override fun logOptimizelyEvent(trackEvent: OptimizelyEvent) {
+ count.value++
+ Assert.assertEquals("44", trackEvent.userId)
+ }
}
- }
optimizelyKit.logEvent(event)
Assert.assertEquals(1, count.value.toLong())
count.value = 0
@@ -460,12 +493,14 @@ class OptimizelyKitTests {
val product1 = Product.Builder("My Other Product", "2356", 2.0).build()
val impression = Impression("name", product).addProduct(product1)
val transactionAttributes = TransactionAttributes("123").setRevenue(43.2)
- val commerceEvent = CommerceEvent.Builder(Product.DETAIL, product)
- .addProduct(product1)
- .addImpression(impression)
- .addCustomFlag(OptimizelyKit.OPTIMIZELY_USER_ID, "44")
- .transactionAttributes(transactionAttributes) // .addPromotion(promotion)
- .build()
+ val commerceEvent =
+ CommerceEvent
+ .Builder(Product.DETAIL, product)
+ .addProduct(product1)
+ .addImpression(impression)
+ .addCustomFlag(OptimizelyKit.OPTIMIZELY_USER_ID, "44")
+ .transactionAttributes(transactionAttributes) // .addPromotion(promotion)
+ .build()
optimizelyKit.logEvent(commerceEvent)
Assert.assertEquals(4, count.value.toLong())
}
@@ -484,7 +519,10 @@ class OptimizelyKitTests {
optimizelyKit.onKitCreate(minimalSettings, MockContext())
}
- private fun invocationCount(`object`: Any, methodName: String): Int {
+ private fun invocationCount(
+ `object`: Any,
+ methodName: String,
+ ): Int {
val invocationList = Mockito.mockingDetails(`object`).invocations
var invocationCount = 0
for (invocation in invocationList) {
@@ -496,40 +534,40 @@ class OptimizelyKitTests {
}
internal open inner class MockOptimizelyKit : OptimizelyKit() {
- override fun getConfiguration(): KitConfiguration? {
- return try {
+ override fun getConfiguration(): KitConfiguration? =
+ try {
MockKitConfiguration.createKitConfiguration(
JSONObject()
.put("id", MParticle.ServiceProviders.OPTIMIZELY)
- .put("as", JSONObject().put(USER_ID_FIELD_KEY, USER_ID_MPID_VALUE))
+ .put("as", JSONObject().put(USER_ID_FIELD_KEY, USER_ID_MPID_VALUE)),
)
} catch (e: JSONException) {
null
}
- }
}
- class Mutable(var value: T)
+ class Mutable(
+ var value: T,
+ )
+
internal open inner class EmptyMParticleUser : MParticleUser {
- override fun getId(): Long {
- return 1L
- }
+ override fun getId(): Long = 1L
- override fun getUserAttributes(): Map {
- return HashMap()
- }
+ override fun getUserAttributes(): Map = HashMap()
override fun getUserAttributes(userAttributeListener: UserAttributeListenerType?): Map? {
if (userAttributeListener is TypedUserAttributeListener) {
userAttributeListener.onUserAttributesReceived(
- HashMap(), HashMap(),
- id
+ HashMap(),
+ HashMap(),
+ id,
)
}
if (userAttributeListener is UserAttributeListener) {
userAttributeListener.onUserAttributesReceived(
- HashMap(), HashMap(),
- id
+ HashMap(),
+ HashMap(),
+ id,
)
}
return null
@@ -539,11 +577,20 @@ class OptimizelyKitTests {
override fun getUserIdentities(): Map = mapOf()
- override fun setUserAttribute(s: String, o: Any): Boolean = false
+ override fun setUserAttribute(
+ s: String,
+ o: Any,
+ ): Boolean = false
- override fun setUserAttributeList(s: String, o: Any): Boolean = false
+ override fun setUserAttributeList(
+ s: String,
+ o: Any,
+ ): Boolean = false
- override fun incrementUserAttribute(s: String, i: Number): Boolean = false
+ override fun incrementUserAttribute(
+ s: String,
+ i: Number,
+ ): Boolean = false
override fun removeUserAttribute(s: String): Boolean = false
@@ -558,9 +605,7 @@ class OptimizelyKitTests {
override fun getFirstSeenTime(): Long = 0
override fun getLastSeenTime(): Long = 0
- override fun getUserAudiences(): AudienceTask {
- throw NotImplementedError("getUserAudiences() is not implemented")
- }
+ override fun getUserAudiences(): AudienceTask = throw NotImplementedError("getUserAudiences() is not implemented")
}
-}
\ No newline at end of file
+}