diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..7b2c5be --- /dev/null +++ b/.editorconfig @@ -0,0 +1,25 @@ +# https://editorconfig.org/ + +# top-most EditorConfig file +root = true + +[*] +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true +insert_final_newline = true +# don't set end_of_line; let correct git setting checkout the appropriate one for OS +charset = utf-8 + +[*.{json,yml,yaml,html,tf}] +indent_size = 2 +ij_json_array_wrapping = normal + +[*.{kt,kts}] +ktlint_code_style = intellij_idea +max_line_length = 120 +ij_kotlin_allow_trailing_comma = true +ij_kotlin_allow_trailing_comma_on_call_site = true + +[*Test.{kt,kts}] +ktlint_standard_max-line-length = disabled diff --git a/build.gradle b/build.gradle index 47bd91e..debbef4 100644 --- a/build.gradle +++ b/build.gradle @@ -18,7 +18,7 @@ buildscript { plugins { id "org.sonarqube" version "3.5.0.2730" - id "org.jlleitschuh.gradle.ktlint" version "11.2.0" + id "org.jlleitschuh.gradle.ktlint" version "13.0.0" } sonarqube { @@ -65,3 +65,10 @@ dependencies { testImplementation ("io.mockk:mockk:1.13.4") testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4' } + +ktlint { + android = true + reporters { + reporter "html" + } +} diff --git a/src/main/kotlin/com/mparticle/kits/RoktKit.kt b/src/main/kotlin/com/mparticle/kits/RoktKit.kt index e58ec2f..eececa4 100644 --- a/src/main/kotlin/com/mparticle/kits/RoktKit.kt +++ b/src/main/kotlin/com/mparticle/kits/RoktKit.kt @@ -35,13 +35,20 @@ import kotlinx.coroutines.flow.map import java.lang.ref.WeakReference import java.math.BigDecimal +const val ROKT_ATTRIBUTE_SANDBOX_MODE: String = "sandbox" + /** * MParticle embedded implementation of the Rokt Library. * * Learn more at our [Developer Docs](https://docs.rokt.com/developers/integration-guides/android) */ + @Suppress("unused") -class RoktKit : KitIntegration(), CommerceListener, IdentityListener, RoktListener, +class RoktKit : + KitIntegration(), + CommerceListener, + IdentityListener, + RoktListener, Rokt.RoktCallback { private var applicationContext: Context? = null private var mpRoktEventCallback: MpRoktEventCallback? = null @@ -49,10 +56,7 @@ class RoktKit : KitIntegration(), CommerceListener, IdentityListener, RoktListen override fun getInstance(): RoktKit = this - public override fun onKitCreate( - settings: Map, - ctx: Context - ): List { + public override fun onKitCreate(settings: Map, ctx: Context): List { applicationContext = ctx.applicationContext val roktTagId = settings[ROKT_ACCOUNT_ID] if (KitUtils.isEmpty(roktTagId)) { @@ -65,7 +69,7 @@ class RoktKit : KitIntegration(), CommerceListener, IdentityListener, RoktListen val info = manager.getPackageInfoForApp(context.packageName, 0) val application = context.applicationContext as Application val mparticleVersion = BuildConfig.VERSION_NAME - + // Get RoktOptions from the kit manager val roktOptions = kitManager?.roktOptions val fontFilePathMap = roktOptions?.fontFilePathMap ?: emptyMap() @@ -83,9 +87,8 @@ class RoktKit : KitIntegration(), CommerceListener, IdentityListener, RoktListen } }, mParticleSdkVersion = mparticleVersion, - mParticleKitVersion = mparticleVersion + mParticleKitVersion = mparticleVersion, ) - } catch (e: PackageManager.NameNotFoundException) { throwOnKitCreateError(NO_APP_VERSION_FOUND) } catch (e: Exception) { @@ -106,38 +109,38 @@ class RoktKit : KitIntegration(), CommerceListener, IdentityListener, RoktListen * Overrides for CommerceListener */ override fun logLtvIncrease( - bigDecimal: BigDecimal, bigDecimal1: BigDecimal, - s: String, map: Map + bigDecimal: BigDecimal, + bigDecimal1: BigDecimal, + s: String, + map: Map, ): List = emptyList() - override fun logEvent(commerceEvent: CommerceEvent): List { - return emptyList() - } + override fun logEvent(commerceEvent: CommerceEvent): List = emptyList() /* * Overrides for IdentityListener */ override fun onIdentifyCompleted( mParticleUser: MParticleUser, - filteredIdentityApiRequest: FilteredIdentityApiRequest + filteredIdentityApiRequest: FilteredIdentityApiRequest, ) { } override fun onLoginCompleted( mParticleUser: MParticleUser, - filteredIdentityApiRequest: FilteredIdentityApiRequest + filteredIdentityApiRequest: FilteredIdentityApiRequest, ) { } override fun onLogoutCompleted( mParticleUser: MParticleUser, - filteredIdentityApiRequest: FilteredIdentityApiRequest + filteredIdentityApiRequest: FilteredIdentityApiRequest, ) { } override fun onModifyCompleted( mParticleUser: MParticleUser, - filteredIdentityApiRequest: FilteredIdentityApiRequest + filteredIdentityApiRequest: FilteredIdentityApiRequest, ) { } @@ -147,14 +150,12 @@ class RoktKit : KitIntegration(), CommerceListener, IdentityListener, RoktListen Logger.error(t, "RoktKit: $message") } - private fun throwOnKitCreateError(message: String) { - throw IllegalArgumentException(message) - } + private fun throwOnKitCreateError(message: String): Unit = throw IllegalArgumentException(message) /* For more details, visit the official documentation: https://docs.rokt.com/developers/integration-guides/android/how-to/adding-a-placement/ - */ + */ override fun execute( viewName: String, attributes: Map, @@ -162,28 +163,24 @@ class RoktKit : KitIntegration(), CommerceListener, IdentityListener, RoktListen placeHolders: MutableMap>?, fontTypefaces: MutableMap>?, filterUser: FilteredMParticleUser?, - mpRoktConfig: RoktConfig? + mpRoktConfig: RoktConfig?, ) { val placeholders: Map>? = placeHolders?.mapNotNull { entry -> val widget = Widget(entry.value.get()?.context as Context) entry.value.get()?.removeAllViews() entry.value.get()?.addView(widget) entry.value.get()?.dimensionCallBack?.let { - widget.registerDimensionListener(object: RoktWidgetDimensionCallBack { - override fun onHeightChanged(height: Int) { - it.onHeightChanged(height) - } - - override fun onMarginChanged( - start: Int, - top: Int, - end: Int, - bottom: Int - ) { - it.onMarginChanged(start, top, end, bottom) - } - - }) + widget.registerDimensionListener( + object : RoktWidgetDimensionCallBack { + override fun onHeightChanged(height: Int) { + it.onHeightChanged(height) + } + + override fun onMarginChanged(start: Int, top: Int, end: Int, bottom: Int) { + it.onMarginChanged(start, top, end, bottom) + } + }, + ) } entry.key to WeakReference(widget) }?.toMap() @@ -202,10 +199,8 @@ class RoktKit : KitIntegration(), CommerceListener, IdentityListener, RoktListen addIdentityAttributes(finalAttributes, filterUser) - - val SANDBOX_MODE_ROKT: String = "sandbox" - attributes?.get(SANDBOX_MODE_ROKT)?.let { value -> - finalAttributes.put(SANDBOX_MODE_ROKT, value) + attributes[ROKT_ATTRIBUTE_SANDBOX_MODE]?.let { value -> + finalAttributes.put(ROKT_ATTRIBUTE_SANDBOX_MODE, value) } verifyHashedEmail(finalAttributes) val roktConfig = mpRoktConfig?.let { mapToRoktConfig(it) } @@ -216,47 +211,49 @@ class RoktKit : KitIntegration(), CommerceListener, IdentityListener, RoktListen // Pass placeholders and fontTypefaces only if they are not empty or null placeholders.takeIf { it?.isNotEmpty() == true }, fontTypefaces.takeIf { it?.isNotEmpty() == true }, - roktConfig + roktConfig, ) } - override fun events(identifier: String): Flow { - return Rokt.events(identifier) - .map { event -> - when (event) { - is RoktEvent.HideLoadingIndicator -> com.mparticle.RoktEvent.HideLoadingIndicator - is RoktEvent.ShowLoadingIndicator -> com.mparticle.RoktEvent.ShowLoadingIndicator - is RoktEvent.FirstPositiveEngagement -> com.mparticle.RoktEvent.FirstPositiveEngagement( - event.id - ) - is RoktEvent.PositiveEngagement -> com.mparticle.RoktEvent.PositiveEngagement( - event.id - ) - is RoktEvent.OfferEngagement -> com.mparticle.RoktEvent.OfferEngagement(event.id) - is RoktEvent.OpenUrl -> com.mparticle.RoktEvent.OpenUrl(event.id, event.url) - is RoktEvent.PlacementClosed -> com.mparticle.RoktEvent.PlacementClosed(event.id) - is RoktEvent.PlacementCompleted -> com.mparticle.RoktEvent.PlacementCompleted( - event.id - ) - is RoktEvent.PlacementFailure -> com.mparticle.RoktEvent.PlacementFailure(event.id) - is RoktEvent.PlacementInteractive -> com.mparticle.RoktEvent.PlacementInteractive( - event.id - ) - is RoktEvent.PlacementReady -> com.mparticle.RoktEvent.PlacementReady(event.id) - is RoktEvent.CartItemInstantPurchase -> com.mparticle.RoktEvent.CartItemInstantPurchase( - placementId = event.placementId, - cartItemId = event.cartItemId, - catalogItemId = event.catalogItemId, - currency = event.currency, - description = event.description, - linkedProductId = event.linkedProductId, - totalPrice = event.totalPrice, - quantity = event.quantity, - unitPrice = event.unitPrice - ) - is RoktEvent.InitComplete -> com.mparticle.RoktEvent.InitComplete(event.success) - } - } + override fun events(identifier: String): Flow = Rokt.events(identifier).map { event -> + when (event) { + is RoktEvent.HideLoadingIndicator -> com.mparticle.RoktEvent.HideLoadingIndicator + is RoktEvent.ShowLoadingIndicator -> com.mparticle.RoktEvent.ShowLoadingIndicator + is RoktEvent.FirstPositiveEngagement -> com.mparticle.RoktEvent.FirstPositiveEngagement( + event.id, + ) + + is RoktEvent.PositiveEngagement -> com.mparticle.RoktEvent.PositiveEngagement( + event.id, + ) + + is RoktEvent.OfferEngagement -> com.mparticle.RoktEvent.OfferEngagement(event.id) + is RoktEvent.OpenUrl -> com.mparticle.RoktEvent.OpenUrl(event.id, event.url) + is RoktEvent.PlacementClosed -> com.mparticle.RoktEvent.PlacementClosed(event.id) + is RoktEvent.PlacementCompleted -> com.mparticle.RoktEvent.PlacementCompleted( + event.id, + ) + + is RoktEvent.PlacementFailure -> com.mparticle.RoktEvent.PlacementFailure(event.id) + is RoktEvent.PlacementInteractive -> com.mparticle.RoktEvent.PlacementInteractive( + event.id, + ) + + is RoktEvent.PlacementReady -> com.mparticle.RoktEvent.PlacementReady(event.id) + is RoktEvent.CartItemInstantPurchase -> com.mparticle.RoktEvent.CartItemInstantPurchase( + placementId = event.placementId, + cartItemId = event.cartItemId, + catalogItemId = event.catalogItemId, + currency = event.currency, + description = event.description, + linkedProductId = event.linkedProductId, + totalPrice = event.totalPrice, + quantity = event.quantity, + unitPrice = event.unitPrice, + ) + + is RoktEvent.InitComplete -> com.mparticle.RoktEvent.InitComplete(event.success) + } } override fun setWrapperSdkVersion(wrapperSdkVersion: WrapperSdkVersion) { @@ -288,15 +285,13 @@ class RoktKit : KitIntegration(), CommerceListener, IdentityListener, RoktListen val cacheConfig = config.cacheConfig?.cacheDurationInSeconds?.let { CacheConfig( cacheDurationInSeconds = it, - cacheAttributes = config.cacheConfig?.cacheAttributes + cacheAttributes = config.cacheConfig?.cacheAttributes, ) } val edgeToEdgeDisplay = config.edgeToEdgeDisplay - val builder = com.rokt.roktsdk.RoktConfig.Builder() - .colorMode(colorMode) - .edgeToEdgeDisplay(edgeToEdgeDisplay) + val builder = com.rokt.roktsdk.RoktConfig.Builder().colorMode(colorMode).edgeToEdgeDisplay(edgeToEdgeDisplay) cacheConfig?.let { builder.cacheConfig(it) @@ -304,7 +299,10 @@ class RoktKit : KitIntegration(), CommerceListener, IdentityListener, RoktListen return builder.build() } - private fun addIdentityAttributes(attributes: MutableMap?, filterUser: FilteredMParticleUser?): MutableMap { + private fun addIdentityAttributes( + attributes: MutableMap?, + filterUser: FilteredMParticleUser?, + ): MutableMap { val identityAttributes = mutableMapOf() if (filterUser != null) { for ((identityNumberKey, identityValue) in filterUser.userIdentities) { @@ -342,32 +340,30 @@ class RoktKit : KitIntegration(), CommerceListener, IdentityListener, RoktListen } } - private fun getStringForIdentity(identityType: IdentityType): String { - return when (identityType) { - IdentityType.Other -> "emailsha256" - IdentityType.CustomerId -> "customerid" - IdentityType.Facebook -> "facebook" - IdentityType.Twitter -> "twitter" - IdentityType.Google -> "google" - IdentityType.Microsoft -> "microsoft" - IdentityType.Yahoo -> "yahoo" - IdentityType.Email -> "email" - IdentityType.Alias -> "alias" - IdentityType.FacebookCustomAudienceId -> "facebookcustomaudienceid" - IdentityType.Other2 -> "other2" - IdentityType.Other3 -> "other3" - IdentityType.Other4 -> "other4" - IdentityType.Other5 -> "other5" - IdentityType.Other6 -> "other6" - IdentityType.Other7 -> "other7" - IdentityType.Other8 -> "other8" - IdentityType.Other9 -> "other9" - IdentityType.Other10 -> "other10" - IdentityType.MobileNumber -> "mobilenumber" - IdentityType.PhoneNumber2 -> "phonenumber2" - IdentityType.PhoneNumber3 -> "phonenumber3" - else -> "" - } + private fun getStringForIdentity(identityType: IdentityType): String = when (identityType) { + IdentityType.Other -> "emailsha256" + IdentityType.CustomerId -> "customerid" + IdentityType.Facebook -> "facebook" + IdentityType.Twitter -> "twitter" + IdentityType.Google -> "google" + IdentityType.Microsoft -> "microsoft" + IdentityType.Yahoo -> "yahoo" + IdentityType.Email -> "email" + IdentityType.Alias -> "alias" + IdentityType.FacebookCustomAudienceId -> "facebookcustomaudienceid" + IdentityType.Other2 -> "other2" + IdentityType.Other3 -> "other3" + IdentityType.Other4 -> "other4" + IdentityType.Other5 -> "other5" + IdentityType.Other6 -> "other6" + IdentityType.Other7 -> "other7" + IdentityType.Other8 -> "other8" + IdentityType.Other9 -> "other9" + IdentityType.Other10 -> "other10" + IdentityType.MobileNumber -> "mobilenumber" + IdentityType.PhoneNumber2 -> "phonenumber2" + IdentityType.PhoneNumber3 -> "phonenumber3" + else -> "" } companion object { @@ -378,20 +374,19 @@ class RoktKit : KitIntegration(), CommerceListener, IdentityListener, RoktListen const val NO_APP_VERSION_FOUND = "No App version found, can't initialize kit." } - - override fun onLoad() : Unit{ + override fun onLoad() { mpRoktEventCallback?.onLoad() } - override fun onShouldHideLoadingIndicator() : Unit { + override fun onShouldHideLoadingIndicator() { mpRoktEventCallback?.onShouldHideLoadingIndicator() } - override fun onShouldShowLoadingIndicator() : Unit { + override fun onShouldShowLoadingIndicator() { mpRoktEventCallback?.onShouldShowLoadingIndicator() } - override fun onUnload(reason: Rokt.UnloadReasons) : Unit { + override fun onUnload(reason: Rokt.UnloadReasons) { mpRoktEventCallback?.onUnload( when (reason) { Rokt.UnloadReasons.NO_OFFERS -> UnloadReasons.NO_OFFERS @@ -402,7 +397,7 @@ class RoktKit : KitIntegration(), CommerceListener, IdentityListener, RoktListen Rokt.UnloadReasons.INIT_FAILED -> UnloadReasons.INIT_FAILED Rokt.UnloadReasons.UNKNOWN_PLACEHOLDER -> UnloadReasons.UNKNOWN_PLACEHOLDER Rokt.UnloadReasons.UNKNOWN -> UnloadReasons.UNKNOWN - } + }, ) } } @@ -411,5 +406,6 @@ fun PackageManager.getPackageInfoForApp(packageName: String, flags: Int = 0): Pa if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(flags.toLong())) } else { - @Suppress("DEPRECATION") getPackageInfo(packageName, flags) - } \ No newline at end of file + @Suppress("DEPRECATION") + getPackageInfo(packageName, flags) + } diff --git a/src/test/kotlin/com/mparticle/kits/RoktKitTests.kt b/src/test/kotlin/com/mparticle/kits/RoktKitTests.kt index 323354c..238b1aa 100644 --- a/src/test/kotlin/com/mparticle/kits/RoktKitTests.kt +++ b/src/test/kotlin/com/mparticle/kits/RoktKitTests.kt @@ -18,7 +18,14 @@ import com.mparticle.internal.CoreCallbacks.KitListener import com.rokt.roktsdk.FulfillmentAttributes import com.rokt.roktsdk.Rokt import com.rokt.roktsdk.RoktEvent -import io.mockk.* +import io.mockk.every +import io.mockk.just +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.runs +import io.mockk.unmockkObject +import io.mockk.verify +import io.mockk.verifyOrder import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.toList @@ -35,7 +42,6 @@ import java.lang.ref.WeakReference import java.lang.reflect.Field import java.lang.reflect.Method import java.lang.reflect.Modifier -import java.util.* class RoktKitTests { private val context = mockk(relaxed = true) @@ -53,34 +59,31 @@ class RoktKitTests { MParticle.setInstance(mock(MParticle::class.java)) Mockito.`when`(MParticle.getInstance()?.Identity()).thenReturn( mock( - IdentityApi::class.java - ) + IdentityApi::class.java, + ), ) val kitManager = KitManagerImpl( mock( - Context::class.java - ), null, emptyCoreCallbacks, mock(MParticleOptions::class.java) + Context::class.java, + ), + null, + emptyCoreCallbacks, + mock(MParticleOptions::class.java), ) - roktKit.kitManager = kitManager/* - roktKit.configuration = - KitConfiguration.createKitConfiguration(JSONObject().put("id", "-1"))*/ - + roktKit.kitManager = kitManager + // roktKit.configuration = KitConfiguration.createKitConfiguration(JSONObject().put("id", "-1")) } - - - private inner class TestKitManager internal constructor() : + private inner class TestKitManager : KitManagerImpl(context, null, TestCoreCallbacks(), mock(MParticleOptions::class.java)) { var attributes = HashMap() var result: AttributionResult? = null private var error: AttributionError? = null - public override fun getIntegrationAttributes(kitIntegration: KitIntegration): Map { - return attributes - } + public override fun getIntegrationAttributes(kitIntegration: KitIntegration): Map = attributes public override fun setIntegrationAttributes( kitIntegration: KitIntegration, - integrationAttributes: Map + integrationAttributes: Map, ) { attributes = integrationAttributes as HashMap } @@ -100,23 +103,22 @@ class RoktKitTests { private inner class TestMParticle : MParticle() { override fun Identity(): IdentityApi = mock(IdentityApi::class.java) - } @Test - fun test_addIdentityAttributes_When_userIdentities_IS_Null(){ + fun test_addIdentityAttributes_When_userIdentities_IS_Null() { val mockFilterUser = mock(FilteredMParticleUser::class.java) val userIdentities = HashMap() Mockito.`when`(mockFilterUser.userIdentities).thenReturn(userIdentities) val attributes: Map = mapOf( "key1" to "value1", "key2" to "value2", - "key3" to "value3" + "key3" to "value3", ) val method: Method = RoktKit::class.java.getDeclaredMethod( "addIdentityAttributes", Map::class.java, - FilteredMParticleUser::class.java + FilteredMParticleUser::class.java, ) method.isAccessible = true val result = method.invoke(roktKit, attributes, mockFilterUser) as Map @@ -128,20 +130,20 @@ class RoktKitTests { } @Test - fun test_addIdentityAttributes_When_userIdentities_Contain_value(){ + fun test_addIdentityAttributes_When_userIdentities_Contain_value() { val mockFilterUser = mock(FilteredMParticleUser::class.java) val userIdentities = HashMap() - userIdentities.put(IdentityType.Email,"TestEmail@gamil.com") + userIdentities.put(IdentityType.Email, "TestEmail@gamil.com") Mockito.`when`(mockFilterUser.userIdentities).thenReturn(userIdentities) val attributes: Map = mapOf( "key1" to "value1", "key2" to "value2", - "key3" to "value3" + "key3" to "value3", ) val method: Method = RoktKit::class.java.getDeclaredMethod( "addIdentityAttributes", Map::class.java, - FilteredMParticleUser::class.java + FilteredMParticleUser::class.java, ) method.isAccessible = true val result = method.invoke(roktKit, attributes, mockFilterUser) as Map @@ -151,25 +153,24 @@ class RoktKitTests { assertTrue(result.containsKey("key2")) assertTrue(result.containsKey("key3")) assertTrue(result.containsKey("email")) - } @Test - fun test_addIdentityAttributes_When_userIdentities_And_attributes_contains_same_key(){ + fun test_addIdentityAttributes_When_userIdentities_And_attributes_contains_same_key() { val mockFilterUser = mock(FilteredMParticleUser::class.java) val userIdentities = HashMap() - userIdentities.put(IdentityType.Email,"TestEmail@gamil.com") + userIdentities.put(IdentityType.Email, "TestEmail@gamil.com") Mockito.`when`(mockFilterUser.userIdentities).thenReturn(userIdentities) val attributes: Map = mapOf( "key1" to "value1", "key2" to "value2", "key3" to "value3", - "email" to "abc@gmail.com" + "email" to "abc@gmail.com", ) val method: Method = RoktKit::class.java.getDeclaredMethod( "addIdentityAttributes", Map::class.java, - FilteredMParticleUser::class.java + FilteredMParticleUser::class.java, ) method.isAccessible = true val result = method.invoke(roktKit, attributes, mockFilterUser) as Map @@ -184,9 +185,9 @@ class RoktKitTests { "key1" to "value1", "key2" to "value2", "key3" to "value3", - "email" to "TestEmail@gamil.com" + "email" to "TestEmail@gamil.com", ), - result + result, ) } @@ -195,10 +196,10 @@ class RoktKitTests { val method: Method = RoktKit::class.java.getDeclaredMethod( "addIdentityAttributes", Map::class.java, - FilteredMParticleUser::class.java + FilteredMParticleUser::class.java, ) method.isAccessible = true - val result = method.invoke(roktKit, null, null) as Map + val result = method.invoke(roktKit, null, null) as Map assertTrue(result.isEmpty()) } @@ -206,12 +207,12 @@ class RoktKitTests { fun testAddIdentityAttributes_nullAttributes_validUser() { val mockFilterUser = mock(FilteredMParticleUser::class.java) val userIdentities = HashMap() - userIdentities.put(IdentityType.Email,"TestEmail@gamil.com") + userIdentities.put(IdentityType.Email, "TestEmail@gamil.com") Mockito.`when`(mockFilterUser.userIdentities).thenReturn(userIdentities) val method: Method = RoktKit::class.java.getDeclaredMethod( "addIdentityAttributes", Map::class.java, - FilteredMParticleUser::class.java + FilteredMParticleUser::class.java, ) method.isAccessible = true val result = method.invoke(roktKit, null, mockFilterUser) as Map @@ -224,12 +225,12 @@ class RoktKitTests { val attributes: Map = mapOf( "key1" to "value1", "key2" to "value2", - "key3" to "value3" + "key3" to "value3", ) val method: Method = RoktKit::class.java.getDeclaredMethod( "addIdentityAttributes", Map::class.java, - FilteredMParticleUser::class.java + FilteredMParticleUser::class.java, ) method.isAccessible = true val result = method.invoke(roktKit, attributes, null) as Map @@ -249,12 +250,12 @@ class RoktKitTests { val attributes: Map = mapOf( "key1" to "value1", "key2" to "value2", - "key3" to "value3" + "key3" to "value3", ) val method: Method = RoktKit::class.java.getDeclaredMethod( "addIdentityAttributes", Map::class.java, - FilteredMParticleUser::class.java + FilteredMParticleUser::class.java, ) method.isAccessible = true val result = method.invoke(roktKit, attributes, mockFilterUser) as Map @@ -317,12 +318,12 @@ class RoktKitTests { fun testRoktEventMapping_FirstPositiveEngagement() = runTest { mockkObject(Rokt) val placementId = "test-placement-123" - val roktEvent = RoktEvent.FirstPositiveEngagement(placementId, + val roktEvent = RoktEvent.FirstPositiveEngagement( + placementId, object : FulfillmentAttributes { override fun sendAttributes(attributes: Map) { - } - } + }, ) every { Rokt.events(any()) } returns flowOf(roktEvent) @@ -462,23 +463,26 @@ class RoktKitTests { linkedProductId = "linked-product-789", totalPrice = 99.99, quantity = 2, - unitPrice = 49.99 + unitPrice = 49.99, ) every { Rokt.events(any()) } returns flowOf(roktEvent) val result = roktKit.events("").first() - assertEquals(result, com.mparticle.RoktEvent.CartItemInstantPurchase( - placementId = "test-placement-purchase", - cartItemId = "cart-item-123", - catalogItemId = "catalog-item-456", - currency = "USD", - description = "Test product description", - linkedProductId = "linked-product-789", - totalPrice = 99.99, - quantity = 2, - unitPrice = 49.99 - )) + assertEquals( + result, + com.mparticle.RoktEvent.CartItemInstantPurchase( + placementId = "test-placement-purchase", + cartItemId = "cart-item-123", + catalogItemId = "catalog-item-456", + currency = "USD", + description = "Test product description", + linkedProductId = "linked-product-789", + totalPrice = 99.99, + quantity = 2, + unitPrice = 49.99, + ), + ) unmockkObject(Rokt) } @@ -513,7 +517,7 @@ class RoktKitTests { val events = listOf( RoktEvent.ShowLoadingIndicator, RoktEvent.HideLoadingIndicator, - RoktEvent.InitComplete(true) + RoktEvent.InitComplete(true), ) every { Rokt.events(any()) } returns flowOf(*events.toTypedArray()) @@ -560,35 +564,33 @@ class RoktKitTests { } @Test - fun TestverifyHashedEmail_removes_when_emailsha256_is_present() { + fun testVerifyHashedEmail_removes_when_emailsha256_is_present() { val attributes = mutableMapOf( "email" to "user@example.com", "emailsha256" to "hashed_email_value", - "other" to "Test" + "other" to "Test", ) val method: Method = RoktKit::class.java.getDeclaredMethod( "verifyHashedEmail", - MutableMap::class.java + MutableMap::class.java, ) method.isAccessible = true method.invoke(roktKit, attributes) - assertFalse(attributes.containsKey("email")) assertEquals("hashed_email_value", attributes["emailsha256"]) assertEquals("Test", attributes["other"]) } - @Test - fun TestverifyHashedEmail_removes_when_neither_emailsha256_nor_other_is_present() { + fun testVerifyHashedEmail_removes_when_neither_emailsha256_nor_other_is_present() { val attributes = mutableMapOf( - "email" to "user@example.com" + "email" to "user@example.com", ) val method: Method = RoktKit::class.java.getDeclaredMethod( "verifyHashedEmail", - MutableMap::class.java + MutableMap::class.java, ) method.isAccessible = true method.invoke(roktKit, attributes) @@ -601,8 +603,8 @@ class RoktKitTests { override fun isBackgrounded(): Boolean = false override fun getUserBucket(): Int = 0 override fun isEnabled(): Boolean = false - override fun setIntegrationAttributes(i: Int, map: Map) {} - override fun getIntegrationAttributes(i: Int): Map? = null + override fun setIntegrationAttributes(kitId: Int, integrationAttributes: Map) {} + override fun getIntegrationAttributes(kitId: Int): Map? = null override fun getCurrentActivity(): WeakReference? = null override fun getLatestKitConfiguration(): JSONArray? = null override fun getDataplanOptions(): DataplanOptions? = null @@ -611,17 +613,15 @@ class RoktKitTests { override fun getPushInstanceId(): String? = null override fun getLaunchUri(): Uri? = null override fun getLaunchAction(): String? = null - override fun getKitListener(): KitListener { - return 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 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 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(methodName: String?, kitId: Int, used: Boolean?, vararg objects: Any?) { } } } @@ -633,8 +633,8 @@ class RoktKitTests { private const val TEST_KIT_ID = 0x01 /* - * Test Helpers - */ + * Test Helpers + */ @Throws(Exception::class) private fun setTestSdkVersion(sdkVersion: Int) { setFinalStatic(VERSION::class.java.getField("SDK_INT"), sdkVersion) @@ -643,11 +643,10 @@ class RoktKitTests { @Throws(Exception::class) private fun setFinalStatic(field: Field, newValue: Int) { field.isAccessible = true - val getDeclaredFields0 = - Class::class.java.getDeclaredMethod( - "getDeclaredFields0", - Boolean::class.javaPrimitiveType - ) + val getDeclaredFields0 = Class::class.java.getDeclaredMethod( + "getDeclaredFields0", + Boolean::class.javaPrimitiveType, + ) getDeclaredFields0.isAccessible = true val fields = getDeclaredFields0.invoke(Field::class.java, false) as Array var modifiersField: Field? = null @@ -658,9 +657,8 @@ class RoktKitTests { } } modifiersField!!.isAccessible = true - modifiersField!!.setInt(field, field.modifiers and Modifier.FINAL.inv()) + modifiersField.setInt(field, field.modifiers and Modifier.FINAL.inv()) field[null] = newValue - } } @@ -672,9 +670,9 @@ class RoktKitTests { override fun isEnabled(): Boolean = false - override fun setIntegrationAttributes(i: Int, map: Map) {} + override fun setIntegrationAttributes(kitId: Int, integrationAttributes: Map) {} - override fun getIntegrationAttributes(i: Int): Map? = null + override fun getIntegrationAttributes(kitId: Int): Map? = null override fun getCurrentActivity(): WeakReference = WeakReference(activity) @@ -692,15 +690,13 @@ class RoktKitTests { override fun getLaunchAction(): String? = null - override fun getKitListener(): KitListener { - return 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?) {} - } + 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 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?) {} } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/com/mparticle/kits/mocks/MockApplication.kt b/src/test/kotlin/com/mparticle/kits/mocks/MockApplication.kt index 2454c6e..8782e5d 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockApplication.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockApplication.kt @@ -13,35 +13,22 @@ class MockApplication(var mContext: MockContext) : Application() { 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..4f18060 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,7 +32,12 @@ 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() @@ -41,22 +54,16 @@ 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) { - Mockito.mock(TelephonyManager::class.java) - } else null + override fun getSystemService(name: String): Any? = if (name == TELEPHONY_SERVICE) { + Mockito.mock(TelephonyManager::class.java) + } else { + null } override fun getPackageManager(): PackageManager { @@ -66,12 +73,10 @@ class MockContext : Context() { info.versionCode = 42 val appInfo = Mockito.mock(ApplicationInfo::class.java) try { - Mockito.`when`(manager.getPackageInfo(Mockito.anyString(), Mockito.anyInt())) - .thenReturn(info) + Mockito.`when`(manager.getPackageInfo(Mockito.anyString(), Mockito.anyInt())).thenReturn(info) Mockito.`when`(manager.getInstallerPackageName(Mockito.anyString())) .thenReturn("com.mparticle.test.installer") - Mockito.`when`(manager.getApplicationInfo(Mockito.anyString(), Mockito.anyInt())) - .thenReturn(appInfo) + Mockito.`when`(manager.getApplicationInfo(Mockito.anyString(), Mockito.anyInt())).thenReturn(appInfo) Mockito.`when`(manager.getApplicationLabel(appInfo)).thenReturn("test label") } catch (e: Exception) { Assert.fail(e.toString()) @@ -79,25 +84,17 @@ 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 getTheme(): Theme? = null - override fun getClassLoader(): ClassLoader? { - return null - } + override fun getClassLoader(): ClassLoader? = null override fun sendBroadcast(intent: Intent) {} override fun sendBroadcast(intent: Intent, receiverPermission: String?) {} @@ -109,16 +106,12 @@ 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?) { } override fun sendOrderedBroadcastAsUser( @@ -129,7 +122,7 @@ class MockContext : Context() { scheduler: Handler?, initialCode: Int, initialData: String?, - initialExtras: Bundle? + initialExtras: Bundle?, ) { } @@ -140,7 +133,7 @@ class MockContext : Context() { scheduler: Handler?, initialCode: Int, initialData: String?, - initialExtras: Bundle? + initialExtras: Bundle?, ) { } @@ -153,71 +146,44 @@ 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 registerReceiver(receiver: BroadcastReceiver?, filter: IntentFilter): Intent? = null - override fun registerReceiver( - receiver: BroadcastReceiver?, - filter: IntentFilter, - flags: Int - ): Intent? { - return 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 startService(service: Intent): ComponentName? = null - override fun startForegroundService(service: Intent): ComponentName? { - return null - } + override fun startForegroundService(service: Intent): ComponentName? = null - override fun stopService(service: Intent): Boolean { - return false - } + override fun stopService(service: Intent): Boolean = false - override fun bindService(service: Intent, conn: ServiceConnection, flags: Int): Boolean { - return 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 - } + override fun startInstrumentation(className: ComponentName, profileFile: String?, 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?) {} @@ -225,17 +191,11 @@ class MockContext : Context() { 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 checkUriPermission(uri: Uri, pid: Int, uid: Int, modeFlags: Int): Int = 0 - override fun checkCallingUriPermission(uri: Uri, modeFlags: Int): Int { - return 0 - } + override fun checkCallingUriPermission(uri: Uri, modeFlags: Int): Int = 0 - override fun checkCallingOrSelfUriPermission(uri: Uri, modeFlags: Int): Int { - return 0 - } + override fun checkCallingOrSelfUriPermission(uri: Uri, modeFlags: Int): Int = 0 override fun checkUriPermission( uri: Uri?, @@ -243,18 +203,10 @@ class MockContext : Context() { writePermission: String?, pid: Int, uid: Int, - modeFlags: Int - ): Int { - return 0 - } - - override fun enforceUriPermission( - uri: Uri, - pid: Int, - uid: Int, modeFlags: Int, - message: String - ) { + ): Int = 0 + + override fun enforceUriPermission(uri: Uri, pid: Int, uid: Int, modeFlags: Int, message: String) { } override fun enforceCallingUriPermission(uri: Uri, modeFlags: Int, message: String) {} @@ -266,166 +218,90 @@ 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 - } + override fun openOrCreateDatabase(name: String, mode: Int, 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) { @@ -443,13 +319,14 @@ class MockContext : Context() { override fun startActivity(intent: Intent, options: Bundle?) {} override fun startActivities(intents: Array) {} 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 +337,23 @@ 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..c9017bd 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockContextApplication.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockContextApplication.kt @@ -1,21 +1,15 @@ 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/MockKitConfiguration.kt b/src/test/kotlin/com/mparticle/kits/mocks/MockKitConfiguration.kt index e2e7d88..5d18c20 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockKitConfiguration.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockKitConfiguration.kt @@ -1,12 +1,8 @@ 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 @@ -40,9 +36,7 @@ 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 { print("SparseArray getting: $key") @@ -62,20 +56,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..ed175dd 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockKitManagerImpl.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockKitManagerImpl.kt @@ -1,51 +1,47 @@ 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 -class MockKitManagerImpl( - context: Context?, - reportingManager: ReportingManager?, - coreCallbacks: CoreCallbacks? -) : KitManagerImpl( - context, reportingManager, coreCallbacks, Mockito.mock( - MParticleOptions::class.java - ) -) { +class MockKitManagerImpl(context: Context?, reportingManager: ReportingManager?, coreCallbacks: CoreCallbacks?) : + KitManagerImpl( + 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..7f853be 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockResources.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockResources.kt @@ -1,9 +1,6 @@ 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 class MockResources : Resources(null, null, null) { override fun getIdentifier(name: String, defType: String, defPackage: String): Int { @@ -25,12 +22,10 @@ class MockResources : Resources(null, null, null) { } @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" + const val TEST_APP_KEY = "the app key" + const val TEST_APP_SECRET = "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..8b99f8f 100644 --- a/src/test/kotlin/com/mparticle/kits/mocks/MockSharedPreferences.kt +++ b/src/test/kotlin/com/mparticle/kits/mocks/MockSharedPreferences.kt @@ -2,10 +2,12 @@ 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