Skip to content

Commit

Permalink
chore: add android native test
Browse files Browse the repository at this point in the history
  • Loading branch information
Mercy811 committed Feb 23, 2024
1 parent b1459d9 commit 09a870d
Show file tree
Hide file tree
Showing 14 changed files with 401 additions and 94 deletions.
11 changes: 9 additions & 2 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ group 'com.amplitude.amplitude_flutter'
version '1.0-SNAPSHOT'

buildscript {
ext.kotlin_version = '1.5.10'
ext.kotlin_version = '1.5.20'
repositories {
google()
mavenCentral()
Expand All @@ -25,7 +25,7 @@ apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'

android {
compileSdkVersion 28
compileSdkVersion 31
// Condition for namespace compatibility in AGP 8
if (project.android.hasProperty("namespace")) {
namespace 'com.amplitude.amplitude_flutter'
Expand All @@ -44,5 +44,12 @@ android {
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "org.jetbrains.kotlin:kotlin-reflect:1.6.10"

implementation 'com.amplitude:analytics-android:1.+'
testImplementation 'org.mockito:mockito-core:4.0.0'
testImplementation "io.mockk:mockk:1.12.4"
testImplementation "io.mockk:mockk-agent-jvm:1.11.0"
testImplementation('junit:junit:4.13')
testImplementation 'org.robolectric:robolectric:4.8.2'
}
Binary file modified android/gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
2 changes: 2 additions & 0 deletions android/gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
35 changes: 22 additions & 13 deletions android/gradlew
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
Expand All @@ -80,13 +80,11 @@ do
esac
done

APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit

APP_NAME="Gradle"
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
Expand Down Expand Up @@ -133,22 +131,29 @@ location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi

# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
Expand Down Expand Up @@ -193,11 +198,15 @@ if "$cygwin" || "$msys" ; then
done
fi

# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.

set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
Expand Down
1 change: 1 addition & 0 deletions android/gradlew.bat
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ if "%OS%"=="Windows_NT" setlocal

set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,37 +14,33 @@ import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
import org.json.JSONObject

class AmplitudeFlutterPlugin : FlutterPlugin, MethodCallHandler {
lateinit var amplitude: Amplitude

companion object {
lateinit var ctxt: Context

private const val methodChannelName = "amplitude_flutter"
private lateinit var channel: MethodChannel

var ctxt: Context? = null

@JvmStatic
fun registerWith(registrar: Registrar) {
ctxt = registrar.context()
val channel = MethodChannel(registrar.messenger(), methodChannelName)
channel.setMethodCallHandler(AmplitudeFlutterPlugin())
}
companion object {
private const val methodChannelName = "amplitude_flutter"
private const val defaultMinIdLength = 5
}

override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
ctxt = binding.applicationContext
val channel = MethodChannel(binding.binaryMessenger, methodChannelName)
channel.setMethodCallHandler(AmplitudeFlutterPlugin())
channel = MethodChannel(binding.binaryMessenger, methodChannelName)
channel.setMethodCallHandler(this)
}

override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}

override fun onMethodCall(call: MethodCall, result: Result) {
val json = JSONObject(call.arguments.toString())
val json = JSONObject(call.arguments?.toString() ?: "{}")

when (call.method) {
"init" -> {
Expand All @@ -58,7 +54,9 @@ class AmplitudeFlutterPlugin : FlutterPlugin, MethodCallHandler {
flushIntervalMillis = json.getInt("flushIntervalMillis"),
instanceName = json.getString("instanceName"),
optOut = json.getBoolean("optOut"),
minIdLength = json.getInt("minIdLength"),
minIdLength = if (json.optInt("minIdLength") == 0) defaultMinIdLength else json.optInt(
"minIdLength"
),
partnerId = json.getString("partnerId"),
flushMaxRetries = json.getInt("flushMaxRetries"),
useBatch = json.getBoolean("useBatch"),
Expand All @@ -83,9 +81,9 @@ class AmplitudeFlutterPlugin : FlutterPlugin, MethodCallHandler {
useAppSetIdForDeviceId = json.getBoolean("useAppSetIdForDeviceId"),
)
)
amplitude.logger.logMode = Logger.LogMode.valueOf(
json.getString("logLevel").uppercase()
)
amplitude.logger.logMode = Logger.LogMode.valueOf(
json.getString("logLevel").uppercase()
)

result.success("init called..")
}
Expand Down Expand Up @@ -127,10 +125,12 @@ class AmplitudeFlutterPlugin : FlutterPlugin, MethodCallHandler {

"reset" -> {
amplitude.reset()
result.success("reset called..")
}

"flush" -> {
amplitude.flush()
result.success("flush called..")
}

else -> {
Expand All @@ -139,7 +139,7 @@ class AmplitudeFlutterPlugin : FlutterPlugin, MethodCallHandler {
}
}

private fun getTrackingOptions(jsonObject: JSONObject): TrackingOptions {
internal fun getTrackingOptions(jsonObject: JSONObject): TrackingOptions {
val trackingOptions = TrackingOptions()
if (!jsonObject.getBoolean("ipAddress")) {
trackingOptions.disableIpAddress()
Expand Down Expand Up @@ -196,27 +196,35 @@ class AmplitudeFlutterPlugin : FlutterPlugin, MethodCallHandler {
return trackingOptions
}

private fun getEvent(json: JSONObject): BaseEvent {
internal fun getEvent(json: JSONObject): BaseEvent {
val plan = json.getJSONObject("plan")
val ingestionMetadata = json.getJSONObject("ingestion_metadata")
val event = BaseEvent()
event.eventType = json.getString("event_type")
event.eventProperties = json.getJSONObject("event_properties").toMutableMap()
event.userProperties = json.getJSONObject("user_properties").toMutableMap()
event.groups = json.getJSONObject("groups").toMutableMap()
event.groupProperties = json.getJSONObject("group_properties").toMutableMap()
event.eventProperties = json.optJSONObject("event_properties")?.let {
it.toMutableMap()
} ?: null
event.userProperties = json.optJSONObject("user_properties")?.let {
it.toMutableMap()
} ?: null
event.groups = json.optJSONObject("groups")?.let {
it.toMutableMap()
} ?: null
event.groupProperties = json.optJSONObject("group_properties")?.let {
it.toMutableMap()
} ?: null
event.userId = json.getString("user_id")
event.deviceId = json.getString("device_id")
event.timestamp = json.getLong("timestamp")
event.eventId = json.getLong("event_id")
event.sessionId = json.getLong("session_id")
event.insertId = json.getString("insert_id")
event.locationLat = json.getDouble("location_lat")
event.locationLng = json.getDouble("location_lng")
event.timestamp = json.optLong("timestamp")
event.eventId = json.optLong("event_id")
event.sessionId = json.optLong("session_id")
event.insertId = json.optString("insert_id")
event.locationLat = json.optDouble("location_lat")
event.locationLng = json.optDouble("location_lng")
event.appVersion = json.getString("app_version")
event.versionName = json.getString("version_name")
event.platform = json.getString("platform")
event.osName = json.getString("osName")
event.osName = json.getString("os_name")
event.osVersion = json.getString("os_version")
event.deviceBrand = json.getString("device_brand")
event.deviceManufacturer = json.getString("device_manufacturer")
Expand Down Expand Up @@ -244,18 +252,20 @@ class AmplitudeFlutterPlugin : FlutterPlugin, MethodCallHandler {
ingestionMetadata.getString("sourceName"),
ingestionMetadata.getString("sourceVersion")
)
event.revenue = json.getDouble("revenue")
event.price = json.getDouble("price")
event.quantity = json.getInt("quantity")
event.revenue = json.optDouble("revenue")
event.price = json.optDouble("price")
event.quantity = json.optInt("quantity")
event.productId = json.getString("product_id")
event.revenueType = json.getString("revenue_type")
event.extra = json.optJSONObject("extra").toMap()
event.extra = json.optJSONObject("extra")?.let {
it.toMap()
} ?: null
event.partnerId = json.getString("partner_id")

return event
}

private fun JSONObject.toMutableMap(): MutableMap<String, Any?> {
internal fun JSONObject.toMutableMap(): MutableMap<String, Any?> {
val map = mutableMapOf<String, Any?>()
val keys = keys()
while (keys.hasNext()) {
Expand All @@ -269,7 +279,7 @@ class AmplitudeFlutterPlugin : FlutterPlugin, MethodCallHandler {
return map
}

private fun JSONObject.toMap(): Map<String, Any> {
internal fun JSONObject.toMap(): Map<String, Any> {
val map = mutableMapOf<String, Any>()
val keys = keys()
while (keys.hasNext()) {
Expand Down
Loading

0 comments on commit 09a870d

Please sign in to comment.