Skip to content

Commit

Permalink
feat: add unit tests in core module (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
qingzhuozhen authored Apr 28, 2022
1 parent dcc0e9d commit 4283148
Show file tree
Hide file tree
Showing 18 changed files with 910 additions and 34 deletions.
21 changes: 12 additions & 9 deletions core/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,29 @@ repositories {
mavenCentral()
}

test {
useJUnitPlatform()
}

dependencies {
implementation project(":common")
implementation project(":common-jvm")
api project(":common")
api project(":common-jvm")
api project(":event-bridge")
api project(':id')
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation project(':id')

// MAIN DEPS
compileOnly 'org.json:json:20211205'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
implementation project(":event-bridge")

testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.2'
testImplementation 'org.json:json:20211205'
testImplementation 'io.mockk:mockk:1.12.3'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.0'

testImplementation platform("org.junit:junit-bom:5.7.2")
testImplementation "org.junit.jupiter:junit-jupiter"
}

test {
useJUnitPlatform()
}

tasks.dokkaHtmlPartial.configure {
failOnWarning.set(true)
}
33 changes: 30 additions & 3 deletions core/src/main/java/com/amplitude/core/Amplitude.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import com.amplitude.eventbridge.EventChannel
import com.amplitude.id.IMIdentityStorageProvider
import com.amplitude.id.IdentityConfiguration
import com.amplitude.id.IdentityContainer
import com.amplitude.id.IdentityUpdateType
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
Expand Down Expand Up @@ -62,7 +63,11 @@ open class Amplitude internal constructor(

open fun build() {
idContainer = IdentityContainer.getInstance(IdentityConfiguration(instanceName = configuration.instanceName, apiKey = configuration.apiKey, identityStorageProvider = IMIdentityStorageProvider()))
idContainer.identityManager.addIdentityListener(AnalyticsIdentityListener(store))
val listener = AnalyticsIdentityListener(store)
idContainer.identityManager.addIdentityListener(listener)
if (idContainer.identityManager.isInitialized()) {
listener.onIdentityChanged(idContainer.identityManager.getIdentity(), IdentityUpdateType.Initialized)
}
EventBridgeContainer.getInstance(configuration.instanceName).eventBridge.setEventReceiver(EventChannel.EVENT, AnalyticsEventReceiver(this))
add(ContextPlugin())
add(AmplitudeDestination())
Expand Down Expand Up @@ -138,7 +143,9 @@ open class Amplitude internal constructor(
* @return the Amplitude instance
*/
fun setUserId(userId: String?): Amplitude {
this.idContainer.identityManager.editIdentity().setUserId(userId).commit()
amplitudeScope.launch(amplitudeDispatcher) {
idContainer.identityManager.editIdentity().setUserId(userId).commit()
}
return this
}

Expand All @@ -149,7 +156,9 @@ open class Amplitude internal constructor(
* @return the Amplitude instance
*/
fun setDeviceId(deviceId: String): Amplitude {
this.idContainer.identityManager.editIdentity().setDeviceId(deviceId).commit()
amplitudeScope.launch(amplitudeDispatcher) {
idContainer.identityManager.editIdentity().setDeviceId(deviceId).commit()
}
return this
}

Expand Down Expand Up @@ -290,3 +299,21 @@ open class Amplitude internal constructor(
}
}
}

/**
* constructor function to build amplitude in dsl format with config options
* Usage: Amplitude("123") {
* this.flushQueueSize = 10
* }
*
* NOTE: this method should only be used for JVM application.
*
* @param apiKey
* @param configs
* @return
*/
fun Amplitude(apiKey: String, configs: Configuration.() -> Unit): Amplitude {
val config = Configuration(apiKey)
configs.invoke(config)
return Amplitude(config)
}
23 changes: 12 additions & 11 deletions core/src/main/java/com/amplitude/core/Configuration.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@ typealias EventCallBack = (BaseEvent, status: Int, message: String) -> Unit

open class Configuration @JvmOverloads constructor(
val apiKey: String,
val flushQueueSize: Int = FLUSH_QUEUE_SIZE,
val flushIntervalMillis: Int = FLUSH_INTERVAL_MILLIS,
val instanceName: String = DEFAULT_INSTANCE,
var flushQueueSize: Int = FLUSH_QUEUE_SIZE,
var flushIntervalMillis: Int = FLUSH_INTERVAL_MILLIS,
var instanceName: String = DEFAULT_INSTANCE,
var optOut: Boolean = false,
val storageProvider: StorageProvider = InMemoryStorageProvider(),
val loggerProvider: LoggerProvider = ConsoleLoggerProvider(),
val minIdLength: Int? = null,
val partnerId: String? = null,
var minIdLength: Int? = null,
var partnerId: String? = null,
val callback: EventCallBack? = null,
val flushMaxRetries: Int = FLUSH_MAX_RETRIES,
val useBatch: Boolean = false,
val serverZone: ServerZone = ServerZone.US,
val serverUrl: String? = null
var useBatch: Boolean = false,
var serverZone: ServerZone = ServerZone.US,
var serverUrl: String? = null
) {

companion object {
Expand All @@ -35,10 +35,11 @@ open class Configuration @JvmOverloads constructor(
}

fun isMinIdLengthValid(): Boolean {
if (minIdLength == null) {
return true
return minIdLength ?. let {
it > 0
} ?: let {
true
}
return minIdLength > 0
}
}

Expand Down
10 changes: 10 additions & 0 deletions core/src/main/java/com/amplitude/core/events/BaseEvent.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.amplitude.core.events

/**
* BaseEvent for SDK
*/
open class BaseEvent : EventOptions() {
open lateinit var eventType: String
var eventProperties: MutableMap<String, Any?>? = null
Expand Down Expand Up @@ -46,4 +49,11 @@ open class BaseEvent : EventOptions() {
callback ?: let { callback = options.callback }
partnerId ?: let { partnerId = options.partnerId }
}

/**
* Check if event is valid
*/
open fun isValid(): Boolean {
return userId != null || deviceId != null
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,8 @@ import com.amplitude.core.Constants

class GroupIdentifyEvent : BaseEvent() {
override var eventType = Constants.GROUP_IDENTIFY_EVENT

override fun isValid(): Boolean {
return groups != null && groupProperties != null
}
}
4 changes: 2 additions & 2 deletions core/src/main/java/com/amplitude/core/events/Revenue.kt
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ class Revenue {
/**
* The Receipt field (required if you want to verify the revenue event).
*/
private var receipt: String? = null
var receipt: String? = null

/**
* The Receipt Signature field (required if you want to verify the revenue event).
*/
private var receiptSig: String? = null
var receiptSig: String? = null

/**
* The Revenue Event Properties field with (optional).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ class EventPipeline(
connection.close()
}
val responseHandler = storage.getResponseHandler(this@EventPipeline, amplitude.configuration, scope, amplitude.retryDispatcher, events, eventsString)
responseHandler?.handle(connection.response)
responseHandler.handle(connection.response)
} catch (e: Exception) {
e.message?.let {
amplitude.logger.error("Error when upload event: $it")
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/com/amplitude/core/platform/Mediator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import com.amplitude.core.events.GroupIdentifyEvent
import com.amplitude.core.events.IdentifyEvent
import com.amplitude.core.events.RevenueEvent

internal class Mediator(private val plugins: MutableList<Plugin>) {
internal class Mediator(internal val plugins: MutableList<Plugin>) {
fun add(plugin: Plugin) = synchronized(plugins) {
plugins.add(plugin)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ class AmplitudeDestination : DestinationPlugin() {

private fun enqueue(payload: BaseEvent?) {
payload?.let {
pipeline.put(it)
if (it.isValid()) {
pipeline.put(it)
} else {
amplitude.logger.warn("Event is invalid for missing information like userId and deviceId. Dropping event: ${it.eventType}")
}
}
}

Expand Down
4 changes: 2 additions & 2 deletions core/src/main/java/com/amplitude/core/utilities/HttpClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ internal class HttpClient(
var inputStream: InputStream? = null
try {
inputStream = getInputStream(this.connection)
responseBody = inputStream?.bufferedReader()?.use(BufferedReader::readText)
responseBody = inputStream.bufferedReader().use(BufferedReader::readText)
this.response = HttpResponse.createHttpResponse(responseCode, JSONObject(responseBody))
} catch (e: IOException) {
this.response = HttpResponse.createHttpResponse(408, null)
Expand Down Expand Up @@ -68,7 +68,7 @@ internal class HttpClient(

private fun getApiHost(): String {
if (!configuration.serverUrl.isNullOrEmpty()) {
return configuration.serverUrl
return configuration.serverUrl!!
}
if (configuration.serverZone == ServerZone.EU) {
return if (configuration.useBatch) Constants.EU_BATCH_API_HOST else Constants.EU_DEFAULT_API_HOST
Expand Down
Loading

0 comments on commit 4283148

Please sign in to comment.