diff --git a/build.gradle b/build.gradle index c7cdce7..b00ecfc 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,6 @@ buildscript { - if (!project.hasProperty('version') || project.version == 'unspecified') { + ext.kotlin_version = '2.0.20' + if (!project.hasProperty('version') || project.version.equals('unspecified')) { project.version = '+' } @@ -9,15 +10,15 @@ buildscript { 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:2.0.20' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } 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 { @@ -29,16 +30,29 @@ sonarqube { } apply plugin: 'org.jlleitschuh.gradle.ktlint' -apply plugin: "kotlin-android" +apply plugin: 'kotlin-android' apply plugin: 'com.mparticle.kit' android { + namespace 'com.mparticle.kits.appboy' + buildFeatures { + buildConfig = true + } defaultConfig { minSdkVersion 21 } + lint { + // Workaround for lint internal crash + abortOnError false + // Ignore obsolete custom lint checks from older fragment library + disable 'ObsoleteLintCustomCheck' + } compileOptions { - sourceCompatibility 1.8 - targetCompatibility 1.8 + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + kotlinOptions { + jvmTarget = '17' } testOptions { unitTests.all { diff --git a/gradle.properties b/gradle.properties index 0b6a43f..56fb79f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,4 +1,4 @@ android.enableJetifier=true android.useAndroidX=true org.gradle.daemon=true -org.gradle.jvmargs=-Xmx2560m + 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 2afcbba..c4e6c98 100644 --- a/src/main/AndroidManifest.xml +++ b/src/main/AndroidManifest.xml @@ -1,2 +1 @@ - + diff --git a/src/main/kotlin/com/mparticle/kits/AppboyKit.kt b/src/main/kotlin/com/mparticle/kits/AppboyKit.kt index 70ce4e2..c44edcf 100644 --- a/src/main/kotlin/com/mparticle/kits/AppboyKit.kt +++ b/src/main/kotlin/com/mparticle/kits/AppboyKit.kt @@ -5,12 +5,15 @@ import android.app.Application.ActivityLifecycleCallbacks import android.content.Context import android.content.Intent import android.os.Handler -import android.util.Log import com.braze.Braze import com.braze.BrazeActivityLifecycleCallbackListener import com.braze.BrazeUser import com.braze.configuration.BrazeConfig -import com.braze.enums.* +import com.braze.enums.BrazeSdkMetadata +import com.braze.enums.Gender +import com.braze.enums.Month +import com.braze.enums.NotificationSubscriptionType +import com.braze.enums.SdkFlavor import com.braze.events.IValueCallback import com.braze.models.outgoing.BrazeProperties import com.braze.push.BrazeFirebaseMessagingService @@ -28,21 +31,34 @@ import com.mparticle.consent.ConsentState import com.mparticle.identity.MParticleUser import com.mparticle.internal.Logger import com.mparticle.kits.CommerceEventUtils.OnAttributeExtracted -import com.mparticle.kits.KitIntegration.* +import com.mparticle.kits.KitIntegration.AttributeListener +import com.mparticle.kits.KitIntegration.CommerceListener +import com.mparticle.kits.KitIntegration.EventListener +import com.mparticle.kits.KitIntegration.IdentityListener +import com.mparticle.kits.KitIntegration.PushListener +import com.mparticle.kits.KitIntegration.UserAttributeListener import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.math.BigDecimal import java.text.SimpleDateFormat -import java.util.* +import java.util.Calendar +import java.util.Date +import java.util.EnumSet +import java.util.LinkedList import kotlin.collections.HashMap /** * mParticle client-side Appboy integration */ -open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, - KitIntegration.EventListener, PushListener, IdentityListener, KitIntegration.UserAttributeListener { - +open class AppboyKit : + KitIntegration(), + AttributeListener, + CommerceListener, + KitIntegration.EventListener, + PushListener, + IdentityListener, + KitIntegration.UserAttributeListener { var enableTypeDetection = false var bundleCommerceEvents = false var isMpidIdentityType = false @@ -53,18 +69,16 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, private var forwardScreenViews = false private lateinit var updatedInstanceId: String - override fun getName() = NAME - public override fun onKitCreate( settings: Map, - context: Context + context: Context, ): List? { val key = settings[APPBOY_KEY] require(!KitUtils.isEmpty(key)) { "Braze key is empty." } - //try to get endpoint from the host setting + // try to get endpoint from the host setting val authority = settings[HOST] if (!KitUtils.isEmpty(authority)) { setAuthority(authority) @@ -86,25 +100,31 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, } } forwardScreenViews = settings[FORWARD_SCREEN_VIEWS].toBoolean() - subscriptionGroupIds = settings[SUBSCRIPTION_GROUP_MAPPING]?.let { - getSubscriptionGroupIds(it) - } + subscriptionGroupIds = + settings[SUBSCRIPTION_GROUP_MAPPING] + ?.let { + getSubscriptionGroupIds(it) + } if (key != null) { - val config = BrazeConfig.Builder().setApiKey(key) - .setSdkFlavor(SdkFlavor.MPARTICLE) - .setSdkMetadata(EnumSet.of(BrazeSdkMetadata.MPARTICLE)) - .build() + val config = + BrazeConfig + .Builder() + .setApiKey(key) + .setSdkFlavor(SdkFlavor.MPARTICLE) + .setSdkMetadata(EnumSet.of(BrazeSdkMetadata.MPARTICLE)) + .build() Braze.configure(context, config) } - dataFlushRunnable = Runnable { - if (kitManager.isBackgrounded) { - Braze.getInstance(getContext()).requestImmediateDataFlush() + dataFlushRunnable = + Runnable { + if (kitManager.isBackgrounded) { + Braze.getInstance(getContext()).requestImmediateDataFlush() + } } - } queueDataFlush() if (setDefaultAppboyLifecycleCallbackListener) { (context.applicationContext as Application).registerActivityLifecycleCallbacks( - BrazeActivityLifecycleCallbackListener() as ActivityLifecycleCallbacks + BrazeActivityLifecycleCallbackListener() as ActivityLifecycleCallbacks, ) } setIdentityType(settings) @@ -137,13 +157,13 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, override fun logError( message: String, - errorAttributes: Map + errorAttributes: Map, ): List = emptyList() override fun logException( exception: Exception, exceptionAttributes: Map, - message: String + message: String, ): List = emptyList() override fun logEvent(event: MPEvent): List { @@ -159,31 +179,35 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, } } Braze.getInstance(context).logCustomEvent(event.eventName, properties) - Braze.getInstance(context).getCurrentUser(object : IValueCallback { - override fun onSuccess(value: BrazeUser) { - val userAttributeSetter = UserAttributeSetter(value, enableTypeDetection) - event.customAttributeStrings?.let { it -> - for ((key, attributeValue) in it) { - val hashedKey = - KitUtils.hashForFiltering(event.eventType.value.toString() + event.eventName + key) - - configuration.eventAttributesAddToUser?.get(hashedKey)?.let { - value.addToCustomAttributeArray(it, attributeValue) - } - configuration.eventAttributesRemoveFromUser?.get(hashedKey)?.let { - value.removeFromCustomAttributeArray(it, attributeValue) - } - configuration.eventAttributesSingleItemUser?.get(hashedKey)?.let { - userAttributeSetter.parseValue(it, attributeValue) + Braze + .getInstance(context) + .getCurrentUser( + object : IValueCallback { + override fun onSuccess(value: BrazeUser) { + val userAttributeSetter = UserAttributeSetter(value, enableTypeDetection) + event.customAttributeStrings?.let { it -> + for ((key, attributeValue) in it) { + val hashedKey = + KitUtils.hashForFiltering(event.eventType.value.toString() + event.eventName + key) + + configuration.eventAttributesAddToUser?.get(hashedKey)?.let { + value.addToCustomAttributeArray(it, attributeValue) + } + configuration.eventAttributesRemoveFromUser?.get(hashedKey)?.let { + value.removeFromCustomAttributeArray(it, attributeValue) + } + configuration.eventAttributesSingleItemUser?.get(hashedKey)?.let { + userAttributeSetter.parseValue(it, attributeValue) + } + } } } - } - } - override fun onError() { - Logger.warning("unable to acquire user to add or remove custom user attributes from events") - } - }) + override fun onError() { + Logger.warning("unable to acquire user to add or remove custom user attributes from events") + } + }, + ) } queueDataFlush() return listOf(ReportingMessage.fromEvent(this, event).setAttributes(newAttributes)) @@ -191,9 +215,9 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, override fun logScreen( screenName: String, - screenAttributes: Map? - ): List { - return if (forwardScreenViews) { + screenAttributes: Map?, + ): List = + if (forwardScreenViews) { if (screenAttributes == null) { Braze.getInstance(context).logCustomEvent(screenName) } else { @@ -211,20 +235,19 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, this, ReportingMessage.MessageType.SCREEN_VIEW, System.currentTimeMillis(), - screenAttributes - ) + screenAttributes, + ), ) messages } else { emptyList() } - } override fun logLtvIncrease( valueIncreased: BigDecimal, valueTotal: BigDecimal, eventName: String, - contextInfo: Map + contextInfo: Map, ): List = emptyList() override fun logEvent(event: CommerceEvent): List { @@ -232,8 +255,9 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, if (!KitUtils.isEmpty(event.productAction) && event.productAction.equals( Product.PURCHASE, - true - ) && !event.products.isNullOrEmpty() + true, + ) && + !event.products.isNullOrEmpty() ) { if (bundleCommerceEvents) { logOrderLevelTransaction(event) @@ -275,96 +299,109 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, return messages } - override fun setUserAttribute(keyIn: String, attributeValue: String) { + override fun setUserAttribute( + keyIn: String, + attributeValue: String, + ) { var key = keyIn - Braze.getInstance(context).getCurrentUser(object : IValueCallback { - override fun onSuccess(value: BrazeUser) { - val userAttributeSetter = UserAttributeSetter(value, enableTypeDetection) - - when (key) { - UserAttributes.CITY -> value.setHomeCity(attributeValue) - UserAttributes.COUNTRY -> value.setCountry(attributeValue) - UserAttributes.FIRSTNAME -> value.setFirstName(attributeValue) - UserAttributes.LASTNAME -> value.setLastName(attributeValue) - UserAttributes.MOBILE_NUMBER -> value.setPhoneNumber(attributeValue) - UserAttributes.ZIPCODE -> value.setCustomUserAttribute("Zip", attributeValue) - UserAttributes.AGE -> { - val calendar = getCalendarMinusYears(attributeValue) - if (calendar != null) { - value.setDateOfBirth(calendar[Calendar.YEAR], Month.JANUARY, 1) - } else { - Logger.warning("unable to set DateOfBirth for " + UserAttributes.AGE + " = " + value) - } - } - EMAIL_SUBSCRIBE -> { - when (attributeValue) { - OPTED_IN -> value.setEmailNotificationSubscriptionType(NotificationSubscriptionType.OPTED_IN) - UNSUBSCRIBED -> value.setEmailNotificationSubscriptionType(NotificationSubscriptionType.UNSUBSCRIBED) - SUBSCRIBED -> value.setEmailNotificationSubscriptionType(NotificationSubscriptionType.SUBSCRIBED) - else -> { - Logger.warning("unable to set email_subscribe with invalid value: " + value) - } - } - } - PUSH_SUBSCRIBE -> { - when (attributeValue) { - OPTED_IN -> value.setPushNotificationSubscriptionType(NotificationSubscriptionType.OPTED_IN) - UNSUBSCRIBED -> value.setPushNotificationSubscriptionType(NotificationSubscriptionType.UNSUBSCRIBED) - SUBSCRIBED -> value.setPushNotificationSubscriptionType(NotificationSubscriptionType.SUBSCRIBED) - else -> { - Logger.warning("unable to set push_subscribe with invalid value: " + value) + Braze + .getInstance(context) + .getCurrentUser( + object : IValueCallback { + override fun onSuccess(value: BrazeUser) { + val userAttributeSetter = UserAttributeSetter(value, enableTypeDetection) + + when (key) { + UserAttributes.CITY -> value.setHomeCity(attributeValue) + UserAttributes.COUNTRY -> value.setCountry(attributeValue) + UserAttributes.FIRSTNAME -> value.setFirstName(attributeValue) + UserAttributes.LASTNAME -> value.setLastName(attributeValue) + UserAttributes.MOBILE_NUMBER -> value.setPhoneNumber(attributeValue) + UserAttributes.ZIPCODE -> value.setCustomUserAttribute("Zip", attributeValue) + UserAttributes.AGE -> { + val calendar = getCalendarMinusYears(attributeValue) + if (calendar != null) { + value.setDateOfBirth(calendar[Calendar.YEAR], Month.JANUARY, 1) + } else { + Logger.warning("unable to set DateOfBirth for " + UserAttributes.AGE + " = " + value) + } } - } - } - DOB -> useDobString(attributeValue, value) - UserAttributes.GENDER -> { - if (attributeValue.contains("fe")) value.setGender(Gender.FEMALE) - else value.setGender(Gender.MALE) - } - else -> { - if (subscriptionGroupIds?.containsKey(key) == true) { - val groupId = subscriptionGroupIds?.get(key) - when (attributeValue.lowercase()) { - "true" -> { - groupId?.let { value.addToSubscriptionGroup(it) } + EMAIL_SUBSCRIBE -> { + when (attributeValue) { + OPTED_IN -> value.setEmailNotificationSubscriptionType(NotificationSubscriptionType.OPTED_IN) + UNSUBSCRIBED -> value.setEmailNotificationSubscriptionType(NotificationSubscriptionType.UNSUBSCRIBED) + SUBSCRIBED -> value.setEmailNotificationSubscriptionType(NotificationSubscriptionType.SUBSCRIBED) + else -> { + Logger.warning("unable to set email_subscribe with invalid value: " + value) + } } - - "false" -> { - groupId?.let { value.removeFromSubscriptionGroup(it) } + } + PUSH_SUBSCRIBE -> { + when (attributeValue) { + OPTED_IN -> value.setPushNotificationSubscriptionType(NotificationSubscriptionType.OPTED_IN) + UNSUBSCRIBED -> value.setPushNotificationSubscriptionType(NotificationSubscriptionType.UNSUBSCRIBED) + SUBSCRIBED -> value.setPushNotificationSubscriptionType(NotificationSubscriptionType.SUBSCRIBED) + else -> { + Logger.warning("unable to set push_subscribe with invalid value: " + value) + } } - - else -> { - Logger.warning( - "Unable to set Subscription Group ID for user attribute: $key due to invalid value data type. Expected Boolean." - ) + } + DOB -> useDobString(attributeValue, value) + UserAttributes.GENDER -> { + if (attributeValue.contains("fe")) { + value.setGender(Gender.FEMALE) + } else { + value.setGender(Gender.MALE) } } - } else { - if (key.startsWith("$")) { - key = key.substring(1) + else -> { + if (subscriptionGroupIds?.containsKey(key) == true) { + val groupId = subscriptionGroupIds?.get(key) + when (attributeValue.lowercase()) { + "true" -> { + groupId?.let { value.addToSubscriptionGroup(it) } + } + + "false" -> { + groupId?.let { value.removeFromSubscriptionGroup(it) } + } + + else -> { + Logger.warning( + "Unable to set Subscription Group ID for user attribute: $key due to invalid value data type. Expected Boolean.", + ) + } + } + } else { + if (key.startsWith("$")) { + key = key.substring(1) + } + userAttributeSetter?.parseValue(key, attributeValue) + } } - userAttributeSetter?.parseValue(key, attributeValue) } + queueDataFlush() } - } - queueDataFlush() - } - override fun onError() { - Logger.warning("unable to set key: " + key + " with value: " + attributeValue) - } - }) + override fun onError() { + Logger.warning("unable to set key: " + key + " with value: " + attributeValue) + } + }, + ) } // Expected Date Format @"yyyy'-'MM'-'dd" - private fun useDobString(value: String, user: BrazeUser) { + private fun useDobString( + value: String, + user: BrazeUser, + ) { val dateFormat = SimpleDateFormat("yyyy-MM-dd") try { val calendar = Calendar.getInstance() calendar.time = dateFormat.parse(value) as Date val year = calendar[Calendar.YEAR] val monthNum = calendar[Calendar.MONTH] - val month = Month.values()[monthNum]// + val month = Month.values()[monthNum] // val day = calendar[Calendar.DAY_OF_MONTH] user.setDateOfBirth(year, month, day) } catch (e: Exception) { @@ -372,56 +409,74 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, } } - override fun setUserAttributeList(key: String, list: List) { - Braze.getInstance(context).getCurrentUser(object : IValueCallback { - override fun onSuccess(value: BrazeUser) { - val array = list.toTypedArray() - value.setCustomAttributeArray(key, array) - queueDataFlush() - } + override fun setUserAttributeList( + key: String, + list: List, + ) { + Braze + .getInstance(context) + .getCurrentUser( + object : IValueCallback { + override fun onSuccess(value: BrazeUser) { + val array = list.toTypedArray() + value.setCustomAttributeArray(key, array) + queueDataFlush() + } - override fun onError() { - Logger.warning("unable to set key: " + key + " with User Attribute List: " + list) - } - }) + override fun onError() { + Logger.warning("unable to set key: " + key + " with User Attribute List: " + list) + } + }, + ) } override fun onIncrementUserAttribute( key: String?, incrementedBy: Number?, value: String?, - user: FilteredMParticleUser? + user: FilteredMParticleUser?, ) { } - override fun onRemoveUserAttribute(key: String?, user: FilteredMParticleUser?) { + override fun onRemoveUserAttribute( + key: String?, + user: FilteredMParticleUser?, + ) { } - override fun onSetUserAttribute(key: String?, value: Any?, user: FilteredMParticleUser?) { + override fun onSetUserAttribute( + key: String?, + value: Any?, + user: FilteredMParticleUser?, + ) { } - override fun onSetUserTag(key: String?, user: FilteredMParticleUser?) { + override fun onSetUserTag( + key: String?, + user: FilteredMParticleUser?, + ) { } override fun onSetUserAttributeList( attributeKey: String?, attributeValueList: MutableList?, - user: FilteredMParticleUser? + user: FilteredMParticleUser?, ) { } override fun onSetAllUserAttributes( userAttributes: MutableMap?, userAttributeLists: MutableMap>?, - user: FilteredMParticleUser? + user: FilteredMParticleUser?, ) { } override fun supportsAttributeLists(): Boolean = true + override fun onConsentStateUpdated( oldState: ConsentState, newState: ConsentState, - user: FilteredMParticleUser + user: FilteredMParticleUser, ) { setConsent(newState) } @@ -429,7 +484,7 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, private fun setConsent(consentState: ConsentState) { val clientConsentSettings = parseToNestedMap(consentState.toString()) - parseConsentMapping(settings[consentMappingSDK]).iterator().forEach { currentConsent -> + parseConsentMapping(settings[CONSENT_MAPPING_SDK]).iterator().forEach { currentConsent -> val isConsentAvailable = searchKeyInNestedMap(clientConsentSettings, key = currentConsent.key) @@ -438,29 +493,39 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, JSONObject(isConsentAvailable.toString()).opt("consented") as Boolean when (currentConsent.value) { - "google_ad_user_data" -> setConsentValueToBraze( - KEY_GOOGLE_AD_USER_DATA, isConsentGranted - ) - - "google_ad_personalization" -> setConsentValueToBraze( - KEY_GOOGLE_AD_PERSONALIZATION, isConsentGranted - ) - + "google_ad_user_data" -> + setConsentValueToBraze( + KEY_GOOGLE_AD_USER_DATA, + isConsentGranted, + ) + + "google_ad_personalization" -> + setConsentValueToBraze( + KEY_GOOGLE_AD_PERSONALIZATION, + isConsentGranted, + ) } } } } - private fun setConsentValueToBraze(key: String, value: Boolean) { - Braze.getInstance(context).getCurrentUser(object : IValueCallback { - override fun onSuccess(brazeUser: BrazeUser) { - brazeUser.setCustomUserAttribute(key, value) - } + private fun setConsentValueToBraze( + key: String, + value: Boolean, + ) { + Braze + .getInstance(context) + .getCurrentUser( + object : IValueCallback { + override fun onSuccess(brazeUser: BrazeUser) { + brazeUser.setCustomUserAttribute(key, value) + } - override fun onError() { - super.onError() - } - }) + override fun onError() { + super.onError() + } + }, + ) } private fun parseConsentMapping(json: String?): Map { @@ -481,7 +546,10 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, } } } catch (jse: JSONException) { - Logger.warning(jse, "The Braze kit threw an exception while searching for the configured consent purpose mapping in the current user's consent status.") + Logger.warning( + jse, + "The Braze kit threw an exception while searching for the configured consent purpose mapping in the current user's consent status.", + ) emptyMap() } } @@ -505,7 +573,10 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, return topLevelMap } - private fun searchKeyInNestedMap(map: Map<*, *>, key: Any): Any? { + private fun searchKeyInNestedMap( + map: Map<*, *>, + key: Any, + ): Any? { if (map.isNullOrEmpty()) { return null } @@ -522,7 +593,10 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, } } } catch (e: Exception) { - Logger.error(e, "The Braze kit threw an exception while searching for the configured consent purpose mapping in the current user's consent status.") + Logger.error( + e, + "The Braze kit threw an exception while searching for the configured consent purpose mapping in the current user's consent status.", + ) } return null } @@ -537,7 +611,7 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, */ override fun setAllUserAttributes( attributes: Map, - attributeLists: Map> + attributeLists: Map>, ) { if (!kitPreferences.getBoolean(PREF_KEY_HAS_SYNCED_ATTRIBUTES, false)) { for ((key, value) in attributes) { @@ -552,78 +626,105 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, override fun removeUserAttribute(keyIn: String) { var key = keyIn - Braze.getInstance(context).getCurrentUser(object : IValueCallback { - override fun onSuccess(value: BrazeUser) { - if (UserAttributes.CITY == key) { - value.setHomeCity(null) - } else if (UserAttributes.COUNTRY == key) { - value.setCountry(null) - } else if (UserAttributes.FIRSTNAME == key) { - value.setFirstName(null) - } //else if (UserAttributes.GENDER == key) { //Braze SDK wont allow for gender parameter to be null. - // user.setGender(null)} - else if (UserAttributes.LASTNAME == key) { - value.setLastName(null) - } else if (UserAttributes.MOBILE_NUMBER == key) { - value.setPhoneNumber(null) - } else { - if (key.startsWith("$")) { - key = key.substring(1) + Braze + .getInstance(context) + .getCurrentUser( + object : IValueCallback { + override fun onSuccess(value: BrazeUser) { + if (UserAttributes.CITY == key) { + value.setHomeCity(null) + } else if (UserAttributes.COUNTRY == key) { + value.setCountry(null) + } else if (UserAttributes.FIRSTNAME == key) { + value.setFirstName(null) + } else if (UserAttributes.LASTNAME == key) { + value.setLastName(null) + } else if (UserAttributes.MOBILE_NUMBER == key) { + value.setPhoneNumber(null) + } else { + if (key.startsWith("$")) { + key = key.substring(1) + } + value.unsetCustomUserAttribute(key) + } + queueDataFlush() } - value.unsetCustomUserAttribute(key) - } - queueDataFlush() - } - override fun onError() { - Logger.warning("unable to remove User Attribute with key: " + key) - } - }) + override fun onError() { + Logger.warning("unable to remove User Attribute with key: " + key) + } + }, + ) } - override fun setUserIdentity(identityType: IdentityType, identity: String) {} + override fun setUserIdentity( + identityType: IdentityType, + identity: String, + ) {} + override fun removeUserIdentity(identityType: IdentityType) {} + override fun logout(): List = emptyList() - fun logTransaction(event: CommerceEvent?, product: Product) { + fun logTransaction( + event: CommerceEvent?, + product: Product, + ) { val purchaseProperties = BrazeProperties() val currency = arrayOfNulls(1) val commerceTypeParser: StringTypeParser = - BrazePropertiesSetter(purchaseProperties, enableTypeDetection) - val onAttributeExtracted: OnAttributeExtracted = object : OnAttributeExtracted { - override fun onAttributeExtracted(key: String, value: String) { - if (!checkCurrency(key, value)) { - commerceTypeParser.parseValue(key, value) + BrazePropertiesSetter( + purchaseProperties, + enableTypeDetection, + ) + val onAttributeExtracted: OnAttributeExtracted = + object : OnAttributeExtracted { + override fun onAttributeExtracted( + key: String, + value: String, + ) { + if (!checkCurrency(key, value)) { + commerceTypeParser.parseValue(key, value) + } } - } - override fun onAttributeExtracted(key: String, value: Double) { - if (!checkCurrency(key, value)) { - purchaseProperties.addProperty(key, value) + override fun onAttributeExtracted( + key: String, + value: Double, + ) { + if (!checkCurrency(key, value)) { + purchaseProperties.addProperty(key, value) + } } - } - override fun onAttributeExtracted(key: String, value: Int) { - purchaseProperties.addProperty(key, value) - } + override fun onAttributeExtracted( + key: String, + value: Int, + ) { + purchaseProperties.addProperty(key, value) + } - override fun onAttributeExtracted(attributes: Map) { - for ((key, value) in attributes) { - if (!checkCurrency(key, value)) { - commerceTypeParser.parseValue(key, value) + override fun onAttributeExtracted(attributes: Map) { + for ((key, value) in attributes) { + if (!checkCurrency(key, value)) { + commerceTypeParser.parseValue(key, value) + } } } - } - private fun checkCurrency(key: String, value: Any?): Boolean { - return if (CommerceEventUtils.Constants.ATT_ACTION_CURRENCY_CODE == key) { - currency[0] = value?.toString() - true - } else { - false - } + private fun checkCurrency( + key: String, + value: Any?, + ): Boolean = + if (CommerceEventUtils.Constants.ATT_ACTION_CURRENCY_CODE == + key + ) { + currency[0] = value?.toString() + true + } else { + false + } } - } CommerceEventUtils.extractActionAttributes(event, onAttributeExtracted) var currencyValue = currency[0] if (KitUtils.isEmpty(currencyValue)) { @@ -639,7 +740,7 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, product.couponCode?.let { purchaseProperties.addProperty( CommerceEventUtils.Constants.ATT_PRODUCT_COUPON_CODE, - it + it, ) } product.brand?.let { @@ -670,7 +771,6 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, } } catch (e: Exception) { Logger.error(e, "The Braze kit threw an exception while searching for forward sku as product name flag.") - } Braze.Companion.getInstance(context).logPurchase( @@ -678,7 +778,7 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, currencyValue, BigDecimal(product.unitPrice), product.quantity.toInt(), - purchaseProperties + purchaseProperties, ) } @@ -686,41 +786,58 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, val properties = BrazeProperties() val currency = arrayOfNulls(1) val commerceTypeParser: StringTypeParser = - BrazePropertiesSetter(properties, enableTypeDetection) - val onAttributeExtracted: OnAttributeExtracted = object : OnAttributeExtracted { - override fun onAttributeExtracted(key: String, value: String) { - if (!checkCurrency(key, value)) { - commerceTypeParser.parseValue(key, value) + BrazePropertiesSetter( + properties, + enableTypeDetection, + ) + val onAttributeExtracted: OnAttributeExtracted = + object : OnAttributeExtracted { + override fun onAttributeExtracted( + key: String, + value: String, + ) { + if (!checkCurrency(key, value)) { + commerceTypeParser.parseValue(key, value) + } } - } - override fun onAttributeExtracted(key: String, value: Double) { - if (!checkCurrency(key, value)) { - properties.addProperty(key, value) + override fun onAttributeExtracted( + key: String, + value: Double, + ) { + if (!checkCurrency(key, value)) { + properties.addProperty(key, value) + } } - } - override fun onAttributeExtracted(key: String, value: Int) { - properties.addProperty(key, value) - } + override fun onAttributeExtracted( + key: String, + value: Int, + ) { + properties.addProperty(key, value) + } - override fun onAttributeExtracted(attributes: Map) { - for ((key, value) in attributes) { - if (!checkCurrency(key, value)) { - commerceTypeParser.parseValue(key, value) + override fun onAttributeExtracted(attributes: Map) { + for ((key, value) in attributes) { + if (!checkCurrency(key, value)) { + commerceTypeParser.parseValue(key, value) + } } } - } - private fun checkCurrency(key: String, value: Any?): Boolean { - return if (CommerceEventUtils.Constants.ATT_ACTION_CURRENCY_CODE == key) { - currency[0] = value?.toString() - true - } else { - false - } + private fun checkCurrency( + key: String, + value: Any?, + ): Boolean = + if (CommerceEventUtils.Constants.ATT_ACTION_CURRENCY_CODE == + key + ) { + currency[0] = value?.toString() + true + } else { + false + } } - } CommerceEventUtils.extractActionAttributes(event, onAttributeExtracted) var currencyValue = currency[0] if (KitUtils.isEmpty(currencyValue)) { @@ -758,39 +875,58 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, currencyValue, event?.transactionAttributes?.revenue?.let { BigDecimal(it) } ?: BigDecimal(0), 1, - properties + properties, ) } else { if (!KitUtils.isEmpty(event?.productAction)) { - Braze.getInstance(context) - .logCustomEvent(String.format(eventName, event?.productAction), properties) + Braze + .getInstance(context) + .logCustomEvent( + String.format(eventName, event?.productAction), + properties, + ) } else if (!KitUtils.isEmpty(event?.promotionAction)) { - Braze.getInstance(context) - .logCustomEvent(String.format(eventName, event?.promotionAction), properties) + Braze + .getInstance(context) + .logCustomEvent( + String.format(eventName, event?.promotionAction), + properties, + ) } else { - Braze.getInstance(context) - .logCustomEvent(String.format(eventName, "Impression"), properties) + Braze + .getInstance(context) + .logCustomEvent( + String.format(eventName, "Impression"), + properties, + ) } } } - override fun willHandlePushMessage(intent: Intent): Boolean { - return if (!(settings[PUSH_ENABLED].toBoolean())) { + override fun willHandlePushMessage(intent: Intent): Boolean = + if (!(settings[PUSH_ENABLED].toBoolean())) { false - } else intent.isBrazePushMessage() - } + } else { + intent.isBrazePushMessage() + } - override fun onPushMessageReceived(context: Context, pushIntent: Intent) { + override fun onPushMessageReceived( + context: Context, + pushIntent: Intent, + ) { if (settings[PUSH_ENABLED].toBoolean()) { BrazeFirebaseMessagingService.handleBrazeRemoteMessage( context, - RemoteMessage(pushIntent.extras) + RemoteMessage(pushIntent.extras), ) } } - override fun onPushRegistration(instanceId: String, senderId: String): Boolean { - return if (settings[PUSH_ENABLED].toBoolean()) { + override fun onPushRegistration( + instanceId: String, + senderId: String, + ): Boolean = + if (settings[PUSH_ENABLED].toBoolean()) { updatedInstanceId = instanceId Braze.getInstance(context).registeredPushToken = instanceId queueDataFlush() @@ -798,39 +934,40 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, } else { false } - } protected open fun setAuthority(authority: String?) { Braze.setEndpointProvider { appboyEndpoint -> - appboyEndpoint.buildUpon() - .authority(authority).build() + appboyEndpoint + .buildUpon() + .authority(authority) + .build() } } override fun onIdentifyCompleted( mParticleUser: MParticleUser, - filteredIdentityApiRequest: FilteredIdentityApiRequest? + filteredIdentityApiRequest: FilteredIdentityApiRequest?, ) { updateUser(mParticleUser) } override fun onLoginCompleted( mParticleUser: MParticleUser, - filteredIdentityApiRequest: FilteredIdentityApiRequest? + filteredIdentityApiRequest: FilteredIdentityApiRequest?, ) { updateUser(mParticleUser) } override fun onLogoutCompleted( mParticleUser: MParticleUser, - filteredIdentityApiRequest: FilteredIdentityApiRequest? + filteredIdentityApiRequest: FilteredIdentityApiRequest?, ) { updateUser(mParticleUser) } override fun onModifyCompleted( mParticleUser: MParticleUser, - filteredIdentityApiRequest: FilteredIdentityApiRequest? + filteredIdentityApiRequest: FilteredIdentityApiRequest?, ) { updateUser(mParticleUser) } @@ -845,12 +982,11 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, fun getIdentity( isMpidIdentityType: Boolean, identityType: IdentityType?, - mParticleUser: MParticleUser? + mParticleUser: MParticleUser?, ): String? { var identity: String? = null if (isMpidIdentityType && mParticleUser != null) { identity = mParticleUser.id.toString() - } else if (identityType != null && mParticleUser != null) { identity = mParticleUser.userIdentities[identityType] } @@ -858,33 +994,44 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, } protected open fun setId(customerId: String) { - Braze.getInstance(context).getCurrentUser(object : IValueCallback { - override fun onSuccess(value: BrazeUser) { - if (value.userId != customerId) { - Braze.getInstance(context).changeUser(customerId) - queueDataFlush() - } - } + Braze + .getInstance(context) + .getCurrentUser( + object : IValueCallback { + override fun onSuccess(value: BrazeUser) { + if (value.userId != customerId) { + Braze.getInstance(context).changeUser(customerId) + queueDataFlush() + } + } - override fun onError() { - Logger.warning("unable to change user to customer ID: " + customerId) - } - }) + override fun onError() { + Logger.warning("unable to change user to customer ID: " + customerId) + } + }, + ) } protected open fun setEmail(email: String) { if (email != kitPreferences.getString(PREF_KEY_CURRENT_EMAIL, null)) { - Braze.getInstance(context).getCurrentUser(object : IValueCallback { - override fun onSuccess(value: BrazeUser) { - value.setEmail(email) - queueDataFlush() - kitPreferences.edit().putString(PREF_KEY_CURRENT_EMAIL, email).apply() - } + Braze + .getInstance(context) + .getCurrentUser( + object : IValueCallback { + override fun onSuccess(value: BrazeUser) { + value.setEmail(email) + queueDataFlush() + kitPreferences + .edit() + .putString(PREF_KEY_CURRENT_EMAIL, email) + .apply() + } - override fun onError() { - Logger.warning("unable to set email with value: " + email) - } - }) + override fun onError() { + Logger.warning("unable to set email with value: " + email) + } + }, + ) } } @@ -894,11 +1041,16 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, } } - fun addToProperties(properties: BrazeProperties, key: String, value: String) { + fun addToProperties( + properties: BrazeProperties, + key: String, + value: String, + ) { try { - if ("true".equals(value, true) || "false".equals( + if ("true".equals(value, true) || + "false".equals( value, - true + true, ) ) { properties.addProperty(key, (value).toBoolean()) @@ -929,15 +1081,14 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, return null } - fun getCalendarMinusYears(years: Int): Calendar? { - return if (years >= 0) { + fun getCalendarMinusYears(years: Int): Calendar? = + if (years >= 0) { val calendar = Calendar.getInstance() calendar[Calendar.YEAR] = calendar[Calendar.YEAR] - years calendar } else { null } - } fun getProductListParameters(productList: List): JSONArray { val productArray = JSONArray() @@ -950,7 +1101,7 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, product.couponCode?.let { productProperties.put( CommerceEventUtils.Constants.ATT_PRODUCT_COUPON_CODE, - it + it, ) } product.brand?.let { @@ -973,15 +1124,15 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, } productProperties.put( CommerceEventUtils.Constants.ATT_PRODUCT_PRICE, - product.unitPrice + product.unitPrice, ) productProperties.put( CommerceEventUtils.Constants.ATT_PRODUCT_QUANTITY, - product.quantity + product.quantity, ) productProperties.put( CommerceEventUtils.Constants.ATT_PRODUCT_TOTAL_AMOUNT, - product.totalAmount + product.totalAmount, ) productArray.put(productProperties) @@ -996,7 +1147,7 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, promotion.creative?.let { promotionProperties.put( CommerceEventUtils.Constants.ATT_PROMOTION_CREATIVE, - it + it, ) } promotion.id?.let { @@ -1008,7 +1159,7 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, promotion.position?.let { promotionProperties.put( CommerceEventUtils.Constants.ATT_PROMOTION_POSITION, - it + it, ) } promotionArray.put(promotionProperties) @@ -1055,15 +1206,22 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, return impressionArray } - internal abstract class StringTypeParser(var enableTypeDetection: Boolean) { - fun parseValue(key: String, value: String): Any { + internal abstract class StringTypeParser( + var enableTypeDetection: Boolean, + ) { + fun parseValue( + key: String, + value: String, + ): Any { if (!enableTypeDetection) { toString(key, value) return value } - return if (true.toString().equals(value, true) || false.toString().equals( + return if ( + true.toString().equals(value, true) || + false.toString().equals( value, - true + true, ) ) { val newBool = (value).toBoolean() @@ -1093,59 +1251,108 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, } } - abstract fun toInt(key: String, value: Int) - abstract fun toLong(key: String, value: Long) - abstract fun toDouble(key: String, value: Double) - abstract fun toBoolean(key: String, value: Boolean) - abstract fun toString(key: String, value: String) + abstract fun toInt( + key: String, + value: Int, + ) + + abstract fun toLong( + key: String, + value: Long, + ) + + abstract fun toDouble( + key: String, + value: Double, + ) + + abstract fun toBoolean( + key: String, + value: Boolean, + ) + + abstract fun toString( + key: String, + value: String, + ) } internal inner class BrazePropertiesSetter( private var properties: BrazeProperties, - enableTypeDetection: Boolean + enableTypeDetection: Boolean, ) : StringTypeParser(enableTypeDetection) { - override fun toInt(key: String, value: Int) { + override fun toInt( + key: String, + value: Int, + ) { properties.addProperty(key, value) } - override fun toLong(key: String, value: Long) { + override fun toLong( + key: String, + value: Long, + ) { properties.addProperty(key, value) } - override fun toDouble(key: String, value: Double) { + override fun toDouble( + key: String, + value: Double, + ) { properties.addProperty(key, value) } - override fun toBoolean(key: String, value: Boolean) { + override fun toBoolean( + key: String, + value: Boolean, + ) { properties.addProperty(key, value) } - override fun toString(key: String, value: String) { + override fun toString( + key: String, + value: String, + ) { properties.addProperty(key, value) } } internal inner class UserAttributeSetter( private var brazeUser: BrazeUser, - enableTypeDetection: Boolean + enableTypeDetection: Boolean, ) : StringTypeParser(enableTypeDetection) { - override fun toInt(key: String, value: Int) { + override fun toInt( + key: String, + value: Int, + ) { brazeUser.setCustomUserAttribute(key, value) } - override fun toLong(key: String, value: Long) { + override fun toLong( + key: String, + value: Long, + ) { brazeUser.setCustomUserAttribute(key, value) } - override fun toDouble(key: String, value: Double) { + override fun toDouble( + key: String, + value: Double, + ) { brazeUser.setCustomUserAttribute(key, value) } - override fun toBoolean(key: String, value: Boolean) { + override fun toBoolean( + key: String, + value: Boolean, + ) { brazeUser.setCustomUserAttribute(key, value) } - override fun toString(key: String, value: String) { + override fun toString( + key: String, + value: String, + ) { brazeUser.setCustomUserAttribute(key, value) } } @@ -1160,6 +1367,7 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, const val HOST = "host" const val PUSH_ENABLED = "push_enabled" const val NAME = "Appboy" + // if this flag is true, kit will send Product name as sku const val REPLACE_SKU_AS_PRODUCT_NAME = "replaceSkuWithProductName" private const val PREF_KEY_HAS_SYNCED_ATTRIBUTES = "appboy::has_synced_attributes" @@ -1175,8 +1383,8 @@ open class AppboyKit : KitIntegration(), AttributeListener, CommerceListener, private const val UNSUBSCRIBED = "unsubscribed" private const val SUBSCRIBED = "subscribed" - //Constants for Read Consent - private const val consentMappingSDK = "consentMappingSDK" + // Constants for Read Consent + private const val CONSENT_MAPPING_SDK = "consentMappingSDK" private const val KEY_GOOGLE_AD_USER_DATA = "\$google_ad_user_data" private const val KEY_GOOGLE_AD_PERSONALIZATION = "\$google_ad_personalization" diff --git a/src/test/kotlin/com/braze/Braze.kt b/src/test/kotlin/com/braze/Braze.kt index e6fc4ed..f2ebeff 100644 --- a/src/test/kotlin/com/braze/Braze.kt +++ b/src/test/kotlin/com/braze/Braze.kt @@ -8,20 +8,18 @@ import com.mparticle.kits.BrazePurchase import java.math.BigDecimal class Braze { + fun getCurrentUser(): BrazeUser = Companion.currentUser - fun getCurrentUser(): BrazeUser { - return Companion.currentUser - } - - fun getCustomAttributeArray(): java.util.HashMap> { - return Companion.currentUser.getCustomAttribute() - } + fun getCustomAttributeArray(): java.util.HashMap> = Companion.currentUser.getCustomAttribute() fun getCurrentUser(callback: IValueCallback) { callback.onSuccess(currentUser) } - fun logCustomEvent(key: String, brazeProperties: BrazeProperties) { + fun logCustomEvent( + key: String, + brazeProperties: BrazeProperties, + ) { events[key] = brazeProperties } @@ -34,7 +32,7 @@ class Braze { currency: String, unitPrice: BigDecimal, quantity: Int, - purchaseProperties: BrazeProperties + purchaseProperties: BrazeProperties, ) { purchases.add(BrazePurchase(sku, currency, unitPrice, quantity, purchaseProperties)) } @@ -54,7 +52,10 @@ class Braze { val currentUser = BrazeUser() @JvmStatic - fun configure(context: Context?, config: BrazeConfig?) = true + fun configure( + context: Context?, + config: BrazeConfig?, + ) = true @JvmStatic fun getInstance(context: Context?): Braze = Braze() diff --git a/src/test/kotlin/com/braze/BrazeUser.kt b/src/test/kotlin/com/braze/BrazeUser.kt index 97be7cf..1398391 100644 --- a/src/test/kotlin/com/braze/BrazeUser.kt +++ b/src/test/kotlin/com/braze/BrazeUser.kt @@ -7,17 +7,24 @@ class BrazeUser { var dobMonth: Month? = null var dobDay = -1 - fun setDateOfBirth(year: Int, month: Month?, day: Int): Boolean { + fun setDateOfBirth( + year: Int, + month: Month?, + day: Int, + ): Boolean { dobYear = year dobMonth = month dobDay = day return true } - val customAttributeArray = HashMap >() + val customAttributeArray = HashMap>() val customUserAttributes = HashMap() - fun addToCustomAttributeArray(key: String, value: String): Boolean { + fun addToCustomAttributeArray( + key: String, + value: String, + ): Boolean { var customArray = customAttributeArray[key] if (customArray == null) { customArray = ArrayList() @@ -27,8 +34,11 @@ class BrazeUser { return true } - fun removeFromCustomAttributeArray(key: String, value: String): Boolean { - return try { + fun removeFromCustomAttributeArray( + key: String, + value: String, + ): Boolean = + try { if (customAttributeArray.containsKey(key)) { customAttributeArray.remove(key) } @@ -36,24 +46,35 @@ class BrazeUser { } catch (npe: NullPointerException) { false } - } - fun setCustomUserAttribute(key: String, value: String): Boolean { + fun setCustomUserAttribute( + key: String, + value: String, + ): Boolean { customUserAttributes[key] = value return true } - fun setCustomUserAttribute(key: String, value: Boolean): Boolean { + fun setCustomUserAttribute( + key: String, + value: Boolean, + ): Boolean { customUserAttributes[key] = value return true } - fun setCustomUserAttribute(key: String, value: Int): Boolean { + fun setCustomUserAttribute( + key: String, + value: Int, + ): Boolean { customUserAttributes[key] = value return true } - fun setCustomUserAttribute(key: String, value: Double): Boolean { + fun setCustomUserAttribute( + key: String, + value: Double, + ): Boolean { customUserAttributes[key] = value return true } @@ -68,11 +89,7 @@ class BrazeUser { return true } - fun getCustomAttribute(): HashMap> { - return customAttributeArray - } + fun getCustomAttribute(): HashMap> = customAttributeArray - fun getCustomUserAttribute(): HashMap { - return customUserAttributes - } + fun getCustomUserAttribute(): HashMap = customUserAttributes } diff --git a/src/test/kotlin/com/braze/models/outgoing/BrazeProperties.kt b/src/test/kotlin/com/braze/models/outgoing/BrazeProperties.kt index 3881c71..e36de65 100644 --- a/src/test/kotlin/com/braze/models/outgoing/BrazeProperties.kt +++ b/src/test/kotlin/com/braze/models/outgoing/BrazeProperties.kt @@ -5,32 +5,50 @@ import java.util.HashMap class BrazeProperties { val properties = HashMap() - fun addProperty(key: String, value: Long): BrazeProperties { + fun addProperty( + key: String, + value: Long, + ): BrazeProperties { properties[key] = value return this } - fun addProperty(key: String, value: Int): BrazeProperties { + fun addProperty( + key: String, + value: Int, + ): BrazeProperties { properties[key] = value return this } - fun addProperty(key: String, value: String): BrazeProperties { + fun addProperty( + key: String, + value: String, + ): BrazeProperties { properties[key] = value return this } - fun addProperty(key: String, value: Double): BrazeProperties { + fun addProperty( + key: String, + value: Double, + ): BrazeProperties { properties[key] = value return this } - fun addProperty(key: String, value: Boolean): BrazeProperties { + fun addProperty( + key: String, + value: Boolean, + ): BrazeProperties { properties[key] = value return this } - fun addProperty(key: String, value: Any): BrazeProperties { + fun addProperty( + key: String, + value: Any, + ): BrazeProperties { properties[key] = value return this } diff --git a/src/test/kotlin/com/mparticle/kits/AppboyKitTest.kt b/src/test/kotlin/com/mparticle/kits/AppboyKitTests.kt similarity index 73% rename from src/test/kotlin/com/mparticle/kits/AppboyKitTest.kt rename to src/test/kotlin/com/mparticle/kits/AppboyKitTests.kt index 4df38c7..d0f6800 100644 --- a/src/test/kotlin/com/mparticle/kits/AppboyKitTest.kt +++ b/src/test/kotlin/com/mparticle/kits/AppboyKitTests.kt @@ -61,11 +61,10 @@ class AppboyKitTests { MParticle.setInstance(Mockito.mock(MParticle::class.java)) Mockito.`when`(MParticle.getInstance()!!.Identity()).thenReturn( Mockito.mock( - IdentityApi::class.java - ) + IdentityApi::class.java, + ), ) braze = Braze - } @Test @@ -124,7 +123,7 @@ class AppboyKitTests { @Test @Throws(Exception::class) fun testHostSettingNull() { - //test that the key is set when it is passed in by the settings map + // test that the key is set when it is passed in by the settings map val missingSettings = HashMap() missingSettings[AppboyKit.APPBOY_KEY] = "key" val kit = MockAppboyKit() @@ -160,7 +159,7 @@ class AppboyKitTests { @Test fun testOnModify() { - //make sure it doesn't crash if there is no email or customerId + // make sure it doesn't crash if there is no email or customerId var e: Exception? = null try { AppboyKit().onModifyCompleted(MockUser(HashMap()), null) @@ -172,18 +171,19 @@ class AppboyKitTests { val values = arrayOfNulls(2) val mockEmail = "mockEmail$i" val mockCustomerId = "12345$i" - val kit: AppboyKit = object : AppboyKit() { - override fun setId(customerId: String) { - values[0] = customerId - } + val kit: AppboyKit = + object : AppboyKit() { + override fun setId(customerId: String) { + values[0] = customerId + } - override fun setEmail(email: String) { - if (values[0] == null) { - Assert.fail("customerId should have been set first") + override fun setEmail(email: String) { + if (values[0] == null) { + Assert.fail("customerId should have been set first") + } + values[1] = email } - values[1] = email } - } kit.identityType = IdentityType.CustomerId val map = HashMap() map[IdentityType.Email] = mockEmail @@ -219,21 +219,25 @@ class AppboyKitTests { val kit: AppboyKit = MockAppboyKit() val currentYear = Calendar.getInstance()[Calendar.YEAR] var calendar = kit.getCalendarMinusYears("5") - calendar?.get(Calendar.YEAR) + calendar + ?.get(Calendar.YEAR) ?.let { Assert.assertEquals((currentYear - 5).toLong(), it.toLong()) } calendar = kit.getCalendarMinusYears(22) - calendar?.get(Calendar.YEAR) + calendar + ?.get(Calendar.YEAR) ?.let { Assert.assertEquals((currentYear - 22).toLong(), it.toLong()) } // round down doubles calendar = kit.getCalendarMinusYears("5.001") - calendar?.get(Calendar.YEAR) + calendar + ?.get(Calendar.YEAR) ?.let { Assert.assertEquals((currentYear - 5).toLong(), it.toLong()) } calendar = kit.getCalendarMinusYears("5.9") - calendar?.get(Calendar.YEAR) + calendar + ?.get(Calendar.YEAR) ?.let { Assert.assertEquals((currentYear - 5).toLong(), it.toLong()) } - //invalid ages (negative, non numeric), don't get set + // invalid ages (negative, non numeric), don't get set Assert.assertNull(kit.getCalendarMinusYears("asdv")) Assert.assertNull(kit.getCalendarMinusYears(-1)) } @@ -243,17 +247,20 @@ class AppboyKitTests { val settings = HashMap() settings[AppboyKit.APPBOY_KEY] = "key" settings[AppboyKit.HOST] = hostName - settings["subscriptionGroupMapping"] = "" + - "[{\"jsmap\":null,\"map\":\"test1\",\"maptype\":\"UserAttributeClass.Name\",\"value\":\"00000000-0000-0000-0000-000000000000\"}," + - "{\"jsmap\":null,\"map\":\"test2\",\"maptype\":\"UserAttributeClass.Name\",\"value\":\"00000000-0000-0000-0000-000000000001\"}," + - "{\"jsmap\":null,\"map\":\"test3\",\"maptype\":\"UserAttributeClass.Name\",\"value\":\"00000000-0000-0000-0000-000000000002\"}]" + settings["subscriptionGroupMapping"] = + "[{\"jsmap\":null,\"map\":\"test1\",\"maptype\":\"UserAttributeClass.Name\"," + + "\"value\":\"00000000-0000-0000-0000-000000000000\"}," + + "{\"jsmap\":null,\"map\":\"test2\",\"maptype\":\"UserAttributeClass.Name\"," + + "\"value\":\"00000000-0000-0000-0000-000000000001\"}," + + "{\"jsmap\":null,\"map\":\"test3\",\"maptype\":\"UserAttributeClass.Name\"," + + "\"value\":\"00000000-0000-0000-0000-000000000002\"}]" val kit = MockAppboyKit() val currentUser = braze.currentUser kit.onKitCreate(settings, MockContextApplication()) - kit.setUserAttribute("test1", "true"); - kit.setUserAttribute("test2", "false"); - kit.setUserAttribute("test3", "notABoolean"); + kit.setUserAttribute("test1", "true") + kit.setUserAttribute("test2", "false") + kit.setUserAttribute("test3", "notABoolean") Assert.assertEquals(2, currentUser.getCustomUserAttribute().size.toLong()) } @@ -315,11 +322,18 @@ class AppboyKitTests { @Test fun setIdentityType() { - val possibleValues = arrayOf( - "Other", "CustomerId", "Facebook", - "Twitter", "Google", "Microsoft", - "Yahoo", "Email", "Alias" - ) + val possibleValues = + arrayOf( + "Other", + "CustomerId", + "Facebook", + "Twitter", + "Google", + "Microsoft", + "Yahoo", + "Email", + "Alias", + ) val mpid = "MPID" for (`val` in possibleValues) { val kit = kit @@ -329,7 +343,7 @@ class AppboyKitTests { Assert.assertNotNull(kit.identityType) Assert.assertEquals( `val`.lowercase(Locale.getDefault()), - kit.identityType?.name?.lowercase(Locale.getDefault()) + kit.identityType?.name?.lowercase(Locale.getDefault()), ) Assert.assertFalse(kit.isMpidIdentityType) } @@ -365,15 +379,17 @@ class AppboyKitTests { // // override fun getEventAttributesAddToUser(): Map { // val map = HashMap() -// map[KitUtils.hashForFiltering(MParticle.EventType.Navigation.toString() + "Navigation Event" + "key1")] = -// "output" +// map[KitUtils.hashForFiltering( +// MParticle.EventType.Navigation.toString() + "Navigation Event" + "key1" +// )] = "output" // return map // } // // override fun getEventAttributesRemoveFromUser(): Map { // val map = HashMap() -// map[KitUtils.hashForFiltering(MParticle.EventType.Location.toString() + "location event" + "key1")] = -// "output" +// map[KitUtils.hashForFiltering( +// MParticle.EventType.Location.toString() + "location event" + "key1" +// )] = "output" // return map // } // @@ -405,34 +421,46 @@ class AppboyKitTests { @Test fun testPurchaseCurrency() { val kit = MockAppboyKit() - val product = Product.Builder("product name", "sku1", 4.5) - .build() - val commerceEvent = CommerceEvent.Builder(Product.CHECKOUT, product) - .currency("Moon Dollars") - .build() + val product = + Product + .Builder("product name", "sku1", 4.5) + .build() + val commerceEvent = + CommerceEvent + .Builder(Product.CHECKOUT, product) + .currency("Moon Dollars") + .build() kit.logTransaction(commerceEvent, product) val braze = Braze val purchases = braze.purchases Assert.assertEquals(1, purchases.size.toLong()) val purchase = purchases[0] Assert.assertEquals("Moon Dollars", purchase.currency) - Assert.assertNull(purchase.purchaseProperties.properties[CommerceEventUtils.Constants.ATT_ACTION_CURRENCY_CODE]) + Assert.assertNull( + purchase.purchaseProperties.properties[CommerceEventUtils.Constants.ATT_ACTION_CURRENCY_CODE], + ) } @Test fun testPurchaseDefaultCurrency() { val kit = MockAppboyKit() - val product = Product.Builder("product name", "sku1", 4.5) - .build() - val commerceEvent = CommerceEvent.Builder(Product.CHECKOUT, product) - .build() + val product = + Product + .Builder("product name", "sku1", 4.5) + .build() + val commerceEvent = + CommerceEvent + .Builder(Product.CHECKOUT, product) + .build() kit.logTransaction(commerceEvent, product) val braze = Braze val purchases = braze.purchases Assert.assertEquals(1, purchases.size.toLong()) val purchase = purchases[0] Assert.assertEquals(CommerceEventUtils.Constants.DEFAULT_CURRENCY_CODE, purchase.currency) - Assert.assertNull(purchase.purchaseProperties.properties[CommerceEventUtils.Constants.ATT_ACTION_CURRENCY_CODE]) + Assert.assertNull( + purchase.purchaseProperties.properties[CommerceEventUtils.Constants.ATT_ACTION_CURRENCY_CODE], + ) } @Test @@ -444,27 +472,32 @@ class AppboyKitTests { val productCustomAttributes = HashMap() productCustomAttributes["productKey1"] = "value1" productCustomAttributes["productKey2"] = "value2" - val transactionAttributes = TransactionAttributes("the id") - .setTax(100.0) - .setShipping(12.0) - .setRevenue(99.0) - .setCouponCode("coupon code") - .setAffiliation("the affiliation") - val product = Product.Builder("product name", "sku1", 4.5) - .quantity(5.0) - .brand("testBrand") - .variant("testVariant") - .position(1) - .category("testCategory") - .customAttributes(productCustomAttributes) - .build() - val commerceEvent = CommerceEvent.Builder(Product.PURCHASE, product) - .currency("Moon Dollars") - .productListName("product list name") - .productListSource("the source") - .customAttributes(customAttributes) - .transactionAttributes(transactionAttributes) - .build() + val transactionAttributes = + TransactionAttributes("the id") + .setTax(100.0) + .setShipping(12.0) + .setRevenue(99.0) + .setCouponCode("coupon code") + .setAffiliation("the affiliation") + val product = + Product + .Builder("product name", "sku1", 4.5) + .quantity(5.0) + .brand("testBrand") + .variant("testVariant") + .position(1) + .category("testCategory") + .customAttributes(productCustomAttributes) + .build() + val commerceEvent = + CommerceEvent + .Builder(Product.PURCHASE, product) + .currency("Moon Dollars") + .productListName("product list name") + .productListSource("the source") + .customAttributes(customAttributes) + .transactionAttributes(transactionAttributes) + .build() kit.logTransaction(commerceEvent, product) val braze = Braze val purchases = braze.purchases @@ -479,52 +512,52 @@ class AppboyKitTests { Assert.assertEquals(properties.remove(CommerceEventUtils.Constants.ATT_SHIPPING), 12.0) Assert.assertEquals( properties.remove(CommerceEventUtils.Constants.ATT_ACTION_PRODUCT_LIST_SOURCE), - "the source" + "the source", ) Assert.assertEquals(properties.remove(CommerceEventUtils.Constants.ATT_TAX), 100.0) Assert.assertEquals(properties.remove(CommerceEventUtils.Constants.ATT_TOTAL), 99.0) Assert.assertEquals( properties.remove(CommerceEventUtils.Constants.ATT_ACTION_PRODUCT_ACTION_LIST), - "product list name" + "product list name", ) Assert.assertEquals( properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_COUPON_CODE), - "coupon code" + "coupon code", ) Assert.assertEquals( properties.remove(CommerceEventUtils.Constants.ATT_TRANSACTION_ID), - "the id" + "the id", ) Assert.assertEquals( properties.remove(CommerceEventUtils.Constants.ATT_AFFILIATION), - "the affiliation" + "the affiliation", ) Assert.assertEquals( properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_NAME), - "product name" + "product name", ) Assert.assertEquals( properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_CATEGORY), - "testCategory" + "testCategory", ) Assert.assertEquals( properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_BRAND), - "testBrand" + "testBrand", ) Assert.assertEquals( properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_POSITION), - 1 + 1, ) Assert.assertEquals( properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_VARIANT), - "testVariant" + "testVariant", ) - //Custom Attributes + // Custom Attributes Assert.assertEquals(properties.remove("key1"), "value1") Assert.assertEquals(properties.remove("key #2"), "value #3") - //Product Custom Attributes + // Product Custom Attributes Assert.assertEquals(properties.remove("productKey1"), "value1") Assert.assertEquals(properties.remove("productKey2"), "value2") @@ -539,22 +572,27 @@ class AppboyKitTests { val customAttributes = HashMap() customAttributes["key1"] = "value1" customAttributes["key #2"] = "value #3" - val transactionAttributes = TransactionAttributes("the id") - .setTax(100.0) - .setShipping(12.0) - .setRevenue(99.0) - .setCouponCode("coupon code") - .setAffiliation("the affiliation") - val product = Product.Builder("product name", "sku1", 4.5) - .quantity(5.0) - .build() - val commerceEvent = CommerceEvent.Builder(Product.PURCHASE, product) - .currency("Moon Dollars") - .productListName("product list name") - .productListSource("the source") - .customAttributes(customAttributes) - .transactionAttributes(transactionAttributes) - .build() + val transactionAttributes = + TransactionAttributes("the id") + .setTax(100.0) + .setShipping(12.0) + .setRevenue(99.0) + .setCouponCode("coupon code") + .setAffiliation("the affiliation") + val product = + Product + .Builder("product name", "sku1", 4.5) + .quantity(5.0) + .build() + val commerceEvent = + CommerceEvent + .Builder(Product.PURCHASE, product) + .currency("Moon Dollars") + .productListName("product list name") + .productListSource("the source") + .customAttributes(customAttributes) + .transactionAttributes(transactionAttributes) + .build() kit.logOrderLevelTransaction(commerceEvent) val braze = Braze val purchases = braze.purchases @@ -575,23 +613,23 @@ class AppboyKitTests { val productProperties = productBrazeProperties.properties Assert.assertEquals( productProperties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_TOTAL_AMOUNT), - 22.5 + 22.5, ) Assert.assertEquals( productProperties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_PRICE), - 4.5 + 4.5, ) Assert.assertEquals( productProperties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_QUANTITY), - 5.0 + 5.0, ) Assert.assertEquals( productProperties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_ID), - "sku1" + "sku1", ) Assert.assertEquals( productProperties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_NAME), - "product name" + "product name", ) Assert.assertEquals(emptyAttributes, productProperties) } @@ -600,24 +638,24 @@ class AppboyKitTests { Assert.assertEquals(properties.remove(CommerceEventUtils.Constants.ATT_TAX), 100.0) Assert.assertEquals( properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_COUPON_CODE), - "coupon code" + "coupon code", ) Assert.assertEquals( properties.remove(CommerceEventUtils.Constants.ATT_AFFILIATION), - "the affiliation" + "the affiliation", ) Assert.assertEquals( properties.remove(CommerceEventUtils.Constants.ATT_ACTION_PRODUCT_LIST_SOURCE), - "the source" + "the source", ) Assert.assertEquals(properties.remove(CommerceEventUtils.Constants.ATT_TOTAL), 99.0) Assert.assertEquals( properties.remove(CommerceEventUtils.Constants.ATT_ACTION_PRODUCT_ACTION_LIST), - "product list name" + "product list name", ) Assert.assertEquals( properties.remove(CommerceEventUtils.Constants.ATT_TRANSACTION_ID), - "the id" + "the id", ) val brazeCustomAttributesDictionary = properties.remove(AppboyKit.CUSTOM_ATTRIBUTES_KEY) @@ -674,15 +712,18 @@ class AppboyKitTests { val customAttributes = HashMap() customAttributes["key1"] = "value1" customAttributes["key #2"] = "value #3" - val promotion = Promotion().apply { - id = "my_promo_1" - creative = "sale_banner_1" - name = "App-wide 50% off sale" - position = "dashboard_bottom" - } - val commerceEvent = CommerceEvent.Builder(Promotion.VIEW, promotion) - .customAttributes(customAttributes) - .build() + val promotion = + Promotion().apply { + id = "my_promo_1" + creative = "sale_banner_1" + name = "App-wide 50% off sale" + position = "dashboard_bottom" + } + val commerceEvent = + CommerceEvent + .Builder(Promotion.VIEW, promotion) + .customAttributes(customAttributes) + .build() kit.logOrderLevelTransaction(commerceEvent) val braze = Braze val events = braze.events @@ -700,19 +741,19 @@ class AppboyKitTests { val promotionProperties = promotionBrazeProperties.properties Assert.assertEquals( promotionProperties.remove(CommerceEventUtils.Constants.ATT_PROMOTION_ID), - "my_promo_1" + "my_promo_1", ) Assert.assertEquals( promotionProperties.remove(CommerceEventUtils.Constants.ATT_PROMOTION_NAME), - "App-wide 50% off sale" + "App-wide 50% off sale", ) Assert.assertEquals( promotionProperties.remove(CommerceEventUtils.Constants.ATT_PROMOTION_POSITION), - "dashboard_bottom" + "dashboard_bottom", ) Assert.assertEquals( promotionProperties.remove(CommerceEventUtils.Constants.ATT_PROMOTION_CREATIVE), - "sale_banner_1" + "sale_banner_1", ) Assert.assertEquals(emptyAttributes, promotionProperties) } @@ -757,12 +798,22 @@ class AppboyKitTests { // Assert.assertNotNull(event.properties) // val properties = event.properties // -// Assert.assertEquals(properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_TOTAL_AMOUNT), "22.5") -// Assert.assertEquals(properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_NAME), "product name") -// Assert.assertEquals(properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_QUANTITY), "5.0") +// Assert.assertEquals( +// properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_TOTAL_AMOUNT), "22.5" +// ) +// Assert.assertEquals( +// properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_NAME), "product name" +// ) +// Assert.assertEquals( +// properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_QUANTITY), "5.0" +// ) // Assert.assertEquals(properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_ID), "sku1") -// Assert.assertEquals(properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_PRICE), "4.5") -// Assert.assertEquals(properties.remove("Product Impression List"), "Suggested Products List") +// Assert.assertEquals( +// properties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_PRICE), "4.5" +// ) +// Assert.assertEquals( +// properties.remove("Product Impression List"), "Suggested Products List" +// ) // Assert.assertEquals(properties.remove("key1"), "value1") // Assert.assertEquals(properties.remove("key #2"), "value #3") // @@ -778,16 +829,21 @@ class AppboyKitTests { val customAttributes = HashMap() customAttributes["key1"] = "value1" customAttributes["key #2"] = "value #3" - val product = Product.Builder("product name", "sku1", 4.5) - .quantity(5.0) - .customAttributes(customAttributes) - .build() - val impression = Impression("Suggested Products List", product).let { - CommerceEvent.Builder(it).build() - } - val commerceEvent = CommerceEvent.Builder(impression) - .customAttributes(customAttributes) - .build() + val product = + Product + .Builder("product name", "sku1", 4.5) + .quantity(5.0) + .customAttributes(customAttributes) + .build() + val impression = + Impression("Suggested Products List", product).let { + CommerceEvent.Builder(it).build() + } + val commerceEvent = + CommerceEvent + .Builder(impression) + .customAttributes(customAttributes) + .build() kit.logOrderLevelTransaction(commerceEvent) val braze = Braze val events = braze.events @@ -805,7 +861,7 @@ class AppboyKitTests { val impressionProperties = impressionBrazeProperties.properties Assert.assertEquals( impressionProperties.remove("Product Impression List"), - "Suggested Products List" + "Suggested Products List", ) val productArray = impressionProperties.remove(AppboyKit.PRODUCT_KEY) Assert.assertTrue(productArray is Array<*>) @@ -815,24 +871,30 @@ class AppboyKitTests { if (productBrazeProperties is BrazeProperties) { val productProperties = productBrazeProperties.properties Assert.assertEquals( - productProperties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_TOTAL_AMOUNT), - 22.5 + productProperties.remove( + CommerceEventUtils.Constants.ATT_PRODUCT_TOTAL_AMOUNT, + ), + 22.5, ) Assert.assertEquals( productProperties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_NAME), - "product name" + "product name", ) Assert.assertEquals( - productProperties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_QUANTITY), - 5.0 + productProperties.remove( + CommerceEventUtils.Constants.ATT_PRODUCT_QUANTITY, + ), + 5.0, ) Assert.assertEquals( productProperties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_ID), - "sku1" + "sku1", ) Assert.assertEquals( - productProperties.remove(CommerceEventUtils.Constants.ATT_PRODUCT_PRICE), - 4.5 + productProperties.remove( + CommerceEventUtils.Constants.ATT_PRODUCT_PRICE, + ), + 4.5, ) val brazeProductCustomAttributesDictionary = productProperties.remove(AppboyKit.CUSTOM_ATTRIBUTES_KEY) @@ -841,11 +903,11 @@ class AppboyKitTests { brazeProductCustomAttributesDictionary.properties Assert.assertEquals( customProductAttributesDictionary.remove("key1"), - "value1" + "value1", ) Assert.assertEquals( customProductAttributesDictionary.remove("key #2"), - "value #3" + "value #3", ) Assert.assertEquals(emptyAttributes, customProductAttributesDictionary) } @@ -1009,7 +1071,7 @@ class AppboyKitTests { val jsonObject = JSONObject() val mapValue = JSONObject() - //this is hash for event attribute i.e combination of eventType + eventName + attribute key + // this is hash for event attribute i.e combination of eventType + eventName + attribute key mapValue.put("888169310", "testEvent") val eaaObject = JSONObject() eaaObject.put("eaa", mapValue) @@ -1021,9 +1083,11 @@ class AppboyKitTests { kit.configuration = kitConfiguration val customAttributes: MutableMap = HashMap() customAttributes["destination"] = "Shop" - val event = MPEvent.Builder("AndroidTEST", MParticle.EventType.Navigation) - .customAttributes(customAttributes) - .build() + val event = + MPEvent + .Builder("AndroidTEST", MParticle.EventType.Navigation) + .customAttributes(customAttributes) + .build() val instance = MParticle.getInstance() instance?.logEvent(event) kit.logEvent(event) @@ -1046,7 +1110,7 @@ class AppboyKitTests { val jsonObject = JSONObject() val mapValue = JSONObject() - //this is hash for event attribute i.e combination of eventType + eventName + attribute key + // this is hash for event attribute i.e combination of eventType + eventName + attribute key mapValue.put("888169310", "testEvent") val eaaObject = JSONObject() eaaObject.put("eaa", mapValue) @@ -1059,9 +1123,11 @@ class AppboyKitTests { kit.configuration = kitConfiguration val customAttributes: MutableMap = HashMap() customAttributes["destination"] = "Shop" - val event = MPEvent.Builder("AndroidTEST", MParticle.EventType.Navigation) - .customAttributes(customAttributes) - .build() + val event = + MPEvent + .Builder("AndroidTEST", MParticle.EventType.Navigation) + .customAttributes(customAttributes) + .build() val instance = MParticle.getInstance() instance?.logEvent(event) kit.logEvent(event) @@ -1078,7 +1144,7 @@ class AppboyKitTests { val jsonObject = JSONObject() val mapValue = JSONObject() - //this is hash for event attribute i.e combination of eventType + eventName + attribute key + // this is hash for event attribute i.e combination of eventType + eventName + attribute key mapValue.put("888169310", "testEvent") val eaaObject = JSONObject() eaaObject.put("eas", mapValue) @@ -1090,9 +1156,11 @@ class AppboyKitTests { kit.configuration = kitConfiguration val customAttributes: MutableMap = HashMap() customAttributes["destination"] = "Shop" - val event = MPEvent.Builder("AndroidTEST", MParticle.EventType.Navigation) - .customAttributes(customAttributes) - .build() + val event = + MPEvent + .Builder("AndroidTEST", MParticle.EventType.Navigation) + .customAttributes(customAttributes) + .build() val instance = MParticle.getInstance() instance?.logEvent(event) kit.logEvent(event) @@ -1110,12 +1178,20 @@ class AppboyKitTests { fun testParseToNestedMap_When_JSON_Is_INVALID() { val kit = MockAppboyKit() var jsonInput = - "{'GDPR':{'marketing':'{:false,'timestamp':1711038269644:'Test consent','location':'17 Cherry Tree Lane','hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}','performance':'{'consented':true,'timestamp':1711038269644,'document':'parental_consent_agreement_v2','location':'17 Cherry Tree Lan 3','hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}'},'CCPA':'{'consented':true,'timestamp':1711038269644,'document':'ccpa_consent_agreement_v3','location':'17 Cherry Tree Lane','hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}'}" - - val method: Method = AppboyKit::class.java.getDeclaredMethod( - "parseToNestedMap", - String::class.java - ) + "{'GDPR':{'marketing':'{:false,'timestamp':1711038269644:'Test consent'," + + "'location':'17 Cherry Tree Lane','hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}," + + "'performance':'{'consented':true,'timestamp':1711038269644," + + "'document':'parental_consent_agreement_v2','location':'17 Cherry Tree Lan 3'," + + "'hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}'}," + + "'CCPA':'{'consented':true,'timestamp':1711038269644," + + "'document':'ccpa_consent_agreement_v3','location':'17 Cherry Tree Lane'," + + "'hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}'}" + + val method: Method = + AppboyKit::class.java.getDeclaredMethod( + "parseToNestedMap", + String::class.java, + ) method.isAccessible = true val result = method.invoke(kit, jsonInput) Assert.assertEquals(mutableMapOf(), result) @@ -1126,10 +1202,11 @@ class AppboyKitTests { val kit = MockAppboyKit() var jsonInput = "" - val method: Method = AppboyKit::class.java.getDeclaredMethod( - "parseToNestedMap", - String::class.java - ) + val method: Method = + AppboyKit::class.java.getDeclaredMethod( + "parseToNestedMap", + String::class.java, + ) method.isAccessible = true val result = method.invoke(kit, jsonInput) Assert.assertEquals(mutableMapOf(), result) @@ -1138,21 +1215,26 @@ class AppboyKitTests { @Test fun testSearchKeyInNestedMap_When_Input_Key_Is_Empty_String() { val kit = MockAppboyKit() - val map = mapOf( - "FeatureEnabled" to true, - "settings" to mapOf( - "darkMode" to false, - "notifications" to mapOf( - "email" to false, - "push" to true, - "lastUpdated" to 1633046400000L - ) + val map = + mapOf( + "FeatureEnabled" to true, + "settings" to + mapOf( + "darkMode" to false, + "notifications" to + mapOf( + "email" to false, + "push" to true, + "lastUpdated" to 1633046400000L, + ), + ), + ) + val method: Method = + AppboyKit::class.java.getDeclaredMethod( + "searchKeyInNestedMap", + Map::class.java, + Any::class.java, ) - ) - val method: Method = AppboyKit::class.java.getDeclaredMethod( - "searchKeyInNestedMap", Map::class.java, - Any::class.java - ) method.isAccessible = true val result = method.invoke(kit, map, "") Assert.assertEquals(null, result) @@ -1162,10 +1244,12 @@ class AppboyKitTests { fun testSearchKeyInNestedMap_When_Input_Is_Empty_Map() { val kit = MockAppboyKit() val emptyMap: Map = emptyMap() - val method: Method = AppboyKit::class.java.getDeclaredMethod( - "searchKeyInNestedMap", Map::class.java, - Any::class.java - ) + val method: Method = + AppboyKit::class.java.getDeclaredMethod( + "searchKeyInNestedMap", + Map::class.java, + Any::class.java, + ) method.isAccessible = true val result = method.invoke(kit, emptyMap, "1") Assert.assertEquals(null, result) @@ -1175,10 +1259,11 @@ class AppboyKitTests { fun testParseConsentMapping_When_Input_Is_Empty_Json() { val kit = MockAppboyKit() val emptyJson = "" - val method: Method = AppboyKit::class.java.getDeclaredMethod( - "parseConsentMapping", - String::class.java - ) + val method: Method = + AppboyKit::class.java.getDeclaredMethod( + "parseConsentMapping", + String::class.java, + ) method.isAccessible = true val result = method.invoke(kit, emptyJson) Assert.assertEquals(emptyMap(), result) @@ -1188,11 +1273,19 @@ class AppboyKitTests { fun testParseConsentMapping_When_Input_Is_Invalid_Json() { val kit = MockAppboyKit() var jsonInput = - "{'GDPR':{'marketing':'{:false,'timestamp':1711038269644:'Test consent','location':'17 Cherry Tree Lane','hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}','performance':'{'consented':true,'timestamp':1711038269644,'document':'parental_consent_agreement_v2','location':'17 Cherry Tree Lan 3','hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}'},'CCPA':'{'consented':true,'timestamp':1711038269644,'document':'ccpa_consent_agreement_v3','location':'17 Cherry Tree Lane','hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}'}" - val method: Method = AppboyKit::class.java.getDeclaredMethod( - "parseConsentMapping", - String::class.java - ) + "{'GDPR':{'marketing':'{:false,'timestamp':1711038269644:'Test consent'," + + "'location':'17 Cherry Tree Lane','hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}," + + "'performance':'{'consented':true,'timestamp':1711038269644," + + "'document':'parental_consent_agreement_v2','location':'17 Cherry Tree Lan 3'," + + "'hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}'}," + + "'CCPA':'{'consented':true,'timestamp':1711038269644," + + "'document':'ccpa_consent_agreement_v3','location':'17 Cherry Tree Lane'," + + "'hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}'}" + val method: Method = + AppboyKit::class.java.getDeclaredMethod( + "parseConsentMapping", + String::class.java, + ) method.isAccessible = true val result = method.invoke(kit, jsonInput) Assert.assertEquals(emptyMap(), result) @@ -1201,10 +1294,11 @@ class AppboyKitTests { @Test fun testParseConsentMapping_When_Input_Is_NULL() { val kit = MockAppboyKit() - val method: Method = AppboyKit::class.java.getDeclaredMethod( - "parseConsentMapping", - String::class.java - ) + val method: Method = + AppboyKit::class.java.getDeclaredMethod( + "parseConsentMapping", + String::class.java, + ) method.isAccessible = true val result = method.invoke(kit, null) Assert.assertEquals(emptyMap(), result) @@ -1218,26 +1312,34 @@ class AppboyKitTests { val map = java.util.HashMap() map["consentMappingSDK"] = - " [{\\\"jsmap\\\":null,\\\"map\\\":\\\"Performance\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"google_ad_user_data\\\"},{\\\"jsmap\\\":null,\\\"map\\\":\\\"Marketing\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"google_ad_personalization\\\"}]" - + " [{\\\"jsmap\\\":null,\\\"map\\\":\\\"Performance\\\"," + + "\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"google_ad_user_data\\\"}," + + "{\\\"jsmap\\\":null,\\\"map\\\":\\\"Marketing\\\"," + + "\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"google_ad_personalization\\\"}]" var kitConfiguration = MockKitConfiguration.createKitConfiguration(JSONObject().put("as", map.toMutableMap())) kit.configuration = kitConfiguration - val marketingConsent = GDPRConsent.builder(false) - .document("Test consent") - .location("17 Cherry Tree Lane") - .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") - .build() - val state = ConsentState.builder() - .addGDPRConsentState("Marketing", marketingConsent) - .build() + val marketingConsent = + GDPRConsent + .builder(false) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + val state = + ConsentState + .builder() + .addGDPRConsentState("Marketing", marketingConsent) + .build() filteredMParticleUser = FilteredMParticleUser.getInstance(user, kit) kit.onConsentStateUpdated(state, state, filteredMParticleUser) - TestCase.assertEquals(false, currentUser.getCustomUserAttribute()["\$google_ad_personalization"]) - + TestCase.assertEquals( + false, + currentUser.getCustomUserAttribute()["\$google_ad_personalization"], + ) } @Test @@ -1248,34 +1350,45 @@ class AppboyKitTests { val map = java.util.HashMap() map["consentMappingSDK"] = - " [{\\\"jsmap\\\":null,\\\"map\\\":\\\"Performance\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"google_ad_user_data\\\"},{\\\"jsmap\\\":null,\\\"map\\\":\\\"Marketing\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"google_ad_personalization\\\"}]" - + " [{\\\"jsmap\\\":null,\\\"map\\\":\\\"Performance\\\"," + + "\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"google_ad_user_data\\\"}," + + "{\\\"jsmap\\\":null,\\\"map\\\":\\\"Marketing\\\"," + + "\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"google_ad_personalization\\\"}]" var kitConfiguration = MockKitConfiguration.createKitConfiguration(JSONObject().put("as", map.toMutableMap())) kit.configuration = kitConfiguration - val marketingConsent = GDPRConsent.builder(true) - .document("Test consent") - .location("17 Cherry Tree Lane") - .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") - .build() - - val performanceConsent = GDPRConsent.builder(true) - .document("parental_consent_agreement_v2") - .location("17 Cherry Tree Lan 3") - .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") - .build() - - val state = ConsentState.builder() - .addGDPRConsentState("Marketing", marketingConsent) - .addGDPRConsentState("Performance", performanceConsent) - .build() + val marketingConsent = + GDPRConsent + .builder(true) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + + val performanceConsent = + GDPRConsent + .builder(true) + .document("parental_consent_agreement_v2") + .location("17 Cherry Tree Lan 3") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + + val state = + ConsentState + .builder() + .addGDPRConsentState("Marketing", marketingConsent) + .addGDPRConsentState("Performance", performanceConsent) + .build() filteredMParticleUser = FilteredMParticleUser.getInstance(user, kit) kit.onConsentStateUpdated(state, state, filteredMParticleUser) TestCase.assertEquals(true, currentUser.getCustomUserAttribute()["\$google_ad_user_data"]) - TestCase.assertEquals(true, currentUser.getCustomUserAttribute()["\$google_ad_personalization"]) + TestCase.assertEquals( + true, + currentUser.getCustomUserAttribute()["\$google_ad_personalization"], + ) } @Test @@ -1283,22 +1396,28 @@ class AppboyKitTests { val kit = MockAppboyKit() val currentUser = braze.currentUser kit.configuration = MockKitConfiguration() - val marketingConsent = GDPRConsent.builder(true) - .document("Test consent") - .location("17 Cherry Tree Lane") - .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") - .build() - - val performanceConsent = GDPRConsent.builder(true) - .document("parental_consent_agreement_v2") - .location("17 Cherry Tree Lan 3") - .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") - .build() - - val state = ConsentState.builder() - .addGDPRConsentState("Marketing", marketingConsent) - .addGDPRConsentState("Performance", performanceConsent) - .build() + val marketingConsent = + GDPRConsent + .builder(true) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + + val performanceConsent = + GDPRConsent + .builder(true) + .document("parental_consent_agreement_v2") + .location("17 Cherry Tree Lan 3") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + + val state = + ConsentState + .builder() + .addGDPRConsentState("Marketing", marketingConsent) + .addGDPRConsentState("Performance", performanceConsent) + .build() filteredMParticleUser = FilteredMParticleUser.getInstance(user, kit) kit.onConsentStateUpdated(state, state, filteredMParticleUser) TestCase.assertEquals(0, currentUser.getCustomUserAttribute().size) @@ -1318,28 +1437,33 @@ class AppboyKitTests { kit.configuration = KitConfiguration.createKitConfiguration(JSONObject().put("as", map.toMutableMap())) - val marketingConsent = GDPRConsent.builder(true) - .document("Test consent") - .location("17 Cherry Tree Lane") - .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") - .build() - - val performanceConsent = GDPRConsent.builder(true) - .document("parental_consent_agreement_v2") - .location("17 Cherry Tree Lan 3") - .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") - .build() - - val state = ConsentState.builder() - .addGDPRConsentState("Marketing", marketingConsent) - .addGDPRConsentState("Performance", performanceConsent) - .build() + val marketingConsent = + GDPRConsent + .builder(true) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + + val performanceConsent = + GDPRConsent + .builder(true) + .document("parental_consent_agreement_v2") + .location("17 Cherry Tree Lan 3") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + + val state = + ConsentState + .builder() + .addGDPRConsentState("Marketing", marketingConsent) + .addGDPRConsentState("Performance", performanceConsent) + .build() filteredMParticleUser = FilteredMParticleUser.getInstance(user, kit) kit.onConsentStateUpdated(state, state, filteredMParticleUser) TestCase.assertEquals(0, currentUser.getCustomUserAttribute().size) - } @Test @@ -1352,18 +1476,24 @@ class AppboyKitTests { kit.configuration = KitConfiguration.createKitConfiguration(JSONObject().put("as", settings)) kit.onKitCreate(settings, MockContextApplication()) - val product = Product.Builder("product name", "sku1", 4.5) - .build() - val commerceEvent = CommerceEvent.Builder(Product.CHECKOUT, product) - .currency("Moon Dollars") - .build() + val product = + Product + .Builder("product name", "sku1", 4.5) + .build() + val commerceEvent = + CommerceEvent + .Builder(Product.CHECKOUT, product) + .currency("Moon Dollars") + .build() kit.logTransaction(commerceEvent, product) val braze = Braze val purchases = braze.purchases Assert.assertEquals(1, purchases.size.toLong()) val purchase = purchases[0] Assert.assertEquals("product name", purchase.sku) - Assert.assertNull(purchase.purchaseProperties.properties[CommerceEventUtils.Constants.ATT_ACTION_CURRENCY_CODE]) + Assert.assertNull( + purchase.purchaseProperties.properties[CommerceEventUtils.Constants.ATT_ACTION_CURRENCY_CODE], + ) } @Test @@ -1376,18 +1506,24 @@ class AppboyKitTests { kit.configuration = KitConfiguration.createKitConfiguration(JSONObject().put("as", settings)) kit.onKitCreate(settings, MockContextApplication()) - val product = Product.Builder("product name", "sku1", 4.5) - .build() - val commerceEvent = CommerceEvent.Builder(Product.CHECKOUT, product) - .currency("Moon Dollars") - .build() + val product = + Product + .Builder("product name", "sku1", 4.5) + .build() + val commerceEvent = + CommerceEvent + .Builder(Product.CHECKOUT, product) + .currency("Moon Dollars") + .build() kit.logTransaction(commerceEvent, product) val braze = Braze val purchases = braze.purchases Assert.assertEquals(1, purchases.size.toLong()) val purchase = purchases[0] Assert.assertEquals("sku1", purchase.sku) - Assert.assertNull(purchase.purchaseProperties.properties[CommerceEventUtils.Constants.ATT_ACTION_CURRENCY_CODE]) + Assert.assertNull( + purchase.purchaseProperties.properties[CommerceEventUtils.Constants.ATT_ACTION_CURRENCY_CODE], + ) } @Test @@ -1399,17 +1535,23 @@ class AppboyKitTests { kit.configuration = KitConfiguration.createKitConfiguration(JSONObject().put("as", settings)) kit.onKitCreate(settings, MockContextApplication()) - val product = Product.Builder("product name", "sku1", 4.5) - .build() - val commerceEvent = CommerceEvent.Builder(Product.CHECKOUT, product) - .currency("Moon Dollars") - .build() + val product = + Product + .Builder("product name", "sku1", 4.5) + .build() + val commerceEvent = + CommerceEvent + .Builder(Product.CHECKOUT, product) + .currency("Moon Dollars") + .build() kit.logTransaction(commerceEvent, product) val braze = Braze val purchases = braze.purchases Assert.assertEquals(1, purchases.size.toLong()) val purchase = purchases[0] Assert.assertEquals("sku1", purchase.sku) - Assert.assertNull(purchase.purchaseProperties.properties[CommerceEventUtils.Constants.ATT_ACTION_CURRENCY_CODE]) + Assert.assertNull( + purchase.purchaseProperties.properties[CommerceEventUtils.Constants.ATT_ACTION_CURRENCY_CODE], + ) } } diff --git a/src/test/kotlin/com/mparticle/kits/BrazePurchase.kt b/src/test/kotlin/com/mparticle/kits/BrazePurchase.kt index 95c4add..93de4c9 100644 --- a/src/test/kotlin/com/mparticle/kits/BrazePurchase.kt +++ b/src/test/kotlin/com/mparticle/kits/BrazePurchase.kt @@ -8,5 +8,5 @@ data class BrazePurchase( val currency: String, val unitPrice: BigDecimal, val quantity: Int, - val purchaseProperties: BrazeProperties -) \ No newline at end of file + val purchaseProperties: BrazeProperties, +) diff --git a/src/test/kotlin/com/mparticle/kits/TypeDetectionTests.kt b/src/test/kotlin/com/mparticle/kits/TypeDetectionTests.kt index bcafdfd..65e9b5e 100644 --- a/src/test/kotlin/com/mparticle/kits/TypeDetectionTests.kt +++ b/src/test/kotlin/com/mparticle/kits/TypeDetectionTests.kt @@ -15,11 +15,11 @@ class TypeDetectionTests { Assert.assertEquals(Int.MIN_VALUE, parser.parseValue("key", Int.MIN_VALUE.toString())) Assert.assertEquals( Int.MAX_VALUE + 1L, - parser.parseValue("key", (Int.MAX_VALUE + 1L).toString()) + parser.parseValue("key", (Int.MAX_VALUE + 1L).toString()), ) Assert.assertEquals( Int.MIN_VALUE - 1L, - parser.parseValue("key", (Int.MIN_VALUE - 1L).toString()) + parser.parseValue("key", (Int.MIN_VALUE - 1L).toString()), ) Assert.assertEquals(Long.MAX_VALUE, parser.parseValue("key", Long.MAX_VALUE.toString())) Assert.assertEquals(Long.MIN_VALUE, parser.parseValue("key", Long.MIN_VALUE.toString())) @@ -42,29 +42,50 @@ class TypeDetectionTests { Assert.assertEquals("1", parser.parseValue("key", "1")) Assert.assertEquals( (Int.MAX_VALUE + 1L).toString(), - parser.parseValue("key", (Int.MAX_VALUE + 1L).toString()) + parser.parseValue("key", (Int.MAX_VALUE + 1L).toString()), ) Assert.assertEquals("432.2561", parser.parseValue("key", "432.2561")) Assert.assertEquals("true", parser.parseValue("key", "true")) } - private inner class SomeParser internal constructor(enableTypeDetection: Boolean?) : - StringTypeParser( - enableTypeDetection!! + private inner class SomeParser internal constructor( + enableTypeDetection: Boolean?, + ) : StringTypeParser( + enableTypeDetection!!, ) { - override fun toString(key: String, value: String) { /* do nothing */ + override fun toString( + key: String, + value: String, + ) { + // do nothing } - override fun toInt(key: String, value: Int) { /* do nothing */ + override fun toInt( + key: String, + value: Int, + ) { + // do nothing } - override fun toLong(key: String, value: Long) { /* do nothing */ + override fun toLong( + key: String, + value: Long, + ) { + // do nothing } - override fun toDouble(key: String, value: Double) { /* do nothing */ + override fun toDouble( + key: String, + value: Double, + ) { + // do nothing } - override fun toBoolean(key: String, value: Boolean) { /* do nothing */ + override fun toBoolean( + key: String, + value: Boolean, + ) { + // do nothing } } } diff --git a/src/test/kotlin/com/mparticle/kits/mocks/MockAppboyKit.kt b/src/test/kotlin/com/mparticle/kits/mocks/MockAppboyKit.kt index 99abdbf..f96faa2 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockAppboyKit.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockAppboyKit.kt @@ -7,19 +7,23 @@ import org.mockito.Mockito class MockAppboyKit : AppboyKit() { val calledAuthority = arrayOfNulls(1) + override fun setAuthority(authority: String?) { calledAuthority[0] = authority } override fun queueDataFlush() { - //do nothing + // do nothing } init { - kitManager = MockKitManagerImpl( - Mockito.mock(Context::class.java), Mockito.mock( - ReportingManager::class.java - ), MockCoreCallbacks() - ) + kitManager = + MockKitManagerImpl( + Mockito.mock(Context::class.java), + Mockito.mock( + ReportingManager::class.java, + ), + MockCoreCallbacks(), + ) } } diff --git a/src/test/kotlin/com/mparticle/kits/mocks/MockApplication.kt b/src/test/kotlin/com/mparticle/kits/mocks/MockApplication.kt index 2454c6e..be9dc8b 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockApplication.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockApplication.kt @@ -7,41 +7,33 @@ import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import android.content.res.Resources -class MockApplication(var mContext: MockContext) : Application() { +class MockApplication( + var mContext: MockContext, +) : Application() { var mCallbacks: ActivityLifecycleCallbacks? = null + override fun registerActivityLifecycleCallbacks(callback: ActivityLifecycleCallbacks) { mCallbacks = callback } - override fun getApplicationContext(): Context { - return this - } + override fun getApplicationContext(): Context = this fun setSharedPreferences(prefs: SharedPreferences) { mContext.setSharedPreferences(prefs) } - override fun getSystemService(name: String): Any? { - return mContext.getSystemService(name) - } + override fun getSystemService(name: String): Any? = mContext.getSystemService(name) - override fun getSharedPreferences(name: String, mode: Int): SharedPreferences { - return mContext.getSharedPreferences(name, mode) - } + override fun getSharedPreferences( + name: String, + mode: Int, + ): SharedPreferences = mContext.getSharedPreferences(name, mode) - override fun getPackageManager(): PackageManager { - return mContext.packageManager - } + override fun getPackageManager(): PackageManager = mContext.packageManager - override fun getPackageName(): String { - return mContext.packageName - } + override fun getPackageName(): String = mContext.packageName - override fun getApplicationInfo(): ApplicationInfo { - return mContext.applicationInfo - } + override fun getApplicationInfo(): ApplicationInfo = mContext.applicationInfo - override fun getResources(): Resources? { - return mContext.resources - } + override fun getResources(): Resources? = mContext.resources } diff --git a/src/test/kotlin/com/mparticle/kits/mocks/MockContext.kt b/src/test/kotlin/com/mparticle/kits/mocks/MockContext.kt index 7a90414..1d62077 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockContext.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockContext.kt @@ -1,7 +1,15 @@ package com.mparticle.kits.mocks -import android.content.* +import android.content.BroadcastReceiver +import android.content.ComponentName +import android.content.ContentResolver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.content.IntentSender import android.content.IntentSender.SendIntentException +import android.content.ServiceConnection +import android.content.SharedPreferences import android.content.pm.ApplicationInfo import android.content.pm.PackageInfo import android.content.pm.PackageManager @@ -24,12 +32,18 @@ import android.telephony.TelephonyManager import android.view.Display import junit.framework.Assert import org.mockito.Mockito -import java.io.* +import java.io.File +import java.io.FileInputStream +import java.io.FileNotFoundException +import java.io.FileOutputStream +import java.io.IOException +import java.io.InputStream class MockContext : Context() { private var sharedPreferences: SharedPreferences = MockSharedPreferences() private var resources: Resources = MockResources() var application: MockApplication? = null + fun setSharedPreferences(prefs: SharedPreferences) { sharedPreferences = prefs } @@ -41,23 +55,21 @@ class MockContext : Context() { return application as MockApplication } - override fun checkCallingOrSelfPermission(permission: String): Int { - return PackageManager.PERMISSION_GRANTED - } + override fun checkCallingOrSelfPermission(permission: String): Int = PackageManager.PERMISSION_GRANTED - override fun getSharedPreferences(name: String, mode: Int): SharedPreferences { - return sharedPreferences - } + override fun getSharedPreferences( + name: String, + mode: Int, + ): SharedPreferences = sharedPreferences - override fun getResources(): Resources? { - return resources - } + override fun getResources(): Resources? = resources - override fun getSystemService(name: String): Any? { - return if (name == TELEPHONY_SERVICE) { + override fun getSystemService(name: String): Any? = + if (name == TELEPHONY_SERVICE) { Mockito.mock(TelephonyManager::class.java) - } else null - } + } else { + null + } override fun getPackageManager(): PackageManager { val manager = Mockito.mock(PackageManager::class.java) @@ -66,11 +78,14 @@ class MockContext : Context() { info.versionCode = 42 val appInfo = Mockito.mock(ApplicationInfo::class.java) try { - Mockito.`when`(manager.getPackageInfo(Mockito.anyString(), Mockito.anyInt())) + Mockito + .`when`(manager.getPackageInfo(Mockito.anyString(), Mockito.anyInt())) .thenReturn(info) - Mockito.`when`(manager.getInstallerPackageName(Mockito.anyString())) + Mockito + .`when`(manager.getInstallerPackageName(Mockito.anyString())) .thenReturn("com.mparticle.test.installer") - Mockito.`when`(manager.getApplicationInfo(Mockito.anyString(), Mockito.anyInt())) + Mockito + .`when`(manager.getApplicationInfo(Mockito.anyString(), Mockito.anyInt())) .thenReturn(appInfo) Mockito.`when`(manager.getApplicationLabel(appInfo)).thenReturn("test label") } catch (e: Exception) { @@ -79,29 +94,31 @@ class MockContext : Context() { return manager } - override fun getPackageName(): String { - return "com.mparticle.test" - } + override fun getPackageName(): String = "com.mparticle.test" - override fun getApplicationInfo(): ApplicationInfo { - return ApplicationInfo() - } + override fun getApplicationInfo(): ApplicationInfo = ApplicationInfo() /** * Stubbed methods */ override fun setTheme(resid: Int) {} - override fun getTheme(): Theme? { - return null - } - override fun getClassLoader(): ClassLoader? { - return null - } + override fun getTheme(): Theme? = null + + override fun getClassLoader(): ClassLoader? = null override fun sendBroadcast(intent: Intent) {} - override fun sendBroadcast(intent: Intent, receiverPermission: String?) {} - override fun sendOrderedBroadcast(intent: Intent, receiverPermission: String?) {} + + override fun sendBroadcast( + intent: Intent, + receiverPermission: String?, + ) {} + + override fun sendOrderedBroadcast( + intent: Intent, + receiverPermission: String?, + ) {} + override fun sendOrderedBroadcast( intent: Intent, receiverPermission: String?, @@ -109,15 +126,19 @@ class MockContext : Context() { scheduler: Handler?, initialCode: Int, initialData: String?, - initialExtras: Bundle? + initialExtras: Bundle?, ) { } - override fun sendBroadcastAsUser(intent: Intent, user: UserHandle) {} override fun sendBroadcastAsUser( intent: Intent, user: UserHandle, - receiverPermission: String? + ) {} + + override fun sendBroadcastAsUser( + intent: Intent, + user: UserHandle, + receiverPermission: String?, ) { } @@ -129,23 +150,29 @@ class MockContext : Context() { scheduler: Handler?, initialCode: Int, initialData: String?, - initialExtras: Bundle? + initialExtras: Bundle?, ) { } override fun sendStickyBroadcast(intent: Intent) {} + override fun sendStickyOrderedBroadcast( intent: Intent, resultReceiver: BroadcastReceiver, scheduler: Handler?, initialCode: Int, initialData: String?, - initialExtras: Bundle? + initialExtras: Bundle?, ) { } override fun removeStickyBroadcast(intent: Intent) {} - override fun sendStickyBroadcastAsUser(intent: Intent, user: UserHandle) {} + + override fun sendStickyBroadcastAsUser( + intent: Intent, + user: UserHandle, + ) {} + override fun sendStickyOrderedBroadcastAsUser( intent: Intent, user: UserHandle, @@ -153,89 +180,115 @@ class MockContext : Context() { scheduler: Handler?, initialCode: Int, initialData: String?, - initialExtras: Bundle? + initialExtras: Bundle?, ) { } - override fun removeStickyBroadcastAsUser(intent: Intent, user: UserHandle) {} - override fun registerReceiver(receiver: BroadcastReceiver?, filter: IntentFilter): Intent? { - return null - } + override fun removeStickyBroadcastAsUser( + intent: Intent, + user: UserHandle, + ) {} override fun registerReceiver( receiver: BroadcastReceiver?, filter: IntentFilter, - flags: Int - ): Intent? { - return null - } + ): Intent? = null + + override fun registerReceiver( + receiver: BroadcastReceiver?, + filter: IntentFilter, + flags: Int, + ): Intent? = null override fun registerReceiver( receiver: BroadcastReceiver, filter: IntentFilter, broadcastPermission: String?, - scheduler: Handler? - ): Intent? { - return null - } + scheduler: Handler?, + ): Intent? = null override fun registerReceiver( receiver: BroadcastReceiver, filter: IntentFilter, broadcastPermission: String?, scheduler: Handler?, - flags: Int - ): Intent? { - return null - } + flags: Int, + ): Intent? = null override fun unregisterReceiver(receiver: BroadcastReceiver) {} - override fun startService(service: Intent): ComponentName? { - return null - } - override fun startForegroundService(service: Intent): ComponentName? { - return null - } + override fun startService(service: Intent): ComponentName? = null - override fun stopService(service: Intent): Boolean { - return false - } + override fun startForegroundService(service: Intent): ComponentName? = null - override fun bindService(service: Intent, conn: ServiceConnection, flags: Int): Boolean { - return false - } + override fun stopService(service: Intent): Boolean = false + + override fun bindService( + service: Intent, + conn: ServiceConnection, + flags: Int, + ): Boolean = false override fun unbindService(conn: ServiceConnection) {} + override fun startInstrumentation( className: ComponentName, profileFile: String?, - arguments: Bundle? - ): Boolean { - return false - } + arguments: Bundle?, + ): Boolean = false - override fun checkSelfPermission(permission: String): Int { - return 0 - } + override fun checkSelfPermission(permission: String): Int = 0 - override fun enforcePermission(permission: String, pid: Int, uid: Int, message: String?) {} - override fun enforceCallingPermission(permission: String, message: String?) {} - override fun enforceCallingOrSelfPermission(permission: String, message: String?) {} - override fun grantUriPermission(toPackage: String, uri: Uri, modeFlags: Int) {} - override fun revokeUriPermission(uri: Uri, modeFlags: Int) {} - override fun revokeUriPermission(toPackage: String, uri: Uri, modeFlags: Int) {} - override fun checkUriPermission(uri: Uri, pid: Int, uid: Int, modeFlags: Int): Int { - return 0 - } + override fun enforcePermission( + permission: String, + pid: Int, + uid: Int, + message: String?, + ) {} - override fun checkCallingUriPermission(uri: Uri, modeFlags: Int): Int { - return 0 - } + override fun enforceCallingPermission( + permission: String, + message: String?, + ) {} - override fun checkCallingOrSelfUriPermission(uri: Uri, modeFlags: Int): Int { - return 0 - } + override fun enforceCallingOrSelfPermission( + permission: String, + message: String?, + ) {} + + override fun grantUriPermission( + toPackage: String, + uri: Uri, + modeFlags: Int, + ) {} + + override fun revokeUriPermission( + uri: Uri, + modeFlags: Int, + ) {} + + override fun revokeUriPermission( + toPackage: String, + uri: Uri, + modeFlags: Int, + ) {} + + override fun checkUriPermission( + uri: Uri, + pid: Int, + uid: Int, + modeFlags: Int, + ): Int = 0 + + override fun checkCallingUriPermission( + uri: Uri, + modeFlags: Int, + ): Int = 0 + + override fun checkCallingOrSelfUriPermission( + uri: Uri, + modeFlags: Int, + ): Int = 0 override fun checkUriPermission( uri: Uri?, @@ -243,22 +296,30 @@ class MockContext : Context() { writePermission: String?, pid: Int, uid: Int, - modeFlags: Int - ): Int { - return 0 - } + modeFlags: Int, + ): Int = 0 override fun enforceUriPermission( uri: Uri, pid: Int, uid: Int, modeFlags: Int, - message: String + message: String, ) { } - override fun enforceCallingUriPermission(uri: Uri, modeFlags: Int, message: String) {} - override fun enforceCallingOrSelfUriPermission(uri: Uri, modeFlags: Int, message: String) {} + override fun enforceCallingUriPermission( + uri: Uri, + modeFlags: Int, + message: String, + ) {} + + override fun enforceCallingOrSelfUriPermission( + uri: Uri, + modeFlags: Int, + message: String, + ) {} + override fun enforceUriPermission( uri: Uri?, readPermission: String?, @@ -266,166 +327,109 @@ class MockContext : Context() { pid: Int, uid: Int, modeFlags: Int, - message: String? + message: String?, ) { } @Throws(NameNotFoundException::class) - override fun createPackageContext(packageName: String, flags: Int): Context? { - return null - } + override fun createPackageContext( + packageName: String, + flags: Int, + ): Context? = null @Throws(NameNotFoundException::class) - override fun createContextForSplit(splitName: String): Context? { - return null - } + override fun createContextForSplit(splitName: String): Context? = null - override fun createConfigurationContext(overrideConfiguration: Configuration): Context? { - return null - } + override fun createConfigurationContext(overrideConfiguration: Configuration): Context? = null - override fun createDisplayContext(display: Display): Context? { - return null - } + override fun createDisplayContext(display: Display): Context? = null - override fun createDeviceProtectedStorageContext(): Context? { - return null - } + override fun createDeviceProtectedStorageContext(): Context? = null - override fun isDeviceProtectedStorage(): Boolean { - return false - } + override fun isDeviceProtectedStorage(): Boolean = false - override fun moveSharedPreferencesFrom(sourceContext: Context, name: String): Boolean { - return false - } + override fun moveSharedPreferencesFrom( + sourceContext: Context, + name: String, + ): Boolean = false - override fun deleteSharedPreferences(name: String): Boolean { - return false - } + override fun deleteSharedPreferences(name: String): Boolean = false @Throws(FileNotFoundException::class) - override fun openFileInput(name: String): FileInputStream? { - return null - } + override fun openFileInput(name: String): FileInputStream? = null @Throws(FileNotFoundException::class) - override fun openFileOutput(name: String, mode: Int): FileOutputStream? { - return null - } + override fun openFileOutput( + name: String, + mode: Int, + ): FileOutputStream? = null - override fun deleteFile(name: String): Boolean { - return false - } + override fun deleteFile(name: String): Boolean = false - override fun getFileStreamPath(name: String): File? { - return null - } + override fun getFileStreamPath(name: String): File? = null - override fun getDataDir(): File? { - return null - } + override fun getDataDir(): File? = null - override fun getFilesDir(): File? { - return null - } + override fun getFilesDir(): File? = null - override fun getNoBackupFilesDir(): File? { - return null - } + override fun getNoBackupFilesDir(): File? = null - override fun getExternalFilesDir(type: String?): File? { - return null - } + override fun getExternalFilesDir(type: String?): File? = null - override fun getExternalFilesDirs(type: String): Array { - return arrayOfNulls(0) - } + override fun getExternalFilesDirs(type: String): Array = arrayOfNulls(0) - override fun getObbDir(): File? { - return null - } + override fun getObbDir(): File? = null - override fun getObbDirs(): Array { - return arrayOfNulls(0) - } + override fun getObbDirs(): Array = arrayOfNulls(0) - override fun getCacheDir(): File? { - return null - } + override fun getCacheDir(): File? = null - override fun getCodeCacheDir(): File? { - return null - } + override fun getCodeCacheDir(): File? = null - override fun getExternalCacheDir(): File? { - return null - } + override fun getExternalCacheDir(): File? = null - override fun getExternalCacheDirs(): Array { - return arrayOfNulls(0) - } + override fun getExternalCacheDirs(): Array = arrayOfNulls(0) - override fun getExternalMediaDirs(): Array { - return arrayOfNulls(0) - } + override fun getExternalMediaDirs(): Array = arrayOfNulls(0) - override fun fileList(): Array { - return arrayOfNulls(0) - } + override fun fileList(): Array = arrayOfNulls(0) - override fun getDir(name: String, mode: Int): File? { - return null - } + override fun getDir( + name: String, + mode: Int, + ): File? = null override fun openOrCreateDatabase( name: String, mode: Int, - factory: CursorFactory - ): SQLiteDatabase? { - return null - } + factory: CursorFactory, + ): SQLiteDatabase? = null override fun openOrCreateDatabase( name: String, mode: Int, factory: CursorFactory, - errorHandler: DatabaseErrorHandler? - ): SQLiteDatabase? { - return null - } + errorHandler: DatabaseErrorHandler?, + ): SQLiteDatabase? = null - override fun moveDatabaseFrom(sourceContext: Context, name: String): Boolean { - return false - } + override fun moveDatabaseFrom( + sourceContext: Context, + name: String, + ): Boolean = false - override fun deleteDatabase(name: String): Boolean { - return false - } + override fun deleteDatabase(name: String): Boolean = false - override fun getDatabasePath(name: String): File? { - return null - } + override fun getDatabasePath(name: String): File? = null - override fun databaseList(): Array { - return arrayOfNulls(0) - } + override fun databaseList(): Array = arrayOfNulls(0) - override fun getWallpaper(): Drawable? { - return null - } + override fun getWallpaper(): Drawable? = null - override fun peekWallpaper(): Drawable? { - return null - } + override fun peekWallpaper(): Drawable? = null - override fun getWallpaperDesiredMinimumWidth(): Int { - return 0 - } + override fun getWallpaperDesiredMinimumWidth(): Int = 0 - override fun getWallpaperDesiredMinimumHeight(): Int { - return 0 - } + override fun getWallpaperDesiredMinimumHeight(): Int = 0 @Throws(IOException::class) override fun setWallpaper(bitmap: Bitmap) { @@ -440,16 +444,26 @@ class MockContext : Context() { } override fun startActivity(intent: Intent) {} - override fun startActivity(intent: Intent, options: Bundle?) {} + + override fun startActivity( + intent: Intent, + options: Bundle?, + ) {} + override fun startActivities(intents: Array) {} - override fun startActivities(intents: Array, options: Bundle) {} + + override fun startActivities( + intents: Array, + options: Bundle, + ) {} + @Throws(SendIntentException::class) override fun startIntentSender( intent: IntentSender, fillInIntent: Intent?, flagsMask: Int, flagsValues: Int, - extraFlags: Int + extraFlags: Int, ) { } @@ -460,39 +474,27 @@ class MockContext : Context() { flagsMask: Int, flagsValues: Int, extraFlags: Int, - options: Bundle? + options: Bundle?, ) { } - override fun getSystemServiceName(serviceClass: Class<*>): String? { - return null - } + override fun getSystemServiceName(serviceClass: Class<*>): String? = null - override fun checkPermission(permission: String, pid: Int, uid: Int): Int { - return 0 - } + override fun checkPermission( + permission: String, + pid: Int, + uid: Int, + ): Int = 0 - override fun checkCallingPermission(permission: String): Int { - return 0 - } + override fun checkCallingPermission(permission: String): Int = 0 - override fun getContentResolver(): ContentResolver? { - return null - } + override fun getContentResolver(): ContentResolver? = null - override fun getMainLooper(): Looper? { - return null - } + override fun getMainLooper(): Looper? = null - override fun getPackageResourcePath(): String? { - return null - } + override fun getPackageResourcePath(): String? = null - override fun getPackageCodePath(): String? { - return null - } + override fun getPackageCodePath(): String? = null - override fun getAssets(): AssetManager? { - return null - } + override fun getAssets(): AssetManager? = null } diff --git a/src/test/kotlin/com/mparticle/kits/mocks/MockContextApplication.kt b/src/test/kotlin/com/mparticle/kits/mocks/MockContextApplication.kt index c49cf04..274af78 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockContextApplication.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockContextApplication.kt @@ -1,21 +1,19 @@ package com.mparticle.kits.mocks import android.app.Application -import android.content.SharedPreferences -import com.mparticle.kits.mocks.MockSharedPreferences import android.app.Application.ActivityLifecycleCallbacks import android.content.Context +import android.content.SharedPreferences class MockContextApplication : Application() { - override fun getApplicationContext(): Context { - return this - } + override fun getApplicationContext(): Context = this - override fun getSharedPreferences(name: String, mode: Int): SharedPreferences { - return MockSharedPreferences() - } + override fun getSharedPreferences( + name: String, + mode: Int, + ): SharedPreferences = MockSharedPreferences() override fun registerActivityLifecycleCallbacks(callback: ActivityLifecycleCallbacks) { - //do nothing + // do nothing } } diff --git a/src/test/kotlin/com/mparticle/kits/mocks/MockCoreCallbacks.kt b/src/test/kotlin/com/mparticle/kits/mocks/MockCoreCallbacks.kt index 758b9f4..fe538f4 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockCoreCallbacks.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockCoreCallbacks.kt @@ -1,71 +1,70 @@ package com.mparticle.kits.mocks -import com.mparticle.internal.CoreCallbacks -import java.lang.ref.WeakReference import android.app.Activity -import com.mparticle.MParticleOptions.DataplanOptions import android.net.Uri +import com.mparticle.MParticleOptions.DataplanOptions +import com.mparticle.internal.CoreCallbacks import com.mparticle.internal.CoreCallbacks.KitListener import org.json.JSONArray +import java.lang.ref.WeakReference class MockCoreCallbacks : CoreCallbacks { - override fun isBackgrounded(): Boolean { - return false - } + override fun isBackgrounded(): Boolean = false - override fun getUserBucket(): Int { - return 0 - } + override fun getUserBucket(): Int = 0 - override fun isEnabled(): Boolean { - return false - } + override fun isEnabled(): Boolean = false - override fun setIntegrationAttributes(kitId: Int, integrationAttributes: Map) {} - override fun getIntegrationAttributes(kitId: Int): Map? { - return null - } + override fun setIntegrationAttributes( + kitId: Int, + integrationAttributes: Map, + ) {} - override fun getCurrentActivity(): WeakReference? { - return null - } + override fun getIntegrationAttributes(kitId: Int): Map? = null - override fun getLatestKitConfiguration(): JSONArray? { - return null - } + override fun getCurrentActivity(): WeakReference? = null - override fun getDataplanOptions(): DataplanOptions? { - return null - } + override fun getLatestKitConfiguration(): JSONArray? = null - override fun isPushEnabled(): Boolean { - return false - } + override fun getDataplanOptions(): DataplanOptions? = null - override fun getPushSenderId(): String? { - return null - } + override fun isPushEnabled(): Boolean = false - override fun getPushInstanceId(): String? { - return null - } + override fun getPushSenderId(): String? = null - override fun getLaunchUri(): Uri? { - return null - } + override fun getPushInstanceId(): String? = null - override fun getLaunchAction(): String? { - return null - } + override fun getLaunchUri(): Uri? = null - override fun getKitListener(): KitListener { - return object : KitListener { + override fun getLaunchAction(): String? = null + + override fun getKitListener(): KitListener = + object : KitListener { override fun kitFound(kitId: Int) {} - override fun kitConfigReceived(kitId: Int, configuration: String?) {} - override fun kitExcluded(kitId: Int, reason: String?) {} + + override fun kitConfigReceived( + kitId: Int, + configuration: String?, + ) {} + + override fun kitExcluded( + kitId: Int, + reason: String?, + ) {} + override fun kitStarted(kitId: Int) {} - override fun onKitApiCalled(kitId: Int, used: Boolean?, vararg objects: Any?) {} - override fun onKitApiCalled(methodName: String?, kitId: Int, used: Boolean?, vararg objects: Any?) {} + + override fun onKitApiCalled( + kitId: Int, + used: Boolean?, + vararg objects: Any?, + ) {} + + override fun onKitApiCalled( + methodName: String?, + kitId: Int, + used: Boolean?, + vararg objects: Any?, + ) {} } - } } diff --git a/src/test/kotlin/com/mparticle/kits/mocks/MockKitConfiguration.kt b/src/test/kotlin/com/mparticle/kits/mocks/MockKitConfiguration.kt index e2e7d88..556310a 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockKitConfiguration.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockKitConfiguration.kt @@ -1,14 +1,12 @@ package com.mparticle.kits.mocks -import com.mparticle.kits.KitConfiguration -import kotlin.Throws -import com.mparticle.kits.mocks.MockKitConfiguration.MockSparseBooleanArray import android.util.SparseBooleanArray import com.mparticle.internal.Logger -import java.util.HashMap -import com.mparticle.kits.mocks.MockKitConfiguration +import com.mparticle.kits.KitConfiguration import org.json.JSONException import org.json.JSONObject +import java.util.HashMap +import kotlin.Throws open class MockKitConfiguration : KitConfiguration() { @Throws(JSONException::class) @@ -40,11 +38,12 @@ open class MockKitConfiguration : KitConfiguration() { } internal inner class MockSparseBooleanArray : SparseBooleanArray() { - override fun get(key: Int): Boolean { - return get(key, false) - } + override fun get(key: Int): Boolean = get(key, false) - override fun get(key: Int, valueIfKeyNotFound: Boolean): Boolean { + override fun get( + key: Int, + valueIfKeyNotFound: Boolean, + ): Boolean { print("SparseArray getting: $key") return if (map.containsKey(key)) { true @@ -54,7 +53,11 @@ open class MockKitConfiguration : KitConfiguration() { } var map: MutableMap = HashMap() - override fun put(key: Int, value: Boolean) { + + override fun put( + key: Int, + value: Boolean, + ) { map[key] = value } @@ -62,20 +65,14 @@ open class MockKitConfiguration : KitConfiguration() { map.clear() } - override fun size(): Int { - return map.size - } + override fun size(): Int = map.size - override fun toString(): String { - return map.toString() - } + override fun toString(): String = map.toString() } companion object { @Throws(JSONException::class) - fun createKitConfiguration(json: JSONObject): KitConfiguration { - return MockKitConfiguration().parseConfiguration(json) - } + fun createKitConfiguration(json: JSONObject): KitConfiguration = MockKitConfiguration().parseConfiguration(json) @Throws(JSONException::class) fun createKitConfiguration(): KitConfiguration { diff --git a/src/test/kotlin/com/mparticle/kits/mocks/MockKitManagerImpl.kt b/src/test/kotlin/com/mparticle/kits/mocks/MockKitManagerImpl.kt index 25ba807..eb493b2 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockKitManagerImpl.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockKitManagerImpl.kt @@ -1,51 +1,71 @@ package com.mparticle.kits.mocks import android.content.Context -import com.mparticle.internal.ReportingManager -import com.mparticle.internal.CoreCallbacks -import com.mparticle.kits.KitManagerImpl -import org.mockito.Mockito import com.mparticle.MParticleOptions -import com.mparticle.kits.mocks.MockContext +import com.mparticle.internal.CoreCallbacks import com.mparticle.internal.CoreCallbacks.KitListener -import kotlin.Throws +import com.mparticle.internal.ReportingManager import com.mparticle.kits.KitConfiguration -import com.mparticle.kits.mocks.MockKitConfiguration +import com.mparticle.kits.KitManagerImpl import org.json.JSONException import org.json.JSONObject +import org.mockito.Mockito +import kotlin.Throws class MockKitManagerImpl( context: Context?, reportingManager: ReportingManager?, - coreCallbacks: CoreCallbacks? + coreCallbacks: CoreCallbacks?, ) : KitManagerImpl( - context, reportingManager, coreCallbacks, Mockito.mock( - MParticleOptions::class.java - ) -) { + context, + reportingManager, + coreCallbacks, + Mockito.mock( + MParticleOptions::class.java, + ), + ) { constructor() : this( MockContext(), Mockito.mock(ReportingManager::class.java), Mockito.mock( - CoreCallbacks::class.java - ) + CoreCallbacks::class.java, + ), ) { - Mockito.`when`(mCoreCallbacks.getKitListener()).thenReturn(object : KitListener { - override fun kitFound(kitId: Int) {} - override fun kitConfigReceived(kitId: Int, configuration: String?) {} - override fun kitExcluded(kitId: Int, reason: String?) {} - override fun kitStarted(kitId: Int) {} - override fun onKitApiCalled(kitId: Int, used: Boolean?, vararg objects: Any?) {} - override fun onKitApiCalled(methodName: String?, kitId: Int, used: Boolean?, vararg objects: Any?) {} - }) + Mockito.`when`(mCoreCallbacks.getKitListener()).thenReturn( + object : KitListener { + override fun kitFound(kitId: Int) {} + + override fun kitConfigReceived( + kitId: Int, + configuration: String?, + ) {} + + override fun kitExcluded( + kitId: Int, + reason: String?, + ) {} + + override fun kitStarted(kitId: Int) {} + + override fun onKitApiCalled( + kitId: Int, + used: Boolean?, + vararg objects: Any?, + ) {} + + override fun onKitApiCalled( + methodName: String?, + kitId: Int, + used: Boolean?, + vararg objects: Any?, + ) {} + }, + ) } @Throws(JSONException::class) - override fun createKitConfiguration(configuration: JSONObject): KitConfiguration { - return MockKitConfiguration.createKitConfiguration(configuration) - } + override fun createKitConfiguration(configuration: JSONObject): KitConfiguration = + MockKitConfiguration.createKitConfiguration(configuration) - override fun getUserBucket(): Int { - return 50 - } + override fun getUserBucket(): Int = 50 } diff --git a/src/test/kotlin/com/mparticle/kits/mocks/MockResources.kt b/src/test/kotlin/com/mparticle/kits/mocks/MockResources.kt index b7c1d99..4b2dca6 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockResources.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockResources.kt @@ -1,12 +1,15 @@ package com.mparticle.kits.mocks import android.content.res.Resources -import kotlin.Throws import android.content.res.Resources.NotFoundException -import com.mparticle.kits.mocks.MockResources +import kotlin.Throws class MockResources : Resources(null, null, null) { - override fun getIdentifier(name: String, defType: String, defPackage: String): Int { + override fun getIdentifier( + name: String, + defType: String, + defPackage: String, + ): Int { if (name == "mp_key") { return 1 } else if (name == "mp_secret") { @@ -18,19 +21,20 @@ class MockResources : Resources(null, null, null) { @Throws(NotFoundException::class) override fun getString(id: Int): String { when (id) { - 1 -> return TEST_APP_KEY - 2 -> return TEST_APP_SECRET + 1 -> return testAppKey + 2 -> return testAppSecret } return "" } @Throws(NotFoundException::class) - override fun getString(id: Int, vararg formatArgs: Any): String { - return super.getString(id, *formatArgs) - } + override fun getString( + id: Int, + vararg formatArgs: Any, + ): String = super.getString(id, *formatArgs) companion object { - var TEST_APP_KEY = "the app key" - var TEST_APP_SECRET = "the app secret" + var testAppKey = "the app key" + var testAppSecret = "the app secret" } } diff --git a/src/test/kotlin/com/mparticle/kits/mocks/MockSharedPreferences.kt b/src/test/kotlin/com/mparticle/kits/mocks/MockSharedPreferences.kt index 55fd669..70f5609 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockSharedPreferences.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockSharedPreferences.kt @@ -2,24 +2,43 @@ package com.mparticle.kits.mocks import android.content.SharedPreferences import android.content.SharedPreferences.Editor -import java.util.TreeSet import android.content.SharedPreferences.OnSharedPreferenceChangeListener +import java.util.TreeSet -class MockSharedPreferences : SharedPreferences, Editor { - +class MockSharedPreferences : + SharedPreferences, + Editor { override fun getAll(): Map? = null - override fun getString(key: String, defValue: String?): String = "" + override fun getString( + key: String, + defValue: String?, + ): String = "" - override fun getStringSet(key: String, defValues: Set?): Set = TreeSet() + override fun getStringSet( + key: String, + defValues: Set?, + ): Set = TreeSet() - override fun getInt(key: String, defValue: Int): Int = 0 + override fun getInt( + key: String, + defValue: Int, + ): Int = 0 - override fun getLong(key: String, defValue: Long): Long = 0 + override fun getLong( + key: String, + defValue: Long, + ): Long = 0 - override fun getFloat(key: String, defValue: Float): Float = 0f + override fun getFloat( + key: String, + defValue: Float, + ): Float = 0f - override fun getBoolean(key: String, defValue: Boolean): Boolean = false + override fun getBoolean( + key: String, + defValue: Boolean, + ): Boolean = false override fun contains(key: String): Boolean = false @@ -29,17 +48,35 @@ class MockSharedPreferences : SharedPreferences, Editor { override fun unregisterOnSharedPreferenceChangeListener(listener: OnSharedPreferenceChangeListener) {} - override fun putString(key: String, value: String?): Editor = this - - override fun putStringSet(key: String, values: Set?): Editor = this - - override fun putInt(key: String, value: Int): Editor = this - - override fun putLong(key: String, value: Long): Editor = this - - override fun putFloat(key: String, value: Float): Editor = this - - override fun putBoolean(key: String, value: Boolean): Editor = this + override fun putString( + key: String, + value: String?, + ): Editor = this + + override fun putStringSet( + key: String, + values: Set?, + ): Editor = this + + override fun putInt( + key: String, + value: Int, + ): Editor = this + + override fun putLong( + key: String, + value: Long, + ): Editor = this + + override fun putFloat( + key: String, + value: Float, + ): Editor = this + + override fun putBoolean( + key: String, + value: Boolean, + ): Editor = this override fun remove(key: String): Editor = this diff --git a/src/test/kotlin/com/mparticle/kits/mocks/MockUser.kt b/src/test/kotlin/com/mparticle/kits/mocks/MockUser.kt index ddd7093..35125bb 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockUser.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockUser.kt @@ -4,11 +4,12 @@ import com.mparticle.MParticle.IdentityType import com.mparticle.UserAttributeListenerType import com.mparticle.audience.AudienceResponse import com.mparticle.audience.AudienceTask -import com.mparticle.identity.MParticleUser import com.mparticle.consent.ConsentState +import com.mparticle.identity.MParticleUser -class MockUser(var identities: Map) : MParticleUser { - +class MockUser( + var identities: Map, +) : MParticleUser { override fun getId(): Long = 0 override fun getUserAttributes(): Map = mapOf() @@ -19,11 +20,20 @@ class MockUser(var identities: Map) : MParticleUser { override fun getUserIdentities(): Map = identities - 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(p0: String, p1: Number?): Boolean = false + override fun incrementUserAttribute( + p0: String, + p1: Number?, + ): Boolean = false override fun removeUserAttribute(s: String): Boolean = false @@ -33,15 +43,11 @@ class MockUser(var identities: Map) : MParticleUser { override fun setConsentState(consentState: ConsentState?) {} - override fun isLoggedIn(): Boolean =false + override fun isLoggedIn(): Boolean = false 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") }