From b0c80fcdf1094cce06f10c6a8dc6dc010c9ca624 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Tue, 20 Feb 2024 15:01:06 +0100 Subject: [PATCH 01/63] chore(gradle): migrate to toml based dependency management SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> --- gradle/libs.versions.toml | 89 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 gradle/libs.versions.toml diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 00000000..8ba366c0 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,89 @@ +[versions] +agp = "8.2.2" +android-compileSdk = "34" +android-minSdk = "28" +android-targetSdk = "34" +androidx-activityCompose = "1.8.2" +androidx-annotation = "1.7.1" +androidx-appcompat = "1.6.1" +androidx-constraintlayout = "2.1.4" +androidx-core-ktx = "1.12.0" +androidx-espresso-core = "3.5.1" +androidx-material = "1.11.0" +androidx-test-runner = "1.5.2" +androidx-test-junit = "1.1.5" +androidx-lifecycle = "2.7.0" +androidx-espresso-idling-resource = "3.5.1" +androidx-security-crypto = "1.1.0-alpha06" +compose = "1.6.1" +compose-compiler = "1.5.6" +compose-plugin = "1.6.0-dev1419" +dokka = "1.9.10" +junit = "4.13.2" +tink = "1.9.0" +kotlin = "1.9.0" +kotlinxCoroutines = "1.7.3" +kotest = "5.8.0" +mockk = "1.13.9" +fcm = "23.4.0" +agconnect_core = "1.9.1.300" +hms_push = "6.11.0.300" +googleServices = "4.4.1" +location-services = "21.1.0" +webkit = "1.7.0" +mockito = "4.9.0" +mockito-kotlin = "4.1.0" + +[libraries] +kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" } +kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" } +kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinxCoroutines" } +kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinxCoroutines" } +androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "androidx-core-ktx" } +androidx-runner = { module = "androidx.test:runner", version.ref = "androidx-test-runner" } +androidx-test-junit = { group = "androidx.test.ext", name = "junit", version.ref = "androidx-test-junit" } +androidx-espresso-idling-resource = { group = "androidx.test.espresso", name = "espresso-idling-resource", version.ref = "androidx-espresso-idling-resource" } +androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "androidx-espresso-core" } +androidx-annotation = { group = "androidx.annotation", name = "annotation", version.ref = "androidx-annotation" } +androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "androidx-appcompat" } +androidx-material = { group = "com.google.android.material", name = "material", version.ref = "androidx-material" } +androidx-constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "androidx-constraintlayout" } +androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activityCompose" } +androidx-lifecycle-process = { module = "androidx.lifecycle:lifecycle-process", version.ref = "androidx-lifecycle" } +androidx-lifecycle-common-java8 = { module = "androidx.lifecycle:lifecycle-common-java8", version.ref = "androidx-lifecycle" } +androidx-security-crypto = { module = "androidx.security:security-crypto", version.ref = "androidx-security-crypto" } +androidx-webkit = { module = "androidx.webkit:webkit", version.ref = "webkit" } +google-tink = { module = "com.google.crypto.tink:tink-android", version.ref = "tink" } +google-location = { module = "com.google.android.gms:play-services-location", version.ref = "location-services" } +google-fcm = { group = "com.google.firebase", name = "firebase-messaging", version.ref = "fcm" } +huawei-hms-push = { group = "com.huawei.hms", name = "push", version.ref = "hms_push" } +huawei-agconnect-core = { group = "com.huawei.agconnect", name = "agconnect-core", version.ref = "agconnect_core" } +compose-ui = { module = "androidx.compose.ui:ui", version.ref = "compose" } +compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling", version.ref = "compose" } +compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview", version.ref = "compose" } +compose-foundation = { module = "androidx.compose.foundation:foundation", version.ref = "compose" } +compose-material = { module = "androidx.compose.material:material", version.ref = "compose" } +junit = { group = "junit", name = "junit", version.ref = "junit" } +kotest-assertions-core = { module = "io.kotest:kotest-assertions-core", version.ref = "kotest" } +kotest-framework-engine = { module = "io.kotest:kotest-framework-engine", version.ref = "kotest" } +mockk-android = { module = "io.mockk:mockk-android", version.ref = "mockk" } +mockk-agent = { module = "io.mockk:mockk-agent-jvm", version.ref = "mockk" } +mockito-android = { module = "org.mockito:mockito-android", version.ref = "mockito" } +mockito-kotlin = { module = "org.mockito.kotlin:mockito-kotlin", version.ref = "mockito-kotlin" } +#byte-buddy = { module = "net.bytebuddy:byte-buddy", version.ref = "byte-buddy" } +androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidx-test-runner" } +androidx-test-rules = { module = "androidx.test:rules", version.ref = "androidx-test-runner" } +androidx-test-extensions = { module = "androidx.test.ext:junit", version.ref = "androidx-test-runner" } +androidx-test-fragment = { module = "androidx.fragment:fragment-testing", version.ref = "androidx-test-runner" } +androidx-test-multidex = { module = "androidx.multidex:multidex-instrumentation", version.ref = "androidx-test-runner" } + +[plugins] +androidApplication = { id = "com.android.application", version.ref = "agp" } +androidLibrary = { id = "com.android.library", version.ref = "agp" } +jetbrainsCompose = { id = "org.jetbrains.compose", version.ref = "compose-plugin" } +kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } +kotlin = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } +kotlinSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } +dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } +agconnect = { id = "com.huawei.agconnect", version.ref = "agconnect_core" } +googleServices = { id = "com.google.gms.google-services", version.ref = "googleServices" } From 81988b57cacd1be5ba7f6144fe9f4ff8b04ca295 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Tue, 20 Feb 2024 16:10:37 +0100 Subject: [PATCH 02/63] chore(gradle): migrate build.gradle to KTS based gradle files SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: matusekma <36794575+matusekma@users.noreply.github.com> --- .env.example | 22 ++++++ .gitignore | 3 +- build.gradle | 42 ----------- build.gradle.kts | 62 ++++++++++++++++ buildSrc/src/main/java/Config.kt | 5 -- buildSrc/src/main/java/Dependency.kt | 73 ------------------- buildSrc/src/main/java/GitVersion.kt | 1 + common/build.gradle | 10 ++- core-api/build.gradle | 14 ---- core-api/build.gradle.kts | 20 +++++ core/build.gradle | 11 --- core/build.gradle.kts | 21 ++++++ core/proguard-rules.pro | 2 +- .../{build.gradle => build.gradle.kts} | 24 ++++-- emarsys-firebase/build.gradle | 26 +++++-- emarsys-huawei/build.gradle | 14 ---- emarsys-huawei/build.gradle.kts | 24 ++++++ emarsys-sdk/build.gradle | 32 -------- emarsys-sdk/build.gradle.kts | 28 +++++++ emarsys-sdk/proguard-rules.pro | 2 +- emarsys/build.gradle | 16 ---- emarsys/build.gradle.kts | 26 +++++++ gradle/common.gradle | 62 ---------------- gradle/dev.gradle | 12 --- gradle/libs.versions.toml | 10 ++- gradle/version.gradle | 42 ----------- mobile-engage-api/build.gradle | 11 --- mobile-engage-api/build.gradle.kts | 22 ++++++ mobile-engage/build.gradle | 18 ----- mobile-engage/build.gradle.kts | 24 ++++++ mobile-engage/proguard-rules.pro | 2 +- predict-api/build.gradle | 9 --- predict-api/build.gradle.kts | 17 +++++ predict/build.gradle | 11 --- predict/build.gradle.kts | 22 ++++++ sample/build.gradle | 34 ++------- settings.gradle.kts | 12 ++- testUtils/build.gradle | 61 ---------------- testUtils/build.gradle.kts | 61 ++++++++++++++++ 39 files changed, 426 insertions(+), 482 deletions(-) create mode 100644 .env.example delete mode 100644 build.gradle create mode 100644 build.gradle.kts delete mode 100644 buildSrc/src/main/java/Config.kt delete mode 100644 buildSrc/src/main/java/Dependency.kt create mode 100644 buildSrc/src/main/java/GitVersion.kt delete mode 100644 core-api/build.gradle create mode 100644 core-api/build.gradle.kts delete mode 100644 core/build.gradle create mode 100644 core/build.gradle.kts rename emarsys-e2e-test/{build.gradle => build.gradle.kts} (67%) delete mode 100644 emarsys-huawei/build.gradle create mode 100644 emarsys-huawei/build.gradle.kts delete mode 100644 emarsys-sdk/build.gradle create mode 100644 emarsys-sdk/build.gradle.kts delete mode 100644 emarsys/build.gradle create mode 100644 emarsys/build.gradle.kts delete mode 100644 gradle/common.gradle delete mode 100644 gradle/dev.gradle delete mode 100644 gradle/version.gradle delete mode 100644 mobile-engage-api/build.gradle create mode 100644 mobile-engage-api/build.gradle.kts delete mode 100644 mobile-engage/build.gradle create mode 100644 mobile-engage/build.gradle.kts delete mode 100644 predict-api/build.gradle create mode 100644 predict-api/build.gradle.kts delete mode 100644 predict/build.gradle create mode 100644 predict/build.gradle.kts delete mode 100644 testUtils/build.gradle create mode 100644 testUtils/build.gradle.kts diff --git a/.env.example b/.env.example new file mode 100644 index 00000000..f4e5f2ca --- /dev/null +++ b/.env.example @@ -0,0 +1,22 @@ +USE_LOCAL_DEPENDENCY= +GOOGLE_SERVICES_API_KEY= +RELEASE_MODE= +ANDROID_RELEASE_STORE_FILE_BASE64= +ANDROID_RELEASE_STORE_PASSWORD= +ANDROID_RELEASE_KEY_ALIAS= +ANDROID_RELEASE_KEY_PASSWORD= +FIREBASE_PROJECT_ID= +FIREBASE_SERVICE_ACCOUNT_JSON= +GOOGLE_OAUTH_SERVER_CLIENT_ID= +GOOGLE_SERVICES_JSON_BASE64= +OSSRH_USERNAME= +OSSRH_PASSWORD= +SONATYPE_STAGING_PROFILE_ID= +SONATYPE_SIGNING_KEY_ID= +SONATYPE_SIGNING_PASSWORD= +SONATYPE_SIGNING_SECRET_KEY_RING_FILE= +DETECT_LATEST_RELEASE_VERSION= +DETECT_PROJECT_USER_GROUPS= +DETECT_PROJECT_VERSION_DISTRIBUTION= +BLACKDUCK_ACCESS_TOKEN= +BLACKDUCK_URL= \ No newline at end of file diff --git a/.gitignore b/.gitignore index d8513c4e..455e1ce2 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,5 @@ local.properties localConfig.properties sample/google-services.json sample/agconnect-services.json -.fleet \ No newline at end of file +.fleet +.env \ No newline at end of file diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 076fcc2f..00000000 --- a/build.gradle +++ /dev/null @@ -1,42 +0,0 @@ -ext.modules = [':core-api', ':core', ':common', ':mobile-engage-api', ':mobile-engage', ':emarsys-firebase', ':emarsys-huawei', ':predict-api', ':predict', ':emarsys', ':emarsys-sdk', ':emarsys-e2e-test'] - -buildscript { - repositories { - google() - maven { url "https://plugins.gradle.org/m2/" } - maven { - url 'https://developer.huawei.com/repo/' - } - maven { - url "https://androidx.dev/storage/compose-compiler/repository/" - } - gradlePluginPortal() - } - dependencies { - classpath 'com.android.tools.build:gradle:8.1.4' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$Versions.kotlin_version" - classpath "org.jetbrains.kotlin:kotlin-allopen:$Versions.kotlin_version" - classpath "com.github.ben-manes:gradle-versions-plugin:0.51.0" - classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.7.6" - classpath "io.github.gradle-nexus:publish-plugin:1.3.0" - } -} - -// for blackduck: -// sourceCompatibility = 17 - -apply from: 'gradle/dev.gradle' -apply from: 'gradle/version.gradle' -apply from: 'gradle/common.gradle' -apply from: 'gradle/release.gradle' -apply plugin: "com.github.ben-manes.versions" - -dependencyUpdates.resolutionStrategy { - componentSelection { rules -> - rules.all { ComponentSelection selection -> - if (!(selection.candidate.version ==~ /\d+\.\d+(\.\d+)?/)) { - selection.reject('Not release candidate!') - } - } - } -} \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 00000000..bae1dca8 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,62 @@ +import org.ajoberstar.grgit.Grgit +import java.io.FileInputStream +import java.util.Properties + +plugins { + alias(libs.plugins.androidLibrary) apply false + alias(libs.plugins.androidApplication) apply false + alias(libs.plugins.kotlin) apply false + alias(libs.plugins.kapt) apply false + alias(libs.plugins.navigationSafeArgs) apply false + alias(libs.plugins.googleServices) apply false + alias(libs.plugins.kotlinAllOpen) apply false + alias(libs.plugins.grGit) + id("com.github.ben-manes.versions") version "0.46.0" +} + +versionData() +loadDevConfig() + +fun loadDevConfig() { + + ext["devConfig"] = Properties() + + try { + val inputStream = FileInputStream("$projectDir/localConfig.properties") + (ext["devConfig"] as Properties).load(inputStream) + + } catch (ignore: Exception) { + } + + if (ext["devConfig"] != null) { + println("Using devConfig: ${ext["devConfig"]}") + } +} + +fun versionData() { + val git = Grgit.open( + mapOf("currentDir" to project.rootDir) + ) + + if ((if (System.getenv("BLACKDUCK") == null) false else System.getenv("BLACKDUCK")) == false) { + git.fetch() + } + if (git.describe() == null) { + throw RuntimeException("Couldn't get Version Name") + } + val v = GitVersion( + versionName = + if (System.getenv("RELEASE_VERSION") == null) git.describe() else System.getenv( + "RELEASE_VERSION" + ), + versionCode = ((System.currentTimeMillis() - 1602845230) / 10000).toInt(), + versionCodeTime = git.head().time + ) + ext["gitVersionName"] = v.versionName + ext["gitVersionCode"] = v.versionCode + ext["gitVersionCodeTime"] = v.versionCodeTime + + println("versionName: ${v.versionName}") + println("versionCode: ${v.versionCode}") + +} \ No newline at end of file diff --git a/buildSrc/src/main/java/Config.kt b/buildSrc/src/main/java/Config.kt deleted file mode 100644 index 6f3bc7d0..00000000 --- a/buildSrc/src/main/java/Config.kt +++ /dev/null @@ -1,5 +0,0 @@ -object Config { - const val minApiLevel = 24 - const val targetApiLevel = 34 - const val buildToolsVersion = Versions.buildToolsVersion -} diff --git a/buildSrc/src/main/java/Dependency.kt b/buildSrc/src/main/java/Dependency.kt deleted file mode 100644 index b41e576a..00000000 --- a/buildSrc/src/main/java/Dependency.kt +++ /dev/null @@ -1,73 +0,0 @@ -object Versions { - const val kotlin_version = "1.9.0" - const val kotlin_coroutines_version = "1.7.3" - const val kotlin_test_version = "3.4.2" - const val mockito_version = "4.9.0" - const val mockito_core_version = "4.9.0" - const val firebase_messaging_version = "23.4.0" - const val support_test_version = "1.5.2" - const val support_rules_test_version = "1.5.0" - const val support_library = "1.6.1" - const val support_test_extensions = "1.1.5" - const val support_test_fragment = "1.6.2" - const val support_annotations = "1.7.1" - const val buildToolsVersion = "34.0.0" - const val multiDexVersion = "2.0.0" - const val kotlinMockito = "4.1.0" - const val location_services_version = "21.1.0" - const val espresso_idling_resources = "3.5.1" - const val archLifecycleVersion = "2.7.0" - const val java8LifecycleVersion = "2.7.0" - const val securityCryptoVersion = "1.1.0-alpha06" - const val byte_buddy_version = "1.14.4" - const val google_tink_version = "1.9.0" - const val huawei_agconnect_core_version = "1.9.1.300" - const val huawei_hms_push_version = "6.11.0.300" - const val mockkVersion = "1.13.3" - const val webkit = "1.7.0" -} - -object Libs { - const val support_annotations = "androidx.annotation:annotation:${Versions.support_annotations}" - const val support_appcompat = "androidx.appcompat:appcompat:${Versions.support_library}" - const val firebase_messaging = - "com.google.firebase:firebase-messaging:${Versions.firebase_messaging_version}" - const val espresso_idling_resources = - "androidx.test.espresso:espresso-idling-resource:${Versions.espresso_idling_resources}" - const val kotlin = "org.jetbrains.kotlin:kotlin-stdlib:${Versions.kotlin_version}" - const val kotlin_reflect = "org.jetbrains.kotlin:kotlin-reflect:${Versions.kotlin_version}" - const val kotlin_stdlib = - "org.jetbrains.kotlin:kotlin-stdlib:${Versions.kotlin_version}" - const val kotlin_coroutines = - "org.jetbrains.kotlinx:kotlinx-coroutines-android:${Versions.kotlin_coroutines_version}" - const val location_services = - "com.google.android.gms:play-services-location:${Versions.location_services_version}" - const val lifecycle_process = - "androidx.lifecycle:lifecycle-process:${Versions.archLifecycleVersion}" - const val lifecycle_extension_java_8 = - "androidx.lifecycle:lifecycle-common-java8:${Versions.java8LifecycleVersion}" - const val security_crypto = - "androidx.security:security-crypto:${Versions.securityCryptoVersion}" - const val google_tink = "com.google.crypto.tink:tink-android:${Versions.google_tink_version}" - const val webkit = "androidx.webkit:webkit:${Versions.webkit}" - const val huawei_agconnect_core = - "com.huawei.agconnect:agconnect-core:${Versions.huawei_agconnect_core_version}" - const val huawei_hms_push = "com.huawei.hms:push:${Versions.huawei_hms_push_version}" -} - -object TestLibs { - const val kotlin_test = "io.kotlintest:kotlintest-runner-junit4:${Versions.kotlin_test_version}" - const val mockito_android = "org.mockito:mockito-android:${Versions.mockito_version}" - const val mockito_core = "org.mockito:mockito-core:${Versions.mockito_core_version}" - const val kotlin_mockito = "org.mockito.kotlin:mockito-kotlin:${Versions.kotlinMockito}" - const val byte_buddy = "net.bytebuddy:byte-buddy:${Versions.byte_buddy_version}" - const val support_test_runner = "androidx.test:runner:${Versions.support_test_version}" - const val support_test_rules = "androidx.test:rules:${Versions.support_rules_test_version}" - const val support_test_extensions = - "androidx.test.ext:junit:${Versions.support_test_extensions}" - const val support_test_fragment = - "androidx.fragment:fragment-testing:${Versions.support_test_fragment}" - const val multiDex = "androidx.multidex:multidex-instrumentation:${Versions.multiDexVersion}" - const val mockk = "io.mockk:mockk-android:${Versions.mockkVersion}" - const val mockk_agent = "io.mockk:mockk-agent-jvm:${Versions.mockkVersion}" -} \ No newline at end of file diff --git a/buildSrc/src/main/java/GitVersion.kt b/buildSrc/src/main/java/GitVersion.kt new file mode 100644 index 00000000..1819f936 --- /dev/null +++ b/buildSrc/src/main/java/GitVersion.kt @@ -0,0 +1 @@ +data class GitVersion(val versionName: String, val versionCode: Int, val versionCodeTime: Long) diff --git a/common/build.gradle b/common/build.gradle index 47649121..8b7b88d7 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -1,6 +1,12 @@ +plugins { + alias(libs.plugins.androidLibrary) + alias(libs.plugins.kotlin) + alias(libs.plugins.kapt) + alias(libs.plugins.kotlinAllOpen) +} dependencies { - implementation project(':core-api') - androidTestImplementation project(':testUtils') + implementation project(":core-api") + androidTestImplementation project(":testUtils") } android { namespace "com.emarsys.common" diff --git a/core-api/build.gradle b/core-api/build.gradle deleted file mode 100644 index 099968cf..00000000 --- a/core-api/build.gradle +++ /dev/null @@ -1,14 +0,0 @@ -dependencies { - api Libs.support_annotations - api Libs.support_appcompat - api Libs.kotlin - api Libs.espresso_idling_resources - api Libs.lifecycle_extension_java_8 - api Libs.lifecycle_process - api Libs.security_crypto - androidTestImplementation project(':testUtils') -} -android { - namespace "com.emarsys.core.api" - sourceCompatibility = 17 -} \ No newline at end of file diff --git a/core-api/build.gradle.kts b/core-api/build.gradle.kts new file mode 100644 index 00000000..8ece3b81 --- /dev/null +++ b/core-api/build.gradle.kts @@ -0,0 +1,20 @@ +plugins { + alias(libs.plugins.androidLibrary) + alias(libs.plugins.kotlin) + alias(libs.plugins.kapt) + alias(libs.plugins.kotlinAllOpen) +} +dependencies { + api(libs.androidx.annotation) + api(libs.androidx.appcompat) + api(libs.kotlin.stdlib) + api(libs.androidx.espresso.idling.resource) + api(libs.androidx.lifecycle.common.java8) + api(libs.androidx.lifecycle.process) + api(libs.androidx.security.crypto) + androidTestImplementation(project(":testUtils")) +} +android { + namespace = "com.emarsys.core.api" +} +kotlin { jvmToolchain(17) } \ No newline at end of file diff --git a/core/build.gradle b/core/build.gradle deleted file mode 100644 index 663e7a59..00000000 --- a/core/build.gradle +++ /dev/null @@ -1,11 +0,0 @@ -dependencies { - implementation project(':core-api') - implementation Libs.google_tink - implementation Libs.kotlin_coroutines - - androidTestImplementation project(':testUtils') -} -android { - namespace "com.emarsys.core" - sourceCompatibility = 17 -} \ No newline at end of file diff --git a/core/build.gradle.kts b/core/build.gradle.kts new file mode 100644 index 00000000..d825ed07 --- /dev/null +++ b/core/build.gradle.kts @@ -0,0 +1,21 @@ +plugins { + alias(libs.plugins.androidLibrary) + alias(libs.plugins.kotlin) + alias(libs.plugins.kapt) + alias(libs.plugins.kotlinAllOpen) +} + +dependencies { + implementation(project(":core-api")) + implementation(libs.google.tink) + implementation(libs.kotlinx.coroutines.core) + + androidTestImplementation(project(":testUtils")) +} +android { + namespace = "com.emarsys.core" +} + +kotlin { + jvmToolchain(17) +} \ No newline at end of file diff --git a/core/proguard-rules.pro b/core/proguard-rules.pro index 162d8da7..e580a0b8 100644 --- a/core/proguard-rules.pro +++ b/core/proguard-rules.pro @@ -2,7 +2,7 @@ # By default, the flags in this file are appended to flags specified # in /Users/jpollak/Library/Android/sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles -# directive in build.gradle. +# directive in build.gradle.kts. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html diff --git a/emarsys-e2e-test/build.gradle b/emarsys-e2e-test/build.gradle.kts similarity index 67% rename from emarsys-e2e-test/build.gradle rename to emarsys-e2e-test/build.gradle.kts index 7ce26b78..e7bd5bb0 100644 --- a/emarsys-e2e-test/build.gradle +++ b/emarsys-e2e-test/build.gradle.kts @@ -1,14 +1,24 @@ +plugins { + alias(libs.plugins.androidLibrary) + alias(libs.plugins.kotlin) + alias(libs.plugins.kapt) + alias(libs.plugins.kotlinAllOpen) +} + dependencies { - implementation project(':emarsys-sdk') - implementation project(':core') - implementation project(':mobile-engage') - implementation project(':predict') + implementation(project(":emarsys-sdk")) + implementation(project(":core")) + implementation(project(":mobile-engage")) + implementation(project(":predict")) - androidTestImplementation project(':testUtils') + androidTestImplementation(project(":testUtils")) } android { - namespace "com.emarsys.test.e2e" - sourceCompatibility = 17 + namespace = "com.emarsys.test.e2e" +} + +kotlin { + jvmToolchain(17) } //task enableMockLocationForTestsOnDevice(type: Exec, dependsOn: 'installDebugAndroidTest') { diff --git a/emarsys-firebase/build.gradle b/emarsys-firebase/build.gradle index 028f7256..8657b869 100644 --- a/emarsys-firebase/build.gradle +++ b/emarsys-firebase/build.gradle @@ -1,14 +1,24 @@ +plugins { + alias(libs.plugins.androidLibrary) + alias(libs.plugins.kotlin) + alias(libs.plugins.kapt) + alias(libs.plugins.kotlinAllOpen) +} + dependencies { - implementation project(':core-api') - implementation project(':core') - implementation project(':mobile-engage') - implementation project(':mobile-engage-api') + implementation(project(":core-api")) + implementation(project(":core")) + implementation(project(":mobile-engage")) + implementation(project(":mobile-engage-api")) - api Libs.firebase_messaging, { exclude group: 'androidx' } + api(libs.google.fcm, { exclude group: 'androidx' }) - androidTestImplementation project(':testUtils') + androidTestImplementation(project(":testUtils")) } android { - namespace "com.emarsys.firebase" - sourceCompatibility = 17 + namespace = "com.emarsys.firebase" +} + +kotlin { + jvmToolchain(17) } \ No newline at end of file diff --git a/emarsys-huawei/build.gradle b/emarsys-huawei/build.gradle deleted file mode 100644 index b7dae9ba..00000000 --- a/emarsys-huawei/build.gradle +++ /dev/null @@ -1,14 +0,0 @@ -dependencies { - implementation project(':core-api') - implementation project(':core') - implementation project(':mobile-engage') - implementation project(':mobile-engage-api') - - api Libs.huawei_agconnect_core - api Libs.huawei_hms_push - androidTestImplementation project(':testUtils') -} -android { - namespace "com.emarsys.huawei" - sourceCompatibility = 17 -} \ No newline at end of file diff --git a/emarsys-huawei/build.gradle.kts b/emarsys-huawei/build.gradle.kts new file mode 100644 index 00000000..8c3ab26e --- /dev/null +++ b/emarsys-huawei/build.gradle.kts @@ -0,0 +1,24 @@ +plugins { + alias(libs.plugins.androidLibrary) + alias(libs.plugins.kotlin) + alias(libs.plugins.kapt) + alias(libs.plugins.kotlinAllOpen) +} + +dependencies { + implementation(project(":core-api")) + implementation(project(":core")) + implementation(project(":mobile-engage")) + implementation(project(":mobile-engage-api")) + + api(libs.huawei.agconnect.core) + api(libs.huawei.hms.push) + androidTestImplementation(project(":testUtils")) +} +android { + namespace = "com.emarsys.huawei" +} + +kotlin { + jvmToolchain(17) +} diff --git a/emarsys-sdk/build.gradle b/emarsys-sdk/build.gradle deleted file mode 100644 index 0f7b63e4..00000000 --- a/emarsys-sdk/build.gradle +++ /dev/null @@ -1,32 +0,0 @@ -dependencies { - api project(':core-api') - api project(':mobile-engage-api') - api project(':predict-api') - - implementation project(':common') - implementation project(':core') - implementation project(':mobile-engage') - implementation project(':predict') - implementation project(':emarsys') - - androidTestImplementation project(':testUtils') -} - -android { - namespace "com.emarsys" - sourceCompatibility = 17 - - defaultConfig { - def api_key = null - def localConfigPropertiesFile = rootProject.file('localConfig.properties') - def localConfigProperties = new Properties() - if (localConfigPropertiesFile.exists()) { - localConfigProperties.load(new FileInputStream(localConfigPropertiesFile)) - api_key = localConfigProperties.getProperty("googleServicesApiKey") - } - - if (!System.env.EXCLUDE_GOOGLE_SERVICES_API_KEY) { - buildConfigField "String", "GOOGLE_SERVICES_API_KEY", "\"${System.env.GOOGLE_SERVICES_API_KEY ?: api_key}\"" - } - } -} \ No newline at end of file diff --git a/emarsys-sdk/build.gradle.kts b/emarsys-sdk/build.gradle.kts new file mode 100644 index 00000000..30005d8d --- /dev/null +++ b/emarsys-sdk/build.gradle.kts @@ -0,0 +1,28 @@ +plugins { + alias(libs.plugins.androidLibrary) + alias(libs.plugins.kotlin) + alias(libs.plugins.kapt) + alias(libs.plugins.kotlinAllOpen) +} + +dependencies { + api(project(":core-api")) + api(project(":mobile-engage-api")) + api(project(":predict-api")) + + implementation(project(":common")) + implementation(project(":core")) + implementation(project(":mobile-engage")) + implementation(project(":predict")) + implementation(project(":emarsys")) + + androidTestImplementation(project(":testUtils")) +} + +android { + namespace = "com.emarsys" +} + +kotlin { + jvmToolchain(17) +} diff --git a/emarsys-sdk/proguard-rules.pro b/emarsys-sdk/proguard-rules.pro index 856d56b7..0ddc77f1 100644 --- a/emarsys-sdk/proguard-rules.pro +++ b/emarsys-sdk/proguard-rules.pro @@ -2,7 +2,7 @@ # By default, the flags in this file are appended to flags specified # in /Users/jpollak/Library/Android/sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles -# directive in build.gradle. +# directive in build.gradle.kts. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html diff --git a/emarsys/build.gradle b/emarsys/build.gradle deleted file mode 100644 index 2e393317..00000000 --- a/emarsys/build.gradle +++ /dev/null @@ -1,16 +0,0 @@ -dependencies { - api project(':core-api') - api project(':mobile-engage-api') - api project(':predict-api') - - implementation project(':common') - implementation project(':core') - implementation project(':mobile-engage') - implementation project(':predict') - - androidTestImplementation project(':testUtils') -} -android { - namespace "com.emarsys.inner" - sourceCompatibility = 17 -} \ No newline at end of file diff --git a/emarsys/build.gradle.kts b/emarsys/build.gradle.kts new file mode 100644 index 00000000..6778a3b5 --- /dev/null +++ b/emarsys/build.gradle.kts @@ -0,0 +1,26 @@ +plugins { + alias(libs.plugins.androidLibrary) + alias(libs.plugins.kotlin) + alias(libs.plugins.kapt) + alias(libs.plugins.kotlinAllOpen) +} + +dependencies { + api(project(":core-api")) + api(project(":mobile-engage-api")) + api(project(":predict-api")) + + implementation(project(":common")) + implementation(project(":core")) + implementation(project(":mobile-engage")) + implementation(project(":predict")) + + androidTestImplementation(project(":testUtils")) +} +android { + namespace = "com.emarsys.inner" +} + +kotlin { + jvmToolchain(17) +} \ No newline at end of file diff --git a/gradle/common.gradle b/gradle/common.gradle deleted file mode 100644 index 684fc3fa..00000000 --- a/gradle/common.gradle +++ /dev/null @@ -1,62 +0,0 @@ -allprojects { - version = gitVersionName - group = 'com.emarsys' -} - -modules.each { - project(it) { - apply plugin: 'com.android.library' - apply plugin: 'kotlin-android' - apply plugin: "kotlin-allopen" - apply plugin: 'kotlin-kapt' - - android { - buildToolsVersion Config.buildToolsVersion - compileSdkVersion Config.targetApiLevel - defaultConfig { - minSdkVersion Config.minApiLevel - targetSdkVersion Config.targetApiLevel - buildConfigField "int", "VERSION_CODE", "$gitVersionCode" - buildConfigField "String", "VERSION_NAME", "\"$gitVersionName\"" - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - lintOptions { - checkDependencies true - } - compileOptions { - coreLibraryDesugaringEnabled true - } - - kotlin { - jvmToolchain(17) - } - - dependencies { - coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.2.0' - } - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - } - debug { - multiDexKeepProguard file("$rootDir/proguard-multidex-rules.pro") - multiDexEnabled true - } - } - - packagingOptions { - exclude 'README.txt' - exclude 'META-INF/LICENSE.md' - exclude 'META-INF/LICENSE-notice.md' - } - useLibrary 'android.test.runner' - - useLibrary 'android.test.base' - useLibrary 'android.test.mock' - } - allOpen { - annotation("com.emarsys.core.Mockable") - } - } -} \ No newline at end of file diff --git a/gradle/dev.gradle b/gradle/dev.gradle deleted file mode 100644 index 102e02c7..00000000 --- a/gradle/dev.gradle +++ /dev/null @@ -1,12 +0,0 @@ -project.ext.devConfig = new Properties() - -try { - new FileInputStream("$projectDir/localConfig.properties").withStream { - project.ext.devConfig.load(it) - } -} catch (ignore) { -} - -if (project.ext.devConfig) { - println "Using devConfig: $project.ext.devConfig" -} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 8ba366c0..753bd8dd 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -15,6 +15,7 @@ androidx-test-junit = "1.1.5" androidx-lifecycle = "2.7.0" androidx-espresso-idling-resource = "3.5.1" androidx-security-crypto = "1.1.0-alpha06" +androidx-navigation-safe-args = "2.5.0" compose = "1.6.1" compose-compiler = "1.5.6" compose-plugin = "1.6.0-dev1419" @@ -33,6 +34,8 @@ location-services = "21.1.0" webkit = "1.7.0" mockito = "4.9.0" mockito-kotlin = "4.1.0" +grGit = "5.0.0-rc.3" +byte-buddy = "1.14.11" [libraries] kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" } @@ -70,7 +73,8 @@ mockk-android = { module = "io.mockk:mockk-android", version.ref = "mockk" } mockk-agent = { module = "io.mockk:mockk-agent-jvm", version.ref = "mockk" } mockito-android = { module = "org.mockito:mockito-android", version.ref = "mockito" } mockito-kotlin = { module = "org.mockito.kotlin:mockito-kotlin", version.ref = "mockito-kotlin" } -#byte-buddy = { module = "net.bytebuddy:byte-buddy", version.ref = "byte-buddy" } +mockito-core = { module = "org.mockito.kotlin:mockito-core", version.ref = "mockito" } +byte-buddy = { module = "net.bytebuddy:byte-buddy", version.ref = "byte-buddy" } androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidx-test-runner" } androidx-test-rules = { module = "androidx.test:rules", version.ref = "androidx-test-runner" } androidx-test-extensions = { module = "androidx.test.ext:junit", version.ref = "androidx-test-runner" } @@ -82,8 +86,12 @@ androidApplication = { id = "com.android.application", version.ref = "agp" } androidLibrary = { id = "com.android.library", version.ref = "agp" } jetbrainsCompose = { id = "org.jetbrains.compose", version.ref = "compose-plugin" } kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } +navigationSafeArgs = { id = "androidx.navigation.safeargs", version.ref = "androidx-navigation-safe-args" } +kapt = { id = "org.jetbrains.kotlin.kapt", version.ref = "kotlin" } kotlin = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } +kotlinAllOpen = { id = "org.jetbrains.kotlin.plugin.allopen", version.ref = "kotlin" } kotlinSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } agconnect = { id = "com.huawei.agconnect", version.ref = "agconnect_core" } googleServices = { id = "com.google.gms.google-services", version.ref = "googleServices" } +grGit = { id = "org.ajoberstar.grgit", version.ref = "grGit" } diff --git a/gradle/version.gradle b/gradle/version.gradle deleted file mode 100644 index b17f56a2..00000000 --- a/gradle/version.gradle +++ /dev/null @@ -1,42 +0,0 @@ -buildscript { - repositories { - mavenCentral() - maven { - name = 'ajoberstar-backup' - url = 'https://ajoberstar.org/bintray-backup/' - } - } - dependencies { - classpath "org.ajoberstar.grgit:grgit-gradle:4.1.0" - } -} - -import org.ajoberstar.grgit.Grgit - -ext { - git = Grgit.open(currentDir: projectDir) - - try { - if ((System.env.BLACKDUCK == null ? false : System.env.BLACKDUCK) == false) { - git.fetch() - } - } catch(Exception e) { - println("GrGit fetch failed ${e.printStackTrace()}") - } - - gitVersionName = System.env.RELEASE_VERSION == null ? git.describe() : System.env.RELEASE_VERSION - gitVersionCode = gitVersionCode = (int) ((new Date().getTime() - 1602845230) / 10000) - gitVersionCodeTime = git.head().time - git = Grgit.open(currentDir: projectDir) - - gitVersionCodeTime = git.head().time - if (git.describe() == null) { - throw new RuntimeException("Couldn't get Version Name") - } -} - -task printVersion() { - println("Version Name: $gitVersionName") - println("Version Code: $gitVersionCode") - println("Version Code Time: $gitVersionCodeTime") -} \ No newline at end of file diff --git a/mobile-engage-api/build.gradle b/mobile-engage-api/build.gradle deleted file mode 100644 index 0c2d6ef1..00000000 --- a/mobile-engage-api/build.gradle +++ /dev/null @@ -1,11 +0,0 @@ -dependencies { - implementation project(':core-api') - - api Libs.location_services - - androidTestImplementation project(':testUtils') -} -android { - namespace "com.emarsys.mobileengage.api" - sourceCompatibility = 17 -} \ No newline at end of file diff --git a/mobile-engage-api/build.gradle.kts b/mobile-engage-api/build.gradle.kts new file mode 100644 index 00000000..367d166d --- /dev/null +++ b/mobile-engage-api/build.gradle.kts @@ -0,0 +1,22 @@ +plugins { + alias(libs.plugins.androidLibrary) + alias(libs.plugins.kotlin) + alias(libs.plugins.kapt) + alias(libs.plugins.kotlinAllOpen) +} + +dependencies { + implementation(project(":core-api")) + + api(libs.google.location) + + androidTestImplementation(project(":testUtils")) +} + +android { + namespace = "com.emarsys.mobileengage.api" +} + +kotlin { + jvmToolchain(17) +} diff --git a/mobile-engage/build.gradle b/mobile-engage/build.gradle deleted file mode 100644 index 18963ab4..00000000 --- a/mobile-engage/build.gradle +++ /dev/null @@ -1,18 +0,0 @@ -plugins { - id("kotlin-parcelize") -} - -dependencies { - implementation project(':common') - implementation project(':core') - implementation project(':core-api') - implementation project(':mobile-engage-api') - - implementation Libs.webkit - - androidTestImplementation project(':testUtils') -} -android { - namespace "com.emarsys.mobileengage" - sourceCompatibility = 17 -} \ No newline at end of file diff --git a/mobile-engage/build.gradle.kts b/mobile-engage/build.gradle.kts new file mode 100644 index 00000000..855380f7 --- /dev/null +++ b/mobile-engage/build.gradle.kts @@ -0,0 +1,24 @@ +plugins { + alias(libs.plugins.androidLibrary) + alias(libs.plugins.kotlin) + alias(libs.plugins.kapt) + alias(libs.plugins.kotlinAllOpen) +} + +dependencies { + implementation(project(":common")) + implementation(project(":core")) + implementation(project(":core-api")) + implementation(project(":mobile-engage-api")) + + implementation(libs.androidx.webkit) + + androidTestImplementation(project(":testUtils")) +} +android { + namespace = "com.emarsys.mobileengage" +} + +kotlin { + jvmToolchain(17) +} \ No newline at end of file diff --git a/mobile-engage/proguard-rules.pro b/mobile-engage/proguard-rules.pro index 3f37f624..29b8540e 100644 --- a/mobile-engage/proguard-rules.pro +++ b/mobile-engage/proguard-rules.pro @@ -2,7 +2,7 @@ # By default, the flags in this file are appended to flags specified # in /Users/jpollak/Library/Android/sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles -# directive in build.gradle. +# directive in build.gradle.kts. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html diff --git a/predict-api/build.gradle b/predict-api/build.gradle deleted file mode 100644 index 4ceb5d9e..00000000 --- a/predict-api/build.gradle +++ /dev/null @@ -1,9 +0,0 @@ -dependencies { - implementation project(':core') - api project(':core-api') - androidTestImplementation project(':testUtils') -} -android { - namespace "com.emarsys.predict.api" - sourceCompatibility = 17 -} \ No newline at end of file diff --git a/predict-api/build.gradle.kts b/predict-api/build.gradle.kts new file mode 100644 index 00000000..80282bc8 --- /dev/null +++ b/predict-api/build.gradle.kts @@ -0,0 +1,17 @@ +plugins { + alias(libs.plugins.androidLibrary) + alias(libs.plugins.kotlin) +} + +dependencies { + implementation(project(":core")) + api(project(":core-api")) + androidTestImplementation(project(":testUtils")) +} +android { + namespace = "com.emarsys.predict.api" +} + +kotlin { + jvmToolchain(17) +} \ No newline at end of file diff --git a/predict/build.gradle b/predict/build.gradle deleted file mode 100644 index 1c1f2b42..00000000 --- a/predict/build.gradle +++ /dev/null @@ -1,11 +0,0 @@ -dependencies { - implementation project(':core') - implementation project(':core-api') - implementation project(':predict-api') - - androidTestImplementation project(':testUtils') -} -android { - namespace "com.emarsys.predict" - sourceCompatibility = 17 -} \ No newline at end of file diff --git a/predict/build.gradle.kts b/predict/build.gradle.kts new file mode 100644 index 00000000..f0cef546 --- /dev/null +++ b/predict/build.gradle.kts @@ -0,0 +1,22 @@ +plugins { + alias(libs.plugins.androidLibrary) + alias(libs.plugins.kotlin) + alias(libs.plugins.kapt) + alias(libs.plugins.kotlinAllOpen) +} + +dependencies { + implementation(project(":core")) + implementation(project(":core-api")) + implementation(project(":predict-api")) + + androidTestImplementation(project(":testUtils")) +} + +android { + namespace = "com.emarsys.predict" +} + +kotlin { + jvmToolchain(17) +} diff --git a/sample/build.gradle b/sample/build.gradle index 27d485b6..a89b521c 100644 --- a/sample/build.gradle +++ b/sample/build.gradle @@ -1,14 +1,16 @@ -apply plugin: 'com.android.application' -apply plugin: 'kotlin-android' -apply plugin: 'androidx.navigation.safeargs' +plugins { + alias(libs.plugins.androidApplication) + alias(libs.plugins.kotlin) + alias(libs.plugins.kapt) + alias(libs.plugins.navigationSafeArgs) + alias(libs.plugins.kotlinAllOpen) +} group = 'com.emarsys.sample' android { namespace = "com.emarsys.sample" - buildToolsVersion Config.buildToolsVersion - compileSdkVersion Config.targetApiLevel - sourceCompatibility = 17 + compileSdkVersion 34 defaultConfig { applicationId "com.emarsys.sample" minSdkVersion 24 @@ -74,19 +76,6 @@ android { } } -buildscript { - repositories { - mavenLocal() - google() - mavenCentral() - maven { url 'https://developer.huawei.com/repo/' } - } - dependencies { - classpath 'com.google.gms:google-services:4.4.0' - classpath 'com.huawei.agconnect:agcp:1.9.1.303' - } -} - dependencies { if (project.devConfig.useLocalDependency == true || System.env.DEVELOPMENT_MODE == true) { implementation project(':emarsys-sdk') @@ -127,10 +116,3 @@ dependencies { implementation "com.google.code.gson:gson:2.10.1" debugImplementation "androidx.compose.ui:ui-tooling:1.6.0" } - -task startApp(type: Exec, dependsOn: 'installDebug') { - commandLine 'adb', 'shell', 'am', 'start', '-n', 'com.emarsys.sample/.main.MainActivity' -} - -apply plugin: 'com.google.gms.google-services' -apply plugin: 'com.huawei.agconnect' diff --git a/settings.gradle.kts b/settings.gradle.kts index ed654217..58298fdd 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -7,16 +7,26 @@ pluginManagement { maven(url = "https://developer.huawei.com/repo/") maven(url = "https://ajoberstar.org/bintray-backup/") } + resolutionStrategy { + eachPlugin { + if (requested.id.namespace == "com.huawei") { + if (requested.id.id == "com.huawei.agconnect") { + useModule("com.huawei.agconnect:agcp:${requested.version}") + } + } + } + } } dependencyResolutionManagement { - repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() maven(url = "https://maven.google.com") maven(url = "https://developer.huawei.com/repo/") + maven(url = "https://ajoberstar.org/bintray-backup/") } } +rootProject.name = "Android Emarsys SDK" include( ":common", diff --git a/testUtils/build.gradle b/testUtils/build.gradle deleted file mode 100644 index a27be5bf..00000000 --- a/testUtils/build.gradle +++ /dev/null @@ -1,61 +0,0 @@ -apply plugin: 'com.android.library' -apply plugin: 'kotlin-android' - -android { - namespace = "com.emarsys.testUtil" - compileSdk Config.targetApiLevel - sourceCompatibility = 17 - defaultConfig { - minSdkVersion Config.minApiLevel - targetSdkVersion Config.targetApiLevel - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - } - debug { - multiDexEnabled true - } - } - packagingOptions { - resources { - excludes += ['README.txt', 'META-INF/LICENSE.md', 'META-INF/LICENSE-notice.md'] - } - } - - lint { - abortOnError false - } - kotlin { - jvmToolchain(17) - } -} - -group = 'com.emarsys.testUtil' - -dependencies { - implementation Libs.support_appcompat - api TestLibs.support_test_extensions - debugApi TestLibs.support_test_fragment - - api Libs.kotlin - implementation Libs.kotlin_stdlib - implementation Libs.kotlin_reflect - api TestLibs.kotlin_test - api TestLibs.mockito_android - api TestLibs.mockito_core - api TestLibs.kotlin_mockito - api TestLibs.byte_buddy - api TestLibs.support_test_runner - api TestLibs.support_test_rules - api TestLibs.multiDex - api TestLibs.mockk - api TestLibs.mockk_agent -} -configurations{ - api { - exclude group: 'io.mockk',module:'mockk-agent-jvm' - } -} \ No newline at end of file diff --git a/testUtils/build.gradle.kts b/testUtils/build.gradle.kts new file mode 100644 index 00000000..45ed1c35 --- /dev/null +++ b/testUtils/build.gradle.kts @@ -0,0 +1,61 @@ +plugins { + alias(libs.plugins.androidLibrary) + alias(libs.plugins.kotlin) +} + +android { + namespace = "com.emarsys.testUtil" + compileSdk = 34 + defaultConfig { + minSdkVersion(24) + targetSdkVersion(34) + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + buildTypes { + release { + isMinifyEnabled = false + proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro") + } + debug { + multiDexEnabled = true + } + } + packagingOptions { + resources { + excludes += arrayOf("README.txt", "META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + } + } + + lint { + abortOnError = false + } + kotlin { + jvmToolchain(17) + } +} + +group = "com.emarsys.testUtil" + +dependencies { + implementation(libs.androidx.appcompat) + api(libs.androidx.test.extensions) + debugApi(libs.androidx.test.fragment) + + api(libs.kotlin.stdlib) + implementation(libs.kotlin.reflect) + api(libs.kotest.assertions.core) + api(libs.mockito.android) + api(libs.mockito.core) + api(libs.mockito.kotlin) + api(libs.byte.buddy) + api(libs.androidx.test.runner) + api(libs.androidx.test.rules) + api(libs.androidx.test.multidex) + api(libs.mockk.android) + api(libs.mockk.agent) +} +configurations { + api { + exclude(group = "io.mockk", module = "mockk-agent-jvm") + } +} \ No newline at end of file From b2a21faa660c52aebdf4da29dae86947993f6120 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Tue, 20 Feb 2024 18:35:16 +0100 Subject: [PATCH 03/63] chore(gradle): migrate build.gradle to KTS based gradle files SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: matusekma <36794575+matusekma@users.noreply.github.com> --- build.gradle.kts | 44 ++----- buildSrc/src/main/java/GitVersion.kt | 2 +- common/build.gradle | 14 -- common/build.gradle.kts | 24 ++++ core-api/build.gradle.kts | 12 +- core/build.gradle.kts | 15 ++- emarsys-e2e-test/build.gradle.kts | 11 +- .../{build.gradle => build.gradle.kts} | 13 +- emarsys-huawei/build.gradle.kts | 12 +- emarsys-sdk/build.gradle.kts | 11 +- emarsys/build.gradle.kts | 11 +- gradle/libs.versions.toml | 30 ++--- mobile-engage-api/build.gradle.kts | 11 +- mobile-engage/build.gradle.kts | 12 +- predict-api/build.gradle.kts | 11 +- predict/build.gradle.kts | 11 +- sample/build.gradle | 118 ----------------- sample/build.gradle.kts | 122 ++++++++++++++++++ sample/proguard-rules.pro | 2 +- settings.gradle.kts | 1 + testUtils/build.gradle.kts | 10 +- 21 files changed, 291 insertions(+), 206 deletions(-) delete mode 100644 common/build.gradle create mode 100644 common/build.gradle.kts rename emarsys-firebase/{build.gradle => build.gradle.kts} (58%) delete mode 100644 sample/build.gradle create mode 100644 sample/build.gradle.kts diff --git a/build.gradle.kts b/build.gradle.kts index bae1dca8..ea16b7a0 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,45 +1,29 @@ import org.ajoberstar.grgit.Grgit -import java.io.FileInputStream -import java.util.Properties plugins { - alias(libs.plugins.androidLibrary) apply false - alias(libs.plugins.androidApplication) apply false + alias(libs.plugins.android.library) apply false + alias(libs.plugins.android.application) apply false alias(libs.plugins.kotlin) apply false alias(libs.plugins.kapt) apply false - alias(libs.plugins.navigationSafeArgs) apply false - alias(libs.plugins.googleServices) apply false - alias(libs.plugins.kotlinAllOpen) apply false - alias(libs.plugins.grGit) + alias(libs.plugins.androidx.navigation.safeargs) apply false + alias(libs.plugins.google.services) apply false +// alias(libs.plugins.huawei.agconnect) apply false + alias(libs.plugins.kotlin.allopen) apply false + alias(libs.plugins.grgit) + alias(libs.plugins.dotenv) + alias(libs.plugins.kotlin.parcelize) apply false id("com.github.ben-manes.versions") version "0.46.0" } versionData() -loadDevConfig() - -fun loadDevConfig() { - - ext["devConfig"] = Properties() - - try { - val inputStream = FileInputStream("$projectDir/localConfig.properties") - (ext["devConfig"] as Properties).load(inputStream) - - } catch (ignore: Exception) { - } - - if (ext["devConfig"] != null) { - println("Using devConfig: ${ext["devConfig"]}") - } -} fun versionData() { val git = Grgit.open( mapOf("currentDir" to project.rootDir) ) - - if ((if (System.getenv("BLACKDUCK") == null) false else System.getenv("BLACKDUCK")) == false) { + try { git.fetch() + } catch (ignored: Exception) { } if (git.describe() == null) { throw RuntimeException("Couldn't get Version Name") @@ -52,11 +36,9 @@ fun versionData() { versionCode = ((System.currentTimeMillis() - 1602845230) / 10000).toInt(), versionCodeTime = git.head().time ) - ext["gitVersionName"] = v.versionName - ext["gitVersionCode"] = v.versionCode - ext["gitVersionCodeTime"] = v.versionCodeTime + + val version by extra(v) println("versionName: ${v.versionName}") println("versionCode: ${v.versionCode}") - } \ No newline at end of file diff --git a/buildSrc/src/main/java/GitVersion.kt b/buildSrc/src/main/java/GitVersion.kt index 1819f936..571ea659 100644 --- a/buildSrc/src/main/java/GitVersion.kt +++ b/buildSrc/src/main/java/GitVersion.kt @@ -1 +1 @@ -data class GitVersion(val versionName: String, val versionCode: Int, val versionCodeTime: Long) +data class GitVersion(val versionName: String, val versionCode: Int, val versionCodeTime: Long) \ No newline at end of file diff --git a/common/build.gradle b/common/build.gradle deleted file mode 100644 index 8b7b88d7..00000000 --- a/common/build.gradle +++ /dev/null @@ -1,14 +0,0 @@ -plugins { - alias(libs.plugins.androidLibrary) - alias(libs.plugins.kotlin) - alias(libs.plugins.kapt) - alias(libs.plugins.kotlinAllOpen) -} -dependencies { - implementation project(":core-api") - androidTestImplementation project(":testUtils") -} -android { - namespace "com.emarsys.common" - sourceCompatibility = 17 -} \ No newline at end of file diff --git a/common/build.gradle.kts b/common/build.gradle.kts new file mode 100644 index 00000000..bf0b2697 --- /dev/null +++ b/common/build.gradle.kts @@ -0,0 +1,24 @@ +plugins { + alias(libs.plugins.android.library) + alias(libs.plugins.kotlin) + alias(libs.plugins.kotlin.allopen) + alias(libs.plugins.kapt) +} +dependencies { + implementation(project(":core-api")) + androidTestImplementation(project(":testUtils")) +} +android { + namespace = "com.emarsys.common" + defaultConfig { + compileSdk = libs.versions.android.compileSdk.get().toInt() + } +} + +allOpen { + annotation("com.emarsys.core.Mockable") +} + +kotlin { + jvmToolchain(17) +} \ No newline at end of file diff --git a/core-api/build.gradle.kts b/core-api/build.gradle.kts index 8ece3b81..0aa78606 100644 --- a/core-api/build.gradle.kts +++ b/core-api/build.gradle.kts @@ -1,8 +1,8 @@ plugins { - alias(libs.plugins.androidLibrary) + alias(libs.plugins.android.library) alias(libs.plugins.kotlin) + alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) - alias(libs.plugins.kotlinAllOpen) } dependencies { api(libs.androidx.annotation) @@ -16,5 +16,13 @@ dependencies { } android { namespace = "com.emarsys.core.api" + defaultConfig { + compileSdk = libs.versions.android.compileSdk.get().toInt() + } } + +allOpen { + annotation("com.emarsys.core.Mockable") +} + kotlin { jvmToolchain(17) } \ No newline at end of file diff --git a/core/build.gradle.kts b/core/build.gradle.kts index d825ed07..afb4dc27 100644 --- a/core/build.gradle.kts +++ b/core/build.gradle.kts @@ -1,8 +1,8 @@ plugins { - alias(libs.plugins.androidLibrary) + alias(libs.plugins.android.library) alias(libs.plugins.kotlin) + alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) - alias(libs.plugins.kotlinAllOpen) } dependencies { @@ -14,6 +14,17 @@ dependencies { } android { namespace = "com.emarsys.core" + defaultConfig { + val version: GitVersion by rootProject.extra + + compileSdk = libs.versions.android.compileSdk.get().toInt() + buildConfigField("int", "VERSION_CODE", "${version.versionCode}") + buildConfigField("String", "VERSION_NAME", "\"${version.versionName}\"") + } +} + +allOpen { + annotation("com.emarsys.core.Mockable") } kotlin { diff --git a/emarsys-e2e-test/build.gradle.kts b/emarsys-e2e-test/build.gradle.kts index e7bd5bb0..71c2d34b 100644 --- a/emarsys-e2e-test/build.gradle.kts +++ b/emarsys-e2e-test/build.gradle.kts @@ -1,8 +1,8 @@ plugins { - alias(libs.plugins.androidLibrary) + alias(libs.plugins.android.library) alias(libs.plugins.kotlin) + alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) - alias(libs.plugins.kotlinAllOpen) } dependencies { @@ -15,6 +15,13 @@ dependencies { } android { namespace = "com.emarsys.test.e2e" + defaultConfig { + compileSdk = libs.versions.android.compileSdk.get().toInt() + } +} + +allOpen { + annotation("com.emarsys.core.Mockable") } kotlin { diff --git a/emarsys-firebase/build.gradle b/emarsys-firebase/build.gradle.kts similarity index 58% rename from emarsys-firebase/build.gradle rename to emarsys-firebase/build.gradle.kts index 8657b869..7e1517ed 100644 --- a/emarsys-firebase/build.gradle +++ b/emarsys-firebase/build.gradle.kts @@ -1,8 +1,8 @@ plugins { - alias(libs.plugins.androidLibrary) + alias(libs.plugins.android.library) alias(libs.plugins.kotlin) + alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) - alias(libs.plugins.kotlinAllOpen) } dependencies { @@ -11,12 +11,19 @@ dependencies { implementation(project(":mobile-engage")) implementation(project(":mobile-engage-api")) - api(libs.google.fcm, { exclude group: 'androidx' }) + api(libs.google.fcm, { exclude(group = "androidx") }) androidTestImplementation(project(":testUtils")) } android { namespace = "com.emarsys.firebase" + defaultConfig { + compileSdk = libs.versions.android.compileSdk.get().toInt() + } +} + +allOpen { + annotation("com.emarsys.core.Mockable") } kotlin { diff --git a/emarsys-huawei/build.gradle.kts b/emarsys-huawei/build.gradle.kts index 8c3ab26e..350ffe3a 100644 --- a/emarsys-huawei/build.gradle.kts +++ b/emarsys-huawei/build.gradle.kts @@ -1,8 +1,9 @@ plugins { - alias(libs.plugins.androidLibrary) + alias(libs.plugins.android.library) alias(libs.plugins.kotlin) + alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) - alias(libs.plugins.kotlinAllOpen) + // alias(libs.plugins.huawei.agconnect) } dependencies { @@ -17,6 +18,13 @@ dependencies { } android { namespace = "com.emarsys.huawei" + defaultConfig { + compileSdk = libs.versions.android.compileSdk.get().toInt() + } +} + +allOpen { + annotation("com.emarsys.core.Mockable") } kotlin { diff --git a/emarsys-sdk/build.gradle.kts b/emarsys-sdk/build.gradle.kts index 30005d8d..caac7482 100644 --- a/emarsys-sdk/build.gradle.kts +++ b/emarsys-sdk/build.gradle.kts @@ -1,8 +1,8 @@ plugins { - alias(libs.plugins.androidLibrary) + alias(libs.plugins.android.library) alias(libs.plugins.kotlin) + alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) - alias(libs.plugins.kotlinAllOpen) } dependencies { @@ -21,6 +21,13 @@ dependencies { android { namespace = "com.emarsys" + defaultConfig { + compileSdk = libs.versions.android.compileSdk.get().toInt() + } +} + +allOpen { + annotation("com.emarsys.core.Mockable") } kotlin { diff --git a/emarsys/build.gradle.kts b/emarsys/build.gradle.kts index 6778a3b5..869078f5 100644 --- a/emarsys/build.gradle.kts +++ b/emarsys/build.gradle.kts @@ -1,8 +1,8 @@ plugins { - alias(libs.plugins.androidLibrary) + alias(libs.plugins.android.library) alias(libs.plugins.kotlin) + alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) - alias(libs.plugins.kotlinAllOpen) } dependencies { @@ -19,6 +19,13 @@ dependencies { } android { namespace = "com.emarsys.inner" + defaultConfig { + compileSdk = libs.versions.android.compileSdk.get().toInt() + } +} + +allOpen { + annotation("com.emarsys.core.Mockable") } kotlin { diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 753bd8dd..a142ea2c 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,5 +1,10 @@ [versions] agp = "8.2.2" +kotlin = "1.9.21" +kotlinxCoroutines = "1.7.3" +compose = "1.6.1" +compose-compiler = "1.5.6" +compose-plugin = "1.6.0-dev1419" android-compileSdk = "34" android-minSdk = "28" android-targetSdk = "34" @@ -16,14 +21,9 @@ androidx-lifecycle = "2.7.0" androidx-espresso-idling-resource = "3.5.1" androidx-security-crypto = "1.1.0-alpha06" androidx-navigation-safe-args = "2.5.0" -compose = "1.6.1" -compose-compiler = "1.5.6" -compose-plugin = "1.6.0-dev1419" dokka = "1.9.10" junit = "4.13.2" tink = "1.9.0" -kotlin = "1.9.0" -kotlinxCoroutines = "1.7.3" kotest = "5.8.0" mockk = "1.13.9" fcm = "23.4.0" @@ -36,6 +36,7 @@ mockito = "4.9.0" mockito-kotlin = "4.1.0" grGit = "5.0.0-rc.3" byte-buddy = "1.14.11" +dotEnv = "4.0.0" [libraries] kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" } @@ -82,16 +83,15 @@ androidx-test-fragment = { module = "androidx.fragment:fragment-testing", versio androidx-test-multidex = { module = "androidx.multidex:multidex-instrumentation", version.ref = "androidx-test-runner" } [plugins] -androidApplication = { id = "com.android.application", version.ref = "agp" } -androidLibrary = { id = "com.android.library", version.ref = "agp" } -jetbrainsCompose = { id = "org.jetbrains.compose", version.ref = "compose-plugin" } -kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } -navigationSafeArgs = { id = "androidx.navigation.safeargs", version.ref = "androidx-navigation-safe-args" } +android-application = { id = "com.android.application", version.ref = "agp" } +android-library = { id = "com.android.library", version.ref = "agp" } +androidx-navigation-safeargs = { id = "androidx.navigation.safeargs", version.ref = "androidx-navigation-safe-args" } kapt = { id = "org.jetbrains.kotlin.kapt", version.ref = "kotlin" } kotlin = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } -kotlinAllOpen = { id = "org.jetbrains.kotlin.plugin.allopen", version.ref = "kotlin" } -kotlinSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } +kotlin-parcelize = { id = "org.jetbrains.kotlin.plugin.parcelize", version.ref = "kotlin" } +kotlin-allopen = { id = "org.jetbrains.kotlin.plugin.allopen", version.ref = "kotlin" } dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } -agconnect = { id = "com.huawei.agconnect", version.ref = "agconnect_core" } -googleServices = { id = "com.google.gms.google-services", version.ref = "googleServices" } -grGit = { id = "org.ajoberstar.grgit", version.ref = "grGit" } +huawei-agconnect = { id = "com.huawei.agconnect", version.ref = "agconnect_core" } +google-services = { id = "com.google.gms.google-services", version.ref = "googleServices" } +grgit = { id = "org.ajoberstar.grgit", version.ref = "grGit" } +dotenv = { id = "co.uzzu.dotenv.gradle", version.ref = "dotEnv" } diff --git a/mobile-engage-api/build.gradle.kts b/mobile-engage-api/build.gradle.kts index 367d166d..38cc2c3e 100644 --- a/mobile-engage-api/build.gradle.kts +++ b/mobile-engage-api/build.gradle.kts @@ -1,8 +1,8 @@ plugins { - alias(libs.plugins.androidLibrary) + alias(libs.plugins.android.library) alias(libs.plugins.kotlin) + alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) - alias(libs.plugins.kotlinAllOpen) } dependencies { @@ -15,6 +15,13 @@ dependencies { android { namespace = "com.emarsys.mobileengage.api" + defaultConfig { + compileSdk = libs.versions.android.compileSdk.get().toInt() + } +} + +allOpen { + annotation("com.emarsys.core.Mockable") } kotlin { diff --git a/mobile-engage/build.gradle.kts b/mobile-engage/build.gradle.kts index 855380f7..5eb7ffa1 100644 --- a/mobile-engage/build.gradle.kts +++ b/mobile-engage/build.gradle.kts @@ -1,8 +1,9 @@ plugins { - alias(libs.plugins.androidLibrary) + alias(libs.plugins.android.library) alias(libs.plugins.kotlin) + alias(libs.plugins.kotlin.allopen) + alias(libs.plugins.kotlin.parcelize) alias(libs.plugins.kapt) - alias(libs.plugins.kotlinAllOpen) } dependencies { @@ -17,6 +18,13 @@ dependencies { } android { namespace = "com.emarsys.mobileengage" + defaultConfig { + compileSdk = libs.versions.android.compileSdk.get().toInt() + } +} + +allOpen { + annotation("com.emarsys.core.Mockable") } kotlin { diff --git a/predict-api/build.gradle.kts b/predict-api/build.gradle.kts index 80282bc8..33e67fc5 100644 --- a/predict-api/build.gradle.kts +++ b/predict-api/build.gradle.kts @@ -1,6 +1,8 @@ plugins { - alias(libs.plugins.androidLibrary) + alias(libs.plugins.android.library) alias(libs.plugins.kotlin) + alias(libs.plugins.kotlin.allopen) + alias(libs.plugins.kapt) } dependencies { @@ -10,6 +12,13 @@ dependencies { } android { namespace = "com.emarsys.predict.api" + defaultConfig { + compileSdk = libs.versions.android.compileSdk.get().toInt() + } +} + +allOpen { + annotation("com.emarsys.core.Mockable") } kotlin { diff --git a/predict/build.gradle.kts b/predict/build.gradle.kts index f0cef546..331af248 100644 --- a/predict/build.gradle.kts +++ b/predict/build.gradle.kts @@ -1,8 +1,8 @@ plugins { - alias(libs.plugins.androidLibrary) + alias(libs.plugins.android.library) alias(libs.plugins.kotlin) + alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) - alias(libs.plugins.kotlinAllOpen) } dependencies { @@ -15,6 +15,13 @@ dependencies { android { namespace = "com.emarsys.predict" + defaultConfig { + compileSdk = libs.versions.android.compileSdk.get().toInt() + } +} + +allOpen { + annotation("com.emarsys.core.Mockable") } kotlin { diff --git a/sample/build.gradle b/sample/build.gradle deleted file mode 100644 index a89b521c..00000000 --- a/sample/build.gradle +++ /dev/null @@ -1,118 +0,0 @@ -plugins { - alias(libs.plugins.androidApplication) - alias(libs.plugins.kotlin) - alias(libs.plugins.kapt) - alias(libs.plugins.navigationSafeArgs) - alias(libs.plugins.kotlinAllOpen) -} - -group = 'com.emarsys.sample' - -android { - namespace = "com.emarsys.sample" - compileSdkVersion 34 - defaultConfig { - applicationId "com.emarsys.sample" - minSdkVersion 24 - targetSdkVersion 34 - multiDexEnabled true - versionCode gitVersionCode - versionName gitVersionName - testInstrumentationRunner "com.emarsys.sample.testutils.SampleAppTestRunner" - resValue "string", "sdk_version", "${gitVersionName}" - - def clientId = null - def localConfigPropertiesFile = rootProject.file('localConfig.properties') - def localConfigProperties = new Properties() - if (localConfigPropertiesFile.exists()) { - localConfigProperties.load(new FileInputStream(localConfigPropertiesFile)) - clientId = localConfigProperties.getProperty("googleOAuthServerClientId") - } - - buildConfigField "String", "GOOGLE_OAUTH_SERVER_CLIENT_ID", "\"${System.env.GOOGLE_OAUTH_SERVER_CLIENT_ID ?: clientId}\"" - } - - buildFeatures { - compose true - } - - kotlin { - jvmToolchain(17) - } - - composeOptions { - kotlinCompilerExtensionVersion '1.5.1' - kotlinCompilerVersion '1.9.0' - } - - if (project.devConfig.releaseSampleApp || System.env.DEVELOPMENT_MODE) { - signingConfigs { - release { - storePassword System.env.RELEASE_STORE_PASSWORD ?: project.devConfig.releaseStorePassword - keyAlias System.env.RELEASE_KEY_ALIAS ?: project.devConfig.releaseKeyAlias - keyPassword System.env.RELEASE_KEY_PASSWORD ?: project.devConfig.releaseKeyPassword - storeFile file(System.env.RELEASE_STORE_FILE ?: project.devConfig.releaseStoreFile) - } - } - buildTypes { - release { - signingConfig signingConfigs.release - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - } - } - } - - buildTypes { - debug { - multiDexKeepProguard file("proguard-multidex-rules.pro") - multiDexEnabled true - } - } - packagingOptions { - resources { - excludes += ['META-INF/LICENSE.md', 'META-INF/LICENSE-notice.md'] - } - } -} - -dependencies { - if (project.devConfig.useLocalDependency == true || System.env.DEVELOPMENT_MODE == true) { - implementation project(':emarsys-sdk') - implementation project(':emarsys-firebase') - implementation project(':emarsys-huawei') - } else { - implementation 'com.emarsys:emarsys-sdk:+' - implementation 'com.emarsys:emarsys-firebase:+' - implementation 'com.emarsys:emarsys-huawei:+' - } - // Getting a "Could not find firebase-core" error? Make sure you have - // the latest Google Repository in the Android SDK manager - - implementation "org.jetbrains.kotlin:kotlin-reflect:1.9.21" - implementation "org.jetbrains.kotlin:kotlin-stdlib:1.9.21" - implementation 'com.google.android.material:material:1.11.0' - implementation 'com.android.support:cardview-v7:28.0.0' - implementation 'com.google.android.gms:play-services-auth:20.7.0' - implementation 'androidx.appcompat:appcompat:1.6.1' - implementation 'io.coil-kt:coil:2.5.0' - - implementation "androidx.core:core-ktx:1.12.0" - implementation "com.google.android.material:material:1.11.0" - implementation "androidx.compose.ui:ui:1.6.0" - implementation "androidx.compose.material:material:1.6.0" - implementation "androidx.compose.ui:ui-tooling-preview:1.6.0" - implementation "androidx.navigation:navigation-compose:2.7.6" - implementation "androidx.compose.material:material-icons-extended:1.6.0" - implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.7.0" - implementation "androidx.activity:activity-compose:1.8.2" - implementation "io.coil-kt:coil-compose:2.5.0" - implementation "androidx.datastore:datastore-preferences:1.0.0" - implementation "com.chibatching.kotpref:kotpref:2.13.2" - implementation "com.google.firebase:firebase-common-ktx:20.4.2" - implementation "com.google.firebase:firebase-messaging-ktx:23.4.0" - implementation "com.google.android.gms:play-services-auth:20.7.0" - implementation "com.google.accompanist:accompanist-swiperefresh:0.34.0" - implementation "com.google.code.gson:gson:2.10.1" - debugImplementation "androidx.compose.ui:ui-tooling:1.6.0" -} diff --git a/sample/build.gradle.kts b/sample/build.gradle.kts new file mode 100644 index 00000000..043083e2 --- /dev/null +++ b/sample/build.gradle.kts @@ -0,0 +1,122 @@ +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin) + alias(libs.plugins.kotlin.allopen) + alias(libs.plugins.kapt) + alias(libs.plugins.androidx.navigation.safeargs) + alias(libs.plugins.google.services) +// alias(libs.plugins.huawei.agconnect) +} + +group = "com.emarsys.sample" + +android { + namespace = "com.emarsys.sample" + defaultConfig { + applicationId = "com.emarsys.sample" + compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + lint { + targetSdk = libs.versions.android.targetSdk.get().toInt() + } + multiDexEnabled = true + val version: GitVersion by rootProject.extra + versionCode = version.versionCode + versionName = version.versionName + + testInstrumentationRunner = "com.emarsys.sample.testutils.SampleAppTestRunner" + resValue("string", "sdk_version", version.versionName) + buildConfigField( + "String", + "GOOGLE_OAUTH_SERVER_CLIENT_ID", + "\"${env.GOOGLE_OAUTH_SERVER_CLIENT_ID.value}\"" + ) + } + + buildFeatures { + compose = true + } + + allOpen { + annotation("com.emarsys.core.Mockable") + } + + kotlin { + jvmToolchain(17) + } + + composeOptions { + kotlinCompilerExtensionVersion = libs.versions.compose.compiler.get().toString() + } + + if (env.RELEASE_MODE.orElse("false") == "true") { + signingConfigs { + create("release") { + storePassword = env.ANDROID_RELEASE_STORE_PASSWORD.value + keyAlias = env.ANDROID_RELEASE_KEY_ALIAS.value + keyPassword = env.ANDROID_RELEASE_KEY_PASSWORD.value + storeFile = file(env.ANDROID_RELEASE_STORE_FILE_BASE64.value) + } + } + buildTypes { + getByName("release") { + signingConfig = signingConfigs.getByName("release") + isMinifyEnabled = false + proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro") + } + } + } + + buildTypes { + getByName("debug") { + multiDexKeepProguard = file("proguard-multidex-rules.pro") + multiDexEnabled = true + } + } + packagingOptions { + resources { + excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + } + } +} + +dependencies { + if (env.USE_LOCAL_DEPENDENCY.orElse("false") == "true") { + implementation(project(":emarsys-sdk")) + implementation(project(":emarsys-firebase")) + implementation(project(":emarsys-huawei")) + } else { + implementation("com.emarsys:emarsys-sdk:+") + implementation("com.emarsys:emarsys-firebase:+") + implementation("com.emarsys:emarsys-huawei:+") + } + // Getting a "Could not find firebase-core" error? Make sure you have + // the latest Google Repository in the Android SDK manager + + implementation("org.jetbrains.kotlin:kotlin-reflect:1.9.21") + implementation("org.jetbrains.kotlin:kotlin-stdlib:1.9.21") + implementation("com.google.android.material:material:1.11.0") + implementation("com.android.support:cardview-v7:28.0.0") + implementation("com.google.android.gms:play-services-auth:20.7.0") + implementation("androidx.appcompat:appcompat:1.6.1") + implementation("io.coil-kt:coil:2.5.0") + + implementation("androidx.core:core-ktx:1.12.0") + implementation("com.google.android.material:material:1.11.0") + implementation("androidx.compose.ui:ui:1.6.0") + implementation("androidx.compose.material:material:1.6.0") + implementation("androidx.compose.ui:ui-tooling-preview:1.6.0") + implementation("androidx.navigation:navigation-compose:2.7.6") + implementation("androidx.compose.material:material-icons-extended:1.6.0") + implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0") + implementation("androidx.activity:activity-compose:1.8.2") + implementation("io.coil-kt:coil-compose:2.5.0") + implementation("androidx.datastore:datastore-preferences:1.0.0") + implementation("com.chibatching.kotpref:kotpref:2.13.2") + implementation("com.google.firebase:firebase-common-ktx:20.4.2") + implementation("com.google.firebase:firebase-messaging-ktx:23.4.0") + implementation("com.google.android.gms:play-services-auth:20.7.0") + implementation("com.google.accompanist:accompanist-swiperefresh:0.34.0") + implementation("com.google.code.gson:gson:2.10.1") + debugImplementation("androidx.compose.ui:ui-tooling:1.6.0") +} \ No newline at end of file diff --git a/sample/proguard-rules.pro b/sample/proguard-rules.pro index 9a66704b..ee71bd71 100644 --- a/sample/proguard-rules.pro +++ b/sample/proguard-rules.pro @@ -2,7 +2,7 @@ # By default, the flags in this file are appended to flags specified # in /Users/jpollak/Library/Android/sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles -# directive in build.gradle. +# directive in build.gradle.kts. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html diff --git a/settings.gradle.kts b/settings.gradle.kts index 58298fdd..97ee31f5 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -24,6 +24,7 @@ dependencyResolutionManagement { maven(url = "https://maven.google.com") maven(url = "https://developer.huawei.com/repo/") maven(url = "https://ajoberstar.org/bintray-backup/") + maven(url = "https://androidx.dev/storage/compose-compiler/repository/") } } rootProject.name = "Android Emarsys SDK" diff --git a/testUtils/build.gradle.kts b/testUtils/build.gradle.kts index 45ed1c35..08c54dc6 100644 --- a/testUtils/build.gradle.kts +++ b/testUtils/build.gradle.kts @@ -1,14 +1,16 @@ plugins { - alias(libs.plugins.androidLibrary) + alias(libs.plugins.android.library) alias(libs.plugins.kotlin) } android { namespace = "com.emarsys.testUtil" - compileSdk = 34 + compileSdk = libs.versions.android.compileSdk.get().toInt() defaultConfig { - minSdkVersion(24) - targetSdkVersion(34) + minSdk = libs.versions.android.minSdk.get().toInt() + lint { + targetSdk = libs.versions.android.targetSdk.get().toInt() + } testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } buildTypes { From e420e5eef17d46bda792b0a1903528f13ceeae20 Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Wed, 21 Feb 2024 14:57:42 +0100 Subject: [PATCH 04/63] chore(gradle): create gradle task for .env value handling SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: megamegax --- build.gradle.kts | 19 +++++++++++++++++ run_all_tests_on_firebase.sh | 40 ------------------------------------ 2 files changed, 19 insertions(+), 40 deletions(-) delete mode 100755 run_all_tests_on_firebase.sh diff --git a/build.gradle.kts b/build.gradle.kts index ea16b7a0..1dd3a02e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,4 +1,5 @@ import org.ajoberstar.grgit.Grgit +import java.util.Base64 plugins { alias(libs.plugins.android.library) apply false @@ -41,4 +42,22 @@ fun versionData() { println("versionName: ${v.versionName}") println("versionCode: ${v.versionCode}") +} + +tasks { + register("base64EnvToFile") { + val propertyName = project.property("propertyName") as String? + ?: throw IllegalArgumentException("Property 'propertyName' is not provided.") + val file = project.property("file") as String? + ?: throw IllegalArgumentException("Property 'file' is not provided.") + + doLast { + val base64String = env.fetch(propertyName) + val decoder = Base64.getDecoder() + val decodedString = String(decoder.decode(base64String)) + + val outputFile = file(file) + outputFile.writeText(decodedString) + } + } } \ No newline at end of file diff --git a/run_all_tests_on_firebase.sh b/run_all_tests_on_firebase.sh deleted file mode 100755 index 334e1b62..00000000 --- a/run_all_tests_on_firebase.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/bin/bash - -PIDS="" -RESULT=0 -MODULES=" -core-api -core -common -mobile-engage-api -mobile-engage -predict-api -predict -emarsys -emarsys-sdk -emarsys-e2e -emarsys-firebase -emarsys-huawei -" -set -ex - -curl -o /tmp/sacc_key.json $BITRISEIO_SERVICE_ACCOUNT_KEY_URL - -#Activate cloud client with the service account -gcloud auth activate-service-account -q --key-file /tmp/sacc_key.json -#Set the project's id used on Google Cloud Platform -gcloud config set project $GCP_PROJECT - -for i in $MODULES; do - gcloud firebase test android run --type instrumentation --test "$i/build/outputs/apk/androidTest/debug/$i-debug-androidTest.apk" --app=/bitrise/deploy/sample-debug-androidTest.apk $FIREBASE_DEVICES --timeout 20m --quiet --project ems-mobile-sdk & - PIDS="$PIDS $!" -done - -for PID in $PIDS; do - wait $PID || let "RESULT=1" -done - -if [[ "$RESULT" == "1" ]]; - then - exit 1 -fi \ No newline at end of file From 4fef9df50b13d2db9c687641d0d7054727e7ca8b Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Thu, 22 Feb 2024 11:25:12 +0100 Subject: [PATCH 05/63] chore(project): updated .env.example and .gitignore SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: megamegax --- .env.example | 8 +------- .gitignore | 4 +++- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/.env.example b/.env.example index f4e5f2ca..24efaabf 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,4 @@ USE_LOCAL_DEPENDENCY= -GOOGLE_SERVICES_API_KEY= RELEASE_MODE= ANDROID_RELEASE_STORE_FILE_BASE64= ANDROID_RELEASE_STORE_PASSWORD= @@ -14,9 +13,4 @@ OSSRH_PASSWORD= SONATYPE_STAGING_PROFILE_ID= SONATYPE_SIGNING_KEY_ID= SONATYPE_SIGNING_PASSWORD= -SONATYPE_SIGNING_SECRET_KEY_RING_FILE= -DETECT_LATEST_RELEASE_VERSION= -DETECT_PROJECT_USER_GROUPS= -DETECT_PROJECT_VERSION_DISTRIBUTION= -BLACKDUCK_ACCESS_TOKEN= -BLACKDUCK_URL= \ No newline at end of file +SONATYPE_SIGNING_SECRET_KEY_RING_FILE_BASE64= \ No newline at end of file diff --git a/.gitignore b/.gitignore index 455e1ce2..ea1f6a9f 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,6 @@ localConfig.properties sample/google-services.json sample/agconnect-services.json .fleet -.env \ No newline at end of file +.env +firebase_service_account.json +workflow.secrets \ No newline at end of file From 62c130a42425997b3b2b473c7ca8dc26e31184c0 Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Thu, 22 Feb 2024 11:43:27 +0100 Subject: [PATCH 06/63] chore(pipeline): modified pipelines SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: megamegax --- .github/workflows/nightly_e2e_workflow.yml | 1 - .github/workflows/nightly_workflow.yml | 1 - .github/workflows/on_push_workflow.yml | 30 ++- .github/workflows/on_push_workflow_new.yml | 252 +++++++++++++++++++++ .github/workflows/on_tag_workflow.yml | 1 - Makefile | 61 +++++ 6 files changed, 333 insertions(+), 13 deletions(-) create mode 100644 .github/workflows/on_push_workflow_new.yml create mode 100644 Makefile diff --git a/.github/workflows/nightly_e2e_workflow.yml b/.github/workflows/nightly_e2e_workflow.yml index 0cd3361b..161ffe23 100644 --- a/.github/workflows/nightly_e2e_workflow.yml +++ b/.github/workflows/nightly_e2e_workflow.yml @@ -11,7 +11,6 @@ env: RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} RELEASE_STORE_FILE: ${{ secrets.RELEASE_STORE_FILE }} DEVELOPMENT_MODE: ${{ secrets.DEVELOPMENT_MODE }} - GOOGLE_SERVICES_API_KEY: ${{ secrets.GOOGLE_SERVICES_API_KEY }} SLACK_CHANNEL: ${{ secrets.SLACK_CHANNEL }} SLACK_ICON: https://icons.iconarchive.com/icons/martz90/circle/256/android-icon.png SLACK_TITLE: Commit status diff --git a/.github/workflows/nightly_workflow.yml b/.github/workflows/nightly_workflow.yml index 1e9bcc5d..22cbdfd0 100644 --- a/.github/workflows/nightly_workflow.yml +++ b/.github/workflows/nightly_workflow.yml @@ -11,7 +11,6 @@ env: RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} RELEASE_STORE_FILE: ${{ secrets.RELEASE_STORE_FILE }} DEVELOPMENT_MODE: ${{ secrets.DEVELOPMENT_MODE }} - GOOGLE_SERVICES_API_KEY: ${{ secrets.GOOGLE_SERVICES_API_KEY }} SLACK_CHANNEL: ${{ secrets.SLACK_CHANNEL }} SLACK_ICON: https://icons.iconarchive.com/icons/martz90/circle/256/android-icon.png SLACK_TITLE: Nightly build status diff --git a/.github/workflows/on_push_workflow.yml b/.github/workflows/on_push_workflow.yml index 1fb4f5cc..51f3b5fc 100644 --- a/.github/workflows/on_push_workflow.yml +++ b/.github/workflows/on_push_workflow.yml @@ -11,7 +11,23 @@ env: RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} RELEASE_STORE_FILE: ${{ secrets.RELEASE_STORE_FILE }} DEVELOPMENT_MODE: ${{ secrets.DEVELOPMENT_MODE }} - GOOGLE_SERVICES_API_KEY: ${{ secrets.GOOGLE_SERVICES_API_KEY }} + + USE_LOCAL_DEPENDENCY: ${{ vars.USE_LOCAL_DEPENDENCY }} + RELEASE_MODE: ${{ vars.RELEASE_MODE }} + ANDROID_RELEASE_STORE_FILE_BASE64: ${{ secrets.ANDROID_RELEASE_STORE_FILE_BASE64 }} + ANDROID_RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_RELEASE_STORE_PASSWORD }} + ANDROID_RELEASE_KEY_ALIAS: ${{ secrets.ANDROID_RELEASE_KEY_ALIAS }} + ANDROID_RELEASE_KEY_PASSWORD: ${{ secrets.ANDROID_RELEASE_KEY_PASSWORD }} + FIREBASE_PROJECT_ID: ${{ vars.FIREBASE_PROJECT_ID }} + FIREBASE_SERVICE_ACCOUNT_JSON: ${{ secrets.FIREBASE_SERVICE_ACCOUNT_JSON }} + GOOGLE_OAUTH_SERVER_CLIENT_ID: ${{ secrets.GOOGLE_OAUTH_SERVER_CLIENT_ID }} + GOOGLE_SERVICES_JSON_BASE64: ${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }} + OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} + OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} + SONATYPE_STAGING_PROFILE_ID: ${{ secrets.SONATYPE_STAGING_PROFILE_ID }} + SONATYPE_SIGNING_KEY_ID: ${{ secrets.SONATYPE_SIGNING_KEY_ID }} + SONATYPE_SIGNING_PASSWORD: ${{ secrets.SONATYPE_SIGNING_PASSWORD }} + SONATYPE_SIGNING_SECRET_KEY_RING_FILE_BASE64: ${{ secrets.SONATYPE_SIGNING_SECRET_KEY_RING_FILE_BASE64 }} SLACK_CHANNEL: ${{ secrets.SLACK_CHANNEL }} SLACK_ICON: https://icons.iconarchive.com/icons/martz90/circle/256/android-icon.png SLACK_TITLE: Commit status @@ -35,18 +51,12 @@ jobs: with: distribution: 'temurin' java-version: 17 - - name: create-google services json - uses: jsdaniell/create-json@1.1.2 - with: - name: google-services.json - json: ${{ secrets.GOOGLE_SERVICES_JSON }} - dir: sample - - name: create local.properties - run: echo $ANDROID_HOME > local.properties + - name: Prepare CI + run: make prepare-ci - name: Build with Gradle - run: ./gradlew clean assembleAndroidTest -x lint + run: make build-test - name: upload sample app artifact uses: actions/upload-artifact@v2 diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml new file mode 100644 index 00000000..837d25f4 --- /dev/null +++ b/.github/workflows/on_push_workflow_new.yml @@ -0,0 +1,252 @@ +name: Last push build + +on: + workflow_dispatch: + +env: + USE_LOCAL_DEPENDENCY: ${{ vars.USE_LOCAL_DEPENDENCY }} + RELEASE_MODE: ${{ vars.RELEASE_MODE }} + ANDROID_RELEASE_STORE_FILE_BASE64: ${{ secrets.ANDROID_RELEASE_STORE_FILE_BASE64 }} + ANDROID_RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_RELEASE_STORE_PASSWORD }} + ANDROID_RELEASE_KEY_ALIAS: ${{ secrets.ANDROID_RELEASE_KEY_ALIAS }} + ANDROID_RELEASE_KEY_PASSWORD: ${{ secrets.ANDROID_RELEASE_KEY_PASSWORD }} + FIREBASE_PROJECT_ID: ${{ vars.FIREBASE_PROJECT_ID }} + FIREBASE_SERVICE_ACCOUNT_JSON: ${{ secrets.FIREBASE_SERVICE_ACCOUNT_JSON }} + GOOGLE_OAUTH_SERVER_CLIENT_ID: ${{ secrets.GOOGLE_OAUTH_SERVER_CLIENT_ID }} + GOOGLE_SERVICES_JSON_BASE64: ${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }} + OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} + OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} + SONATYPE_STAGING_PROFILE_ID: ${{ secrets.SONATYPE_STAGING_PROFILE_ID }} + SONATYPE_SIGNING_KEY_ID: ${{ secrets.SONATYPE_SIGNING_KEY_ID }} + SONATYPE_SIGNING_PASSWORD: ${{ secrets.SONATYPE_SIGNING_PASSWORD }} + SONATYPE_SIGNING_SECRET_KEY_RING_FILE_BASE64: ${{ secrets.SONATYPE_SIGNING_SECRET_KEY_RING_FILE_BASE64 }} + SLACK_CHANNEL: ${{ secrets.SLACK_CHANNEL }} + SLACK_ICON: https://icons.iconarchive.com/icons/martz90/circle/256/android-icon.png + SLACK_TITLE: Commit status + SLACK_USERNAME: Emarsys SDK - Android + SLACK_WEBHOOK: ${{ secrets.SLACK_MOBILE_TEAM_CI_CHANNEL_WEBHOOK }} + +jobs: + Build: + runs-on: ubuntu-latest + name: Build job + steps: + - uses: actions/checkout@v4 + with: + ref: dev + submodules: true + fetch-depth: 0 # 0 indicates all history + + - name: set up JDK 1.17 + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: 17 + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 + + - name: Prepare CI + run: make prepare-ci + + - name: Build with Gradle + run: make build-test + + Test: + needs: Build + runs-on: ubuntu-latest + name: Test modules + strategy: + matrix: + include: + - module: core + - module: mobile-engage + - module: predict + - module: emarsys-firebase + - module: emarsys-huawei + - module: emarsys-sdk + steps: + - uses: actions/checkout@v4 + with: + ref: dev + submodules: true + fetch-depth: 0 # 0 indicates all history + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 + + - name: Prepare CI + run: make prepare-ci + + - name: Authenticate to Google Cloud + if: matrix.platform == 'android' + uses: google-github-actions/auth@v2.1.1 + with: + credentials_json: ${{ env.FIREBASE_SERVICE_ACCOUNT_JSON }} + + - name: Set up Cloud SDK + if: matrix.platform == 'android' + uses: google-github-actions/setup-gcloud@v2 + with: + project_id: ${{ env.FIREBASE_PROJECT_ID }} + + - name: create apks + run: make create-apks + + - name: test core + if: matrix.module == 'core' + run: make test-android-firebase MODULE_NAME=core + + - name: test mobile-engage + if: matrix.module == 'mobile-engage' + run: make test-android-firebase MODULE_NAME=mobile-engage + + - name: test predict + if: matrix.module == 'predict' + run: make test-android-firebase MODULE_NAME=predict + + - name: test emarsys-firebase + if: matrix.module == 'emarsys-firebase' + run: make test-android-firebase MODULE_NAME=emarsys-firebase + + - name: test emarsys-huawei + if: matrix.module == 'emarsys-huawei' + run: make test-android-firebase MODULE_NAME=emarsys-huawei + + - name: test emarsys-sdk + if: matrix.module == 'emarsys-sdk' + run: make test-android-firebase MODULE_NAME=emarsys-sdk + +# GradleLint: +# name: Run lint on project +# runs-on: ubuntu-latest +# steps: +# - uses: actions/checkout@v3 +# with: +# submodules: true +# fetch-depth: 0 # 0 indicates all history +# - run: git fetch --all || echo "==> Accept any result" +# - name: set up JDK 1.17 +# uses: actions/setup-java@v3 +# with: +# distribution: 'temurin' +# java-version: 17 +# - name: create-google services json +# uses: jsdaniell/create-json@1.1.2 +# with: +# name: google-services.json +# json: ${{ secrets.GOOGLE_SERVICES_JSON }} +# dir: sample +# +# - name: create local.properties +# run: echo $ANDROID_HOME > local.properties +# +# - name: Lint project with Gradle +# run: ./gradlew lint + +# CreateReleaseBundle: +# name: Create release bundle +# needs: Build +# runs-on: ubuntu-latest +# steps: +# - uses: actions/checkout@v3 +# with: +# submodules: true +# fetch-depth: 0 # 0 indicates all history +# - run: git fetch --all || echo "==> Accept any result" +# - name: set up JDK 1.17 +# uses: actions/setup-java@v3 +# with: +# distribution: 'temurin' +# java-version: 17 +# - name: create-google services json +# uses: jsdaniell/create-json@1.1.2 +# with: +# name: google-services.json +# json: ${{ secrets.GOOGLE_SERVICES_JSON }} +# dir: sample +# +# - name: create local.properties +# run: echo $ANDROID_HOME > local.properties +# +# - name: Create release keystore file +# shell: bash +# run: | +# echo "${{ secrets.ANDROID_KEYSTORE }}" > mobile-team-android.jks.asc +# gpg -d --passphrase "${{ secrets.ANDROID_GPG_PASSWORD }}" --batch mobile-team-android.jks.asc > sample/mobile-team-android.jks +# - name: Create release sample app with Gradle +# run: ./gradlew :sample:bundleRelease +# +# - name: Upload bundle +# uses: actions/upload-artifact@v2 +# with: +# name: mobile-sdk-sample +# path: sample/build/outputs/bundle/release/sample-release.aab + +# ReleaseSample: +# name: Release sample app +# runs-on: ubuntu-latest +# needs: [ Build, TestCore, TestMobileEngage, TestPredict, TestEmarsysSDK, TestEmarsys, TestCommon, TestEmarsysFirebase, TestEmarsysHuawei, CreateReleaseBundle, GradleLint ] +# steps: +# - uses: actions/checkout@v3 +# with: +# submodules: true +# fetch-depth: 0 # 0 indicates all history +# - run: git fetch --all || echo "==> Accept any result" +# +# - name: Download sample app +# uses: actions/download-artifact@v2 +# with: +# name: mobile-sdk-sample +# +# - name: create-google services json +# uses: jsdaniell/create-json@1.1.2 +# with: +# name: google-play-services.json +# json: ${{ secrets.GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON }} +# +# - name: Playstore upload +# uses: r0adkll/upload-google-play@v1.0.15 +# with: +# serviceAccountJson: google-play-services.json +# packageName: com.emarsys.sample +# releaseFile: sample-release.aab +# track: alpha +# +# SlackNotification: +# name: Send slack notification +# runs-on: ubuntu-latest +# needs: [ ReleaseSample ] +# steps: +# - name: Slack Notification +# uses: megamegax/slack_action@0.2.3 +# with: +# channel: '${{env.SLACK_CHANNEL}}' +# message: 'Last push build successful! :man-gesturing-ok: :bananadance:' +# user_name: '${{env.SLACK_USERNAME}}' +# job_status: 'success' +# user_icon: '${{env.SLACK_ICON}}' +# actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" },{ "type": "button", "text": "Install page", "url": "http://ems-mobileteam-artifacts.s3-website-eu-west-1.amazonaws.com/index-ems.html" }]' + +# +# SlackNotificationOnError: +# name: Send slack on error +# runs-on: ubuntu-latest +# needs: [ ReleaseSample ] +# if: ${{ failure() }} +# steps: +# - uses: actions/checkout@v3 +# with: +# submodules: true +# fetch-depth: 0 # 0 indicates all history +# - run: git fetch --all || echo "==> Accept any result" +# +# - name: Slack Notification +# uses: megamegax/slack_action@0.2.3 +# with: +# channel: '${{env.SLACK_CHANNEL}}' +# message: 'Last push build failed! :man-gesturing-no: :blobcatfearful:' +# user_name: '${{env.SLACK_USERNAME}}' +# job_status: 'failure' +# user_icon: '${{env.SLACK_ICON}}' +# actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" }]' diff --git a/.github/workflows/on_tag_workflow.yml b/.github/workflows/on_tag_workflow.yml index cbd6a140..5cb2c7f9 100644 --- a/.github/workflows/on_tag_workflow.yml +++ b/.github/workflows/on_tag_workflow.yml @@ -11,7 +11,6 @@ env: RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} RELEASE_STORE_FILE: ${{ secrets.RELEASE_STORE_FILE }} DEVELOPMENT_MODE: ${{ secrets.DEVELOPMENT_MODE }} - GOOGLE_SERVICES_API_KEY: ${{ secrets.GOOGLE_SERVICES_API_KEY }} SLACK_CHANNEL: ${{ secrets.SLACK_CHANNEL }} SLACK_ICON: https://icons.iconarchive.com/icons/martz90/circle/256/android-icon.png SLACK_TITLE: New SDK Release diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..a7f7d9d0 --- /dev/null +++ b/Makefile @@ -0,0 +1,61 @@ +.PHONY: check-env help build-test create-apks prepare-ci run-github-workflow-locally test-android-firebase test-android-firebase-emulator +.DEFAULT_GOAL := help + +ifneq (,$(wildcard .env)) +include .env +export +endif + +REQUIRED_VARS := $(shell cat .env.example | sed 's/=.*//' | xargs) +check-env: + @MISSING_VARS=""; \ + for var in $(REQUIRED_VARS); do \ + if [ -z "$${!var+x}" ]; then \ + MISSING_VARS="$$MISSING_VARS $$var"; \ + fi; \ + done; \ + if [ -n "$$MISSING_VARS" ]; then \ + echo "Missing environment variables:$$MISSING_VARS"; \ + echo "Please set them in your .env file or as system environment variables. Check https://secret.emarsys.net/cred/detail/18243/"; \ + exit 1; \ + fi + +help: check-env ## Show this help + @echo "Targets:" + @fgrep -h "##" $(MAKEFILE_LIST) | grep ":" | fgrep -v fgrep | sed -e 's/\\$$//' | sed -e 's/\(.*\):.*##[ \t]*/ \1 ## /' | sort | column -t -s '##' + @echo + +build-test: check-env ## builds android tests excluding and lint + @./gradlew clean assembleAndroidTest -x lint -x + +create-apks: check-env ## create apks for testing + @./gradlew assembleAndroidTest -x :sample:test + +prepare-ci: check-env ## setup prerequisites for pipeline + @chmod +x gradlew + @echo $ANDROID_HOME > local.properties + @./gradlew base64EnvToFile -PpropertyName=GOOGLE_SERVICES_JSON_BASE64 -Pfile=./sample/google-services.json + +test-android-firebase-emulator: check-env ## run Android Instrumented tests on emulators on Firebase Test Lab + @gcloud firebase test android run \ + --type instrumentation \ + --app ./sample/build/outputs/apk/androidTest/debug/sample-debug-androidTest.apk \ + --test ./$(MODULE_NAME)/build/outputs/apk/androidTest/debug/$(MODULE_NAME)-debug-androidTest.apk \ + --device model=Nexus5X,version=24,locale=en,orientation=portrait \ + --device model=Pixel2,version=30,locale=en,orientation=portrait \ + --device model=SmallPhone,version=33,locale=en,orientation=portrait \ + --client-details matrixLabel="Android Emarsys SDK" + +test-android-firebase: check-env ## run Android Instrumented tests on real devices on Firebase Test Lab + @gcloud firebase test android run \ + --type instrumentation \ + --app ./sample/build/outputs/apk/androidTest/debug/sample-debug-androidTest.apk \ + --test ./$(MODULE_NAME)/build/outputs/apk/androidTest/debug/$(MODULE_NAME)-debug-androidTest.apk \ + --device model=f2q,version=30,locale=en,orientation=portrait \ + --device model=a51,version=31,locale=en,orientation=portrait \ + --device model=bluejay,version=32,locale=en,orientation=portrait \ + --device model=b4q,version=33,locale=en,orientation=portrait \ + --client-details matrixLabel="Unified SDK" + +run-github-workflow-locally: check-env ## needs act to be installed: `brew install act` and docker running. Pass in workflow path to run + @act --secret-file ./workflow.secrets -W $(WORKFLOW_PATH) --container-architecture linux/amd64 From 5f47bbd243b6b32445917557bc40508d0e6a2948 Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Thu, 22 Feb 2024 12:00:05 +0100 Subject: [PATCH 07/63] chore(pipeline): specified shell in Makefile SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> --- Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/Makefile b/Makefile index a7f7d9d0..070ecf53 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,6 @@ .PHONY: check-env help build-test create-apks prepare-ci run-github-workflow-locally test-android-firebase test-android-firebase-emulator .DEFAULT_GOAL := help +SHELL := /bin/bash ifneq (,$(wildcard .env)) include .env From ee1cfccb095b8120443b241a7ed3e8619e210b13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Thu, 22 Feb 2024 12:17:04 +0100 Subject: [PATCH 08/63] Rename .java to .kt --- .../{TimestampProviderTest.java => TimestampProviderTest.kt} | 0 .../provider/uuid/{UUIDProviderTest.java => UUIDProviderTest.kt} | 0 .../resource/{MetaDataReaderTest.java => MetaDataReaderTest.kt} | 0 ...InstrumentationTest.java => HeaderUtilsInstrumentationTest.kt} | 0 .../{SerializationUtilsTest.java => SerializationUtilsTest.kt} | 0 ...ltDeepLinkInternalTest.java => DefaultDeepLinkInternalTest.kt} | 0 ...dDisplayedIamActionTest.java => SendDisplayedIamActionTest.kt} | 0 .../{IamConversionUtilsTest.java => IamConversionUtilsTest.kt} | 0 .../{CustomEventCommandTest.java => CustomEventCommandTest.kt} | 0 ...ActionClickCommandTest.java => TrackActionClickCommandTest.kt} | 0 .../{SendDisplayedIamAction.java => SendDisplayedIamAction.kt} | 0 11 files changed, 0 insertions(+), 0 deletions(-) rename core/src/androidTest/java/com/emarsys/core/provider/timestamp/{TimestampProviderTest.java => TimestampProviderTest.kt} (100%) rename core/src/androidTest/java/com/emarsys/core/provider/uuid/{UUIDProviderTest.java => UUIDProviderTest.kt} (100%) rename core/src/androidTest/java/com/emarsys/core/resource/{MetaDataReaderTest.java => MetaDataReaderTest.kt} (100%) rename core/src/androidTest/java/com/emarsys/core/util/{HeaderUtilsInstrumentationTest.java => HeaderUtilsInstrumentationTest.kt} (100%) rename core/src/androidTest/java/com/emarsys/core/util/{SerializationUtilsTest.java => SerializationUtilsTest.kt} (100%) rename mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/{DefaultDeepLinkInternalTest.java => DefaultDeepLinkInternalTest.kt} (100%) rename mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/action/{SendDisplayedIamActionTest.java => SendDisplayedIamActionTest.kt} (100%) rename mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/{IamConversionUtilsTest.java => IamConversionUtilsTest.kt} (100%) rename mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/{CustomEventCommandTest.java => CustomEventCommandTest.kt} (100%) rename mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/{TrackActionClickCommandTest.java => TrackActionClickCommandTest.kt} (100%) rename mobile-engage/src/main/java/com/emarsys/mobileengage/iam/dialog/action/{SendDisplayedIamAction.java => SendDisplayedIamAction.kt} (100%) diff --git a/core/src/androidTest/java/com/emarsys/core/provider/timestamp/TimestampProviderTest.java b/core/src/androidTest/java/com/emarsys/core/provider/timestamp/TimestampProviderTest.kt similarity index 100% rename from core/src/androidTest/java/com/emarsys/core/provider/timestamp/TimestampProviderTest.java rename to core/src/androidTest/java/com/emarsys/core/provider/timestamp/TimestampProviderTest.kt diff --git a/core/src/androidTest/java/com/emarsys/core/provider/uuid/UUIDProviderTest.java b/core/src/androidTest/java/com/emarsys/core/provider/uuid/UUIDProviderTest.kt similarity index 100% rename from core/src/androidTest/java/com/emarsys/core/provider/uuid/UUIDProviderTest.java rename to core/src/androidTest/java/com/emarsys/core/provider/uuid/UUIDProviderTest.kt diff --git a/core/src/androidTest/java/com/emarsys/core/resource/MetaDataReaderTest.java b/core/src/androidTest/java/com/emarsys/core/resource/MetaDataReaderTest.kt similarity index 100% rename from core/src/androidTest/java/com/emarsys/core/resource/MetaDataReaderTest.java rename to core/src/androidTest/java/com/emarsys/core/resource/MetaDataReaderTest.kt diff --git a/core/src/androidTest/java/com/emarsys/core/util/HeaderUtilsInstrumentationTest.java b/core/src/androidTest/java/com/emarsys/core/util/HeaderUtilsInstrumentationTest.kt similarity index 100% rename from core/src/androidTest/java/com/emarsys/core/util/HeaderUtilsInstrumentationTest.java rename to core/src/androidTest/java/com/emarsys/core/util/HeaderUtilsInstrumentationTest.kt diff --git a/core/src/androidTest/java/com/emarsys/core/util/SerializationUtilsTest.java b/core/src/androidTest/java/com/emarsys/core/util/SerializationUtilsTest.kt similarity index 100% rename from core/src/androidTest/java/com/emarsys/core/util/SerializationUtilsTest.java rename to core/src/androidTest/java/com/emarsys/core/util/SerializationUtilsTest.kt diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternalTest.java b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternalTest.kt similarity index 100% rename from mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternalTest.java rename to mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternalTest.kt diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamActionTest.java b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamActionTest.kt similarity index 100% rename from mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamActionTest.java rename to mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamActionTest.kt diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/IamConversionUtilsTest.java b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/IamConversionUtilsTest.kt similarity index 100% rename from mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/IamConversionUtilsTest.java rename to mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/IamConversionUtilsTest.kt diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CustomEventCommandTest.java b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CustomEventCommandTest.kt similarity index 100% rename from mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CustomEventCommandTest.java rename to mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CustomEventCommandTest.kt diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackActionClickCommandTest.java b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackActionClickCommandTest.kt similarity index 100% rename from mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackActionClickCommandTest.java rename to mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackActionClickCommandTest.kt diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamAction.java b/mobile-engage/src/main/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamAction.kt similarity index 100% rename from mobile-engage/src/main/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamAction.java rename to mobile-engage/src/main/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamAction.kt From 031b6dd0556bf33390c4d1901699aaa2f16d58a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Thu, 22 Feb 2024 12:17:05 +0100 Subject: [PATCH 09/63] test(chore): move to junit5 SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> --- build.gradle.kts | 40 +- common/build.gradle.kts | 19 + .../common/feature/InnerFeatureTest.kt | 23 +- core-api/build.gradle.kts | 19 + .../java/com/emarsys/core/api/ApiTest.kt | 9 +- core/build.gradle.kts | 31 +- .../core/DefaultCoreCompletionHandlerTest.kt | 24 +- .../java/com/emarsys/core/DeviceInfoTest.kt | 24 +- .../ActivityLifecycleActionRegistryTest.kt | 19 +- .../activity/ActivityLifecycleWatchdogTest.kt | 14 +- .../activity/CurrentActivityWatchdogTest.kt | 14 +- .../com/emarsys/core/api/AsyncProxyTest.kt | 16 +- .../emarsys/core/api/LogExceptionProxyTest.kt | 26 +- .../core/app/AppLifecycleObserverTest.kt | 14 +- .../ConcurrentHandlerHolderFactoryTest.kt | 21 +- .../core/concurrency/CoreHandlerTest.kt | 22 +- .../core/connection/ConnectionProviderTest.kt | 30 +- .../core/connection/ConnectionWatchDogTest.kt | 23 +- .../ConnectivityChangeReceiverTest.kt | 19 +- ...ty_getConnectionState_ParameterizedTest.kt | 41 +- .../HardwareIdContentResolverTest.kt | 149 +++--- .../com/emarsys/core/crypto/CryptoTest.kt | 6 +- .../HardwareIdentificationCryptoTest.kt | 8 +- .../DelegatingCoreSQLiteDatabaseTest.kt | 20 +- ...abase_registerTrigger_parameterizedTest.kt | 192 ++++--- ...base_triggerRecursion_parameterizedTest.kt | 128 +++-- .../database/helper/AbstractDbHelperTest.kt | 40 +- .../core/database/helper/CoreDbHelperTest.kt | 22 +- .../AbstractSqliteRepositoryTest.kt | 30 +- .../specification/EverythingTest.kt | 20 +- .../specification/FilterByRequestIdsTest.kt | 16 +- .../QueryLatestRequestModelTest.kt | 16 +- .../core/device/LanguageProviderTest.kt | 27 +- .../endpoint/ServiceEndpointProviderTest.kt | 17 +- .../core/feature/FeatureRegistryTest.kt | 21 +- .../NotificationManagerHelperTest.kt | 16 +- .../activity/CurrentActivityProviderTest.kt | 14 +- .../hardwareid/HardwareIdProviderTest.kt | 20 +- .../provider/random/RandomProviderTest.kt | 6 +- .../timestamp/TimestampProviderTest.kt | 30 +- .../core/provider/uuid/UUIDProviderTest.kt | 26 +- .../provider/version/VersionProviderTest.kt | 16 +- .../core/request/RequestManagerDennaTest.kt | 109 ++-- .../core/request/RequestManagerOfflineTest.kt | 26 +- .../core/request/RequestManagerTest.kt | 65 ++- .../emarsys/core/request/RequestTaskTest.kt | 20 +- .../emarsys/core/request/RestClientTest.kt | 16 +- ...CompletionHandlerMiddlewareProviderTest.kt | 17 +- .../model/CompositeRequestModelTest.kt | 18 +- .../model/RequestModelRepositoryTest.kt | 66 ++- .../core/request/model/RequestModelTest.kt | 92 ++-- .../specification/FilterByUrlPatternTest.kt | 25 +- .../core/resource/MetaDataReaderTest.kt | 175 ++++--- .../response/AbstractResponseHandlerTest.kt | 19 +- .../response/ResponseHandlersProcessorTest.kt | 29 +- .../core/response/ResponseModelTest.kt | 189 +++---- .../core/shard/ShardModelRepositoryTest.kt | 33 +- .../com/emarsys/core/shard/ShardModelTest.kt | 195 +++---- .../specification/FilterByShardIdsTest.kt | 25 +- .../specification/FilterByShardTypeTest.kt | 23 +- .../core/storage/AbstractStorageTest.kt | 32 +- .../core/storage/BooleanStorageTest.kt | 25 +- .../core/storage/CoreStorageKeyTest.kt | 21 +- .../core/storage/DefaultKeyValueStoreTest.kt | 178 ++++--- .../SecureSharedPreferencesProviderTest.kt | 19 +- .../emarsys/core/storage/StringStorageTest.kt | 37 +- .../java/com/emarsys/core/util/AssertTest.kt | 89 ++-- .../com/emarsys/core/util/DatabaseUtilTest.kt | 14 +- .../core/util/ExceptionExtensionsKtTest.kt | 4 +- .../emarsys/core/util/FileDownloaderTest.kt | 64 +-- .../util/HeaderUtilsInstrumentationTest.kt | 37 +- .../com/emarsys/core/util/ImageUtilsTest.kt | 52 +- .../com/emarsys/core/util/JsonUtilsTest.kt | 451 +++++++++------- .../emarsys/core/util/MapExtensionsKtTest.kt | 4 +- .../core/util/RequestModelUtilsTest.kt | 72 +-- .../core/util/SerializationUtilsTest.kt | 78 ++- .../com/emarsys/core/util/SystemUtilsTest.kt | 11 +- .../emarsys/core/util/TimestampUtilsTest.kt | 35 +- .../util/batch/BatchingShardTriggerTest.kt | 20 +- .../core/util/batch/ListChunkerTest.kt | 62 ++- .../core/util/log/LogShardListMergerTest.kt | 119 +++-- .../com/emarsys/core/util/log/LoggerTest.kt | 35 +- .../core/util/log/entry/AppEventLogTest.kt | 13 +- .../core/util/log/entry/CrashLogTest.kt | 16 +- .../core/util/log/entry/InAppLogTest.kt | 12 +- .../core/util/log/entry/LogEntryKtTest.kt | 4 +- .../util/log/entry/MethodNotAlllowedTest.kt | 16 +- .../util/log/entry/OfflineQueueSizeTest.kt | 12 +- .../core/util/log/entry/RequestLogTest.kt | 16 +- .../core/util/log/entry/StatusLogTest.kt | 18 +- .../util/predicate/ListSizeAtLeastTest.kt | 16 +- .../core/validate/JsonObjectValidatorTest.kt | 125 ++--- .../CoreCompletionHandlerMiddlewareTest.kt | 27 +- .../emarsys/core/worker/DefaultWorkerTest.kt | 46 +- .../core/activity/CurrentActivityWatchdog.kt | 3 +- .../core/connection/ConnectionProvider.kt | 8 +- .../core/connection/ConnectionWatchDog.kt | 6 +- .../database/DelegatingCoreSQLiteDatabase.kt | 3 +- .../repository/specification/Everything.kt | 3 +- .../com/emarsys/core/device/DeviceInfo.kt | 51 +- .../core/device/HardwareIdentification.kt | 10 +- .../emarsys/core/device/LanguageProvider.java | 2 + .../provider/timestamp/TimestampProvider.java | 3 + .../core/provider/uuid/UUIDProvider.java | 3 + .../provider/version/VersionProvider.java | 2 + .../com/emarsys/core/request/RequestTask.kt | 4 +- .../request/model/CompositeRequestModel.kt | 3 +- .../core/request/model/RequestModel.kt | 19 +- .../emarsys/core/response/ResponseModel.kt | 3 +- .../com/emarsys/core/shard/ShardModel.java | 2 + .../emarsys/core/util/log/entry/RequestLog.kt | 1 + emarsys-e2e-test/build.gradle.kts | 18 + .../java/com/emarsys/EmarsysE2ETests.kt | 49 +- emarsys-firebase/build.gradle.kts | 20 +- .../EmarsysFirebaseMessagingServiceTest.kt | 25 +- ...marsysFirebaseMessagingServiceUtilsTest.kt | 13 +- .../EmarsysFirebaseMessagingServiceUtils.kt | 3 +- emarsys-huawei/build.gradle.kts | 18 + .../EmarsysHuaweiMessagingServiceTest.kt | 25 +- .../EmarsysHuaweiMessagingServiceUtilsTest.kt | 8 +- emarsys-sdk/build.gradle.kts | 18 + .../emarsys/DefaultInboxIntegrationTest.kt | 74 ++- .../java/com/emarsys/EmarsysTest.kt | 493 +++++++++--------- .../androidTest/java/com/emarsys/InAppTest.kt | 18 +- .../InappNotificationIntegrationTest.kt | 28 +- .../emarsys/MobileEngageIntegrationTest.kt | 146 +++--- ...ngageRefreshContactTokenIntegrationTest.kt | 72 ++- .../com/emarsys/PredictIntegrationTest.kt | 103 ++-- .../java/com/emarsys/PredictTest.kt | 207 +++++--- .../androidTest/java/com/emarsys/PushTest.kt | 17 +- .../emarsys/RemoteConfigIntegrationTest.kt | 36 +- .../com/emarsys/config/ConfigLoaderTest.kt | 19 +- .../java/com/emarsys/config/ConfigTest.kt | 35 +- .../com/emarsys/config/EmarsysConfigTest.kt | 20 +- .../java/com/emarsys/deeplink/DeepLinkTest.kt | 11 +- .../di/EmarsysDependencyInjectionTest.kt | 8 +- .../emarsys/eventservice/EventServiceTest.kt | 20 +- .../java/com/emarsys/geofence/GeofenceTest.kt | 16 +- .../emarsys/inapp/ui/InlineInAppViewTest.kt | 93 ++-- .../com/emarsys/inbox/MessageInboxTest.kt | 10 +- .../emarsys/mobileengage/MobileEngageTest.kt | 10 +- .../mapper/RemoteMessageMapperFactoryTest.kt | 8 +- .../oneventaction/OnEventActionTest.kt | 22 +- .../emarsys/predict/PredictRestrictedTest.kt | 16 +- ...rdwareIdentificationContentProviderTest.kt | 98 ++-- .../emarsys/testUtil/IntegrationTestUtils.kt | 2 +- .../src/main/java/com/emarsys/Emarsys.kt | 2 +- ...edHardwareIdentificationContentProvider.kt | 2 +- emarsys/build.gradle.kts | 18 + .../emarsys/EmarsysRequestModelFactoryTest.kt | 16 +- .../config/DefaultConfigInternalTest.kt | 33 +- .../config/FetchRemoteConfigActionTest.kt | 19 +- .../config/RemoteConfigResponseMapperTest.kt | 20 +- gradle.properties | 2 +- gradle/libs.versions.toml | 68 ++- mobile-engage-api/build.gradle.kts | 21 +- .../com/emarsys/mobileengage/api/MEApiTest.kt | 10 +- mobile-engage/build.gradle.kts | 20 + .../DefaultMobileEngageInternalTest.kt | 24 +- .../MobileEngageRequestContextTest.kt | 11 +- .../DefaultClientServiceInternalTest.kt | 17 +- .../deeplink/DeepLinkActionTest.kt | 16 +- .../deeplink/DefaultDeepLinkInternalTest.kt | 301 ++++++----- .../device/DeviceInfoStartActionTest.kt | 22 +- .../event/CacheableEventHandlerTest.kt | 17 +- .../event/DefaultEventServiceInternalTest.kt | 22 +- .../mobileengage/fake/FakeRequestManager.kt | 3 +- .../geofence/DefaultGeofenceInternalTest.kt | 22 +- .../geofence/FetchGeofencesActionTest.kt | 17 +- .../geofence/GeofenceFilterTest.kt | 17 +- .../GeofencePendingIntentProviderTest.kt | 6 +- .../geofence/GeofenceResponseMapperTest.kt | 16 +- .../mobileengage/iam/AppStartActionTest.kt | 16 +- .../iam/InAppEventHandlerInternalTest.kt | 24 +- .../mobileengage/iam/InAppInternalTest.kt | 17 +- .../iam/OverlayInAppPresenterTest.kt | 267 +++++----- .../mobileengage/iam/PushToInAppActionTest.kt | 24 +- .../iam/SaveDisplayedIamActionTest.kt | 16 +- .../iam/dialog/IamDialogProviderTest.kt | 44 +- .../mobileengage/iam/dialog/IamDialogTest.kt | 97 ++-- .../action/SendDisplayedIamActionTest.kt | 163 +++--- .../iam/jsbridge/IamJsBridgeFactoryTest.kt | 6 +- .../iam/jsbridge/IamJsBridgeTest.kt | 104 ++-- .../jsbridge/JSCommandFactoryProviderTest.kt | 4 +- .../iam/jsbridge/JSCommandFactoryTest.kt | 109 ++-- .../iam/model/IamConversionUtilsTest.kt | 173 +++--- .../ButtonClickedRepositoryTest.kt | 59 +-- .../DisplayedIamRepositoryTest.kt | 19 +- .../RequestRepositoryProxyTest.kt | 38 +- .../specification/FilterByCampaignIdTest.kt | 16 +- .../iam/webview/IamWebViewClientTest.kt | 19 +- .../iam/webview/IamWebViewFactoryTest.kt | 63 ++- .../iam/webview/IamWebViewTest.kt | 55 +- .../inbox/DefaultMessageInboxInternalTest.kt | 24 +- .../inbox/MessageInboxResponseMapperTest.kt | 8 +- .../notification/ActionCommandFactoryTest.kt | 19 +- ...ityCommandLifecycleCallbacksFactoryTest.kt | 4 +- ...chActivityCommandLifecycleCallbacksTest.kt | 8 +- .../NotificationCommandFactoryTest.kt | 30 +- .../command/AppEventCommandTest.kt | 17 +- .../command/CompositeCommandTest.kt | 10 +- .../command/CustomEventCommandTest.kt | 80 ++- .../command/DismissNotificationCommandTest.kt | 10 +- .../command/LaunchApplicationCommandTest.kt | 87 ++-- .../NotificationInformationCommandTest.kt | 2 +- .../command/OpenExternalUrlCommandTest.kt | 10 +- .../PreloadedInappHandlerCommandTest.kt | 18 +- ...ilentNotificationInformationCommandTest.kt | 10 +- .../command/TrackActionClickCommandTest.kt | 73 ++- .../command/TrackMessageOpenCommandTest.kt | 10 +- .../push/DefaultPushInternalTest.kt | 27 +- .../push/DefaultPushTokenProviderTest.kt | 12 +- ...ionHandlerRefreshTokenProxyProviderTest.kt | 16 +- ...eCompletionHandlerRefreshTokenProxyTest.kt | 15 +- .../MobileEngageRequestModelFactoryTest.kt | 16 +- .../mapper/ContactTokenHeaderMapperTest.kt | 19 +- .../mapper/DefaultRequestHeaderMapperTest.kt | 19 +- .../DeviceEventStateRequestMapperTest.kt | 8 +- .../mapper/MobileEngageHeaderMapperTest.kt | 19 +- .../mapper/OpenIdTokenRequestMapperTest.kt | 17 +- .../ClientInfoResponseHandlerTest.kt | 17 +- .../DeviceEventStateResponseHandlerTest.kt | 14 +- .../InAppCleanUpResponseHandlerTest.kt | 16 +- .../InAppCleanUpResponseHandlerV4Test.kt | 29 +- .../InAppMessageResponseHandlerTest.kt | 110 ++-- ...ileEngageClientStateResponseHandlerTest.kt | 19 +- .../MobileEngageTokenResponseHandlerTest.kt | 19 +- .../OnEventActionResponseHandlerTest.kt | 26 +- .../mobileengage/service/IntentUtilsTest.kt | 18 +- .../service/MessagingServiceUtilsTest.kt | 27 +- .../service/NotificationActionUtilsTest.kt | 25 +- .../service/RemoteMessageMapperV1Test.kt | 30 +- .../service/RemoteMessageMapperV2Test.kt | 28 +- .../session/MobileEngageSessionTest.kt | 6 +- .../storage/MobileEngageStorageKeyTest.kt | 20 +- .../util/RequestModelHelperTest.kt | 16 +- .../util/RequestPayloadUtilsTest.kt | 287 +++++----- .../deeplink/DefaultDeepLinkInternal.kt | 3 +- .../geofence/DefaultGeofenceInternal.kt | 3 +- .../geofence/GeofenceBroadcastReceiver.kt | 3 +- .../mobileengage/geofence/GeofenceFilter.kt | 3 +- .../geofence/GeofencePendingIntentProvider.kt | 3 +- .../geofence/GeofenceResponseMapper.kt | 3 +- .../dialog/action/SendDisplayedIamAction.kt | 59 +-- .../iam/jsbridge/JSCommandFactoryProvider.kt | 3 +- .../mobileengage/iam/model/InAppMetaData.kt | 2 - .../NotificationCommandFactory.kt | 5 +- .../ClientInfoResponseHandler.kt | 3 +- .../MobileEngageClientStateResponseHandler.kt | 3 +- .../MobileEngageTokenResponseHandler.kt | 8 +- .../service/MessagingServiceUtils.kt | 3 +- .../service/mapper/RemoteMessageMapperV1.kt | 3 +- predict-api/build.gradle.kts | 18 + .../api/model/RecommendationFilterTest.kt | 16 +- .../api/model/RecommendationLogicTest.kt | 25 +- predict/build.gradle.kts | 18 + .../predict/DefaultPredictInternalTest.kt | 45 +- .../predict/PredictResponseMapperTest.kt | 18 +- .../PredictRequestModelBuilderProviderTest.kt | 52 +- .../request/PredictHeaderFactoryTest.kt | 41 +- .../request/PredictRequestModelBuilderTest.kt | 42 +- .../response/VisitorIdResponseHandlerTest.kt | 52 +- .../predict/response/XPResponseHandlerTest.kt | 109 ++-- .../shard/PredictShardListMergerTest.kt | 118 +++-- .../predict/storage/PredictStorageKeyTest.kt | 20 +- .../emarsys/predict/util/CartItemUtilsTest.kt | 57 +- sample/build.gradle.kts | 62 ++- settings.gradle.kts | 29 +- testUtils/build.gradle.kts | 36 +- .../emarsys/testUtil/ExtensionTestUtils.kt | 18 +- .../java/com/emarsys/testUtil/RetryUtils.kt | 9 - .../com/emarsys/testUtil/mockito/ThreadSpy.kt | 2 +- .../emarsys/testUtil/rules/ConnectionRule.kt | 18 +- .../testUtil/rules/DuplicatedThreadRule.kt | 24 +- .../com/emarsys/testUtil/rules/RetryRule.kt | 32 -- 275 files changed, 5243 insertions(+), 5210 deletions(-) delete mode 100644 testUtils/src/main/java/com/emarsys/testUtil/RetryUtils.kt delete mode 100644 testUtils/src/main/java/com/emarsys/testUtil/rules/RetryRule.kt diff --git a/build.gradle.kts b/build.gradle.kts index 1dd3a02e..87d742bd 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -10,10 +10,11 @@ plugins { alias(libs.plugins.google.services) apply false // alias(libs.plugins.huawei.agconnect) apply false alias(libs.plugins.kotlin.allopen) apply false + alias(libs.plugins.kotlin.parcelize) apply false alias(libs.plugins.grgit) alias(libs.plugins.dotenv) - alias(libs.plugins.kotlin.parcelize) apply false - id("com.github.ben-manes.versions") version "0.46.0" + alias(libs.plugins.ben.manes.versions) + alias(libs.plugins.android.junit5) apply false } versionData() @@ -22,26 +23,31 @@ fun versionData() { val git = Grgit.open( mapOf("currentDir" to project.rootDir) ) - try { + val v = try { git.fetch() + if (git.describe() == null) { + throw RuntimeException("Couldn't get Version Name") + } + GitVersion( + versionName = + if (System.getenv("RELEASE_VERSION") == null) git.describe() else System.getenv( + "RELEASE_VERSION" + ), + versionCode = ((System.currentTimeMillis() - 1602845230) / 10000).toInt(), + versionCodeTime = git.head().dateTime.toEpochSecond() + ) + } catch (ignored: Exception) { + GitVersion( + versionName = "0.0.0", + versionCode = 0, + versionCodeTime = 0 + ) } - if (git.describe() == null) { - throw RuntimeException("Couldn't get Version Name") - } - val v = GitVersion( - versionName = - if (System.getenv("RELEASE_VERSION") == null) git.describe() else System.getenv( - "RELEASE_VERSION" - ), - versionCode = ((System.currentTimeMillis() - 1602845230) / 10000).toInt(), - versionCodeTime = git.head().time - ) - val version by extra(v) - println("versionName: ${v.versionName}") - println("versionCode: ${v.versionCode}") + println("versionName: ${version.versionName}") + println("versionCode: ${version.versionCode}") } tasks { diff --git a/common/build.gradle.kts b/common/build.gradle.kts index bf0b2697..838c9b10 100644 --- a/common/build.gradle.kts +++ b/common/build.gradle.kts @@ -6,12 +6,31 @@ plugins { } dependencies { implementation(project(":core-api")) + androidTestImplementation(project(":testUtils")) + + coreLibraryDesugaring(libs.android.tools.desugar) } android { namespace = "com.emarsys.common" defaultConfig { compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + + multiDexEnabled = true + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + testInstrumentationRunnerArgument( + "runnerBuilder", + "de.mannodermaus.junit5.AndroidJUnit5Builder" + ) + } + compileOptions { + isCoreLibraryDesugaringEnabled = true + } + packaging { + resources { + excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + } } } diff --git a/common/src/androidTest/java/com/emarsys/common/feature/InnerFeatureTest.kt b/common/src/androidTest/java/com/emarsys/common/feature/InnerFeatureTest.kt index 0141f9d8..71b503b8 100644 --- a/common/src/androidTest/java/com/emarsys/common/feature/InnerFeatureTest.kt +++ b/common/src/androidTest/java/com/emarsys/common/feature/InnerFeatureTest.kt @@ -1,18 +1,13 @@ package com.emarsys.common.feature -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.data.forall -import io.kotlintest.shouldBe -import io.kotlintest.tables.row -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.data.forAll +import io.kotest.data.row +import io.kotest.matchers.shouldBe +import kotlinx.coroutines.runBlocking +import org.junit.jupiter.api.Test -class InnerFeatureTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule +class InnerFeatureTest { @Test fun testValues_shouldReturnCorrectValues() { @@ -22,17 +17,15 @@ class InnerFeatureTest { } @Test - fun testGetName_shouldReturnCorrectValue() { + fun testGetName_shouldReturnCorrectValue() = runBlocking { InnerFeature.values().map { "inner_feature_${it.name.lowercase()}" }.zip(InnerFeature.values()) { stringValue, enum -> row(enum, stringValue) }.let { - forall(*it.toTypedArray()) { input, expected -> + forAll(*it.toTypedArray()) { input, expected -> input.featureName shouldBe expected } } } - - } \ No newline at end of file diff --git a/core-api/build.gradle.kts b/core-api/build.gradle.kts index 0aa78606..9913c2aa 100644 --- a/core-api/build.gradle.kts +++ b/core-api/build.gradle.kts @@ -12,12 +12,31 @@ dependencies { api(libs.androidx.lifecycle.common.java8) api(libs.androidx.lifecycle.process) api(libs.androidx.security.crypto) + androidTestImplementation(project(":testUtils")) + + coreLibraryDesugaring(libs.android.tools.desugar) } android { namespace = "com.emarsys.core.api" defaultConfig { compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + + multiDexEnabled = true + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + testInstrumentationRunnerArgument( + "runnerBuilder", + "de.mannodermaus.junit5.AndroidJUnit5Builder" + ) + } + compileOptions { + isCoreLibraryDesugaringEnabled = true + } + packaging { + resources { + excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + } } } diff --git a/core-api/src/androidTest/java/com/emarsys/core/api/ApiTest.kt b/core-api/src/androidTest/java/com/emarsys/core/api/ApiTest.kt index 0034352c..0898dd37 100644 --- a/core-api/src/androidTest/java/com/emarsys/core/api/ApiTest.kt +++ b/core-api/src/androidTest/java/com/emarsys/core/api/ApiTest.kt @@ -1,16 +1,11 @@ package com.emarsys.core.api -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.Test + class ApiTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun test() { diff --git a/core/build.gradle.kts b/core/build.gradle.kts index afb4dc27..9166561e 100644 --- a/core/build.gradle.kts +++ b/core/build.gradle.kts @@ -9,18 +9,45 @@ dependencies { implementation(project(":core-api")) implementation(libs.google.tink) implementation(libs.kotlinx.coroutines.core) + implementation(libs.androidx.activity) androidTestImplementation(project(":testUtils")) + + coreLibraryDesugaring(libs.android.tools.desugar) } android { namespace = "com.emarsys.core" - defaultConfig { - val version: GitVersion by rootProject.extra + defaultConfig { compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + + multiDexEnabled = true + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + testInstrumentationRunnerArgument( + "runnerBuilder", + "de.mannodermaus.junit5.AndroidJUnit5Builder" + ) + + val version: GitVersion by rootProject.extra buildConfigField("int", "VERSION_CODE", "${version.versionCode}") buildConfigField("String", "VERSION_NAME", "\"${version.versionName}\"") } + + buildFeatures { + buildConfig = true + } + + compileOptions { + isCoreLibraryDesugaringEnabled = true + } + + packaging { + resources { + excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + } + } } allOpen { diff --git a/core/src/androidTest/java/com/emarsys/core/DefaultCoreCompletionHandlerTest.kt b/core/src/androidTest/java/com/emarsys/core/DefaultCoreCompletionHandlerTest.kt index 14cce975..26ca2b18 100644 --- a/core/src/androidTest/java/com/emarsys/core/DefaultCoreCompletionHandlerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/DefaultCoreCompletionHandlerTest.kt @@ -4,13 +4,16 @@ import com.emarsys.core.api.ResponseErrorException import com.emarsys.core.api.result.CompletionListener import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.* +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.spy +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.verifyNoMoreInteractions class DefaultCoreCompletionHandlerTest { @@ -26,11 +29,8 @@ class DefaultCoreCompletionHandlerTest { private lateinit var coreCompletionHandler: DefaultCoreCompletionHandler private lateinit var responseErrorException: ResponseErrorException - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun init() { mockMap = mock() @@ -90,7 +90,7 @@ class DefaultCoreCompletionHandlerTest { coreCompletionHandler.onSuccess("id1", mock()) verify(listener1).onCompleted(null) - verify(listener2, times(0)) + verifyNoInteractions(listener2) } @Test diff --git a/core/src/androidTest/java/com/emarsys/core/DeviceInfoTest.kt b/core/src/androidTest/java/com/emarsys/core/DeviceInfoTest.kt index 9b0fef96..f254094b 100644 --- a/core/src/androidTest/java/com/emarsys/core/DeviceInfoTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/DeviceInfoTest.kt @@ -16,18 +16,15 @@ import com.emarsys.core.util.AndroidVersionUtils import com.emarsys.testUtil.ApplicationTestUtils.applicationDebug import com.emarsys.testUtil.ApplicationTestUtils.applicationRelease import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.matchers.boolean.shouldBeFalse -import io.kotlintest.matchers.boolean.shouldBeTrue -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe +import io.kotest.matchers.booleans.shouldBeFalse +import io.kotest.matchers.booleans.shouldBeTrue +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe import org.json.JSONObject -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.Mockito import org.mockito.kotlin.any import org.mockito.kotlin.doReturn @@ -51,11 +48,8 @@ class DeviceInfoTest { private lateinit var mockVersionProvider: VersionProvider private lateinit var mockNotificationManagerHelper: NotificationSettings - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setup() { tz = TimeZone.getTimeZone("Asia/Tokyo") TimeZone.setDefault(tz) @@ -78,7 +72,7 @@ class DeviceInfoTest { ) } - @After + @AfterEach fun teardown() { TimeZone.setDefault(null) } diff --git a/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleActionRegistryTest.kt b/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleActionRegistryTest.kt index bbb43654..3f244579 100644 --- a/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleActionRegistryTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleActionRegistryTest.kt @@ -6,10 +6,17 @@ import com.emarsys.core.activity.ActivityLifecycleAction.ActivityLifecycle.RESUM import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.provider.activity.CurrentActivityProvider -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Test -import org.mockito.kotlin.* +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.inOrder +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch class ActivityLifecycleActionRegistryTest { @@ -23,7 +30,7 @@ class ActivityLifecycleActionRegistryTest { private lateinit var mockActions: MutableList private lateinit var mockActivity: Activity - @Before + @BeforeEach fun setup() { mockActivity = mock() mockAction1 = mock { @@ -232,6 +239,7 @@ class ActivityLifecycleActionRegistryTest { fun testAddTriggerOnActivity_shouldBeDelegatedToTheCoreThread() { whenever(mockAction1.execute(any())).doAnswer { Thread.currentThread().name.startsWith("CoreSDKHandlerThread") shouldBe true + Unit } activityLifecycleActionRegistry.addTriggerOnActivityAction(mockAction1) @@ -241,6 +249,7 @@ class ActivityLifecycleActionRegistryTest { fun testActivityLifecycleActionRegistryExecute_shouldBeDelegatedToTheCoreThread() { whenever(mockAction1.execute(any())).doAnswer { Thread.currentThread().name.startsWith("CoreSDKHandlerThread") shouldBe true + Unit } activityLifecycleActionRegistry.execute(mockActivity, listOf(RESUME)) diff --git a/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleWatchdogTest.kt b/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleWatchdogTest.kt index 0195a0a1..f5ecc4cf 100644 --- a/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleWatchdogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleWatchdogTest.kt @@ -1,11 +1,10 @@ package com.emarsys.core.activity import android.app.Activity -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -14,11 +13,8 @@ class ActivityLifecycleWatchdogTest { private lateinit var mockRegistry: ActivityLifecycleActionRegistry private lateinit var mockActivity: Activity - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockRegistry = mock() mockActivity = mock() diff --git a/core/src/androidTest/java/com/emarsys/core/activity/CurrentActivityWatchdogTest.kt b/core/src/androidTest/java/com/emarsys/core/activity/CurrentActivityWatchdogTest.kt index 6b015fb0..8f5f895e 100644 --- a/core/src/androidTest/java/com/emarsys/core/activity/CurrentActivityWatchdogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/activity/CurrentActivityWatchdogTest.kt @@ -5,12 +5,9 @@ import android.os.Bundle import com.emarsys.core.provider.Property import com.emarsys.core.provider.activity.CurrentActivityProvider import com.emarsys.core.provider.activity.FallbackActivityProvider -import com.emarsys.testUtil.TimeoutUtils.timeoutRule -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -22,11 +19,8 @@ class CurrentActivityWatchdogTest { private lateinit var nextActivity: Activity private lateinit var activityProvider: Property - @Rule - @JvmField - var timeout: TestRule = timeoutRule - @Before + @BeforeEach fun setUp() { activityProvider = mock() watchdog = CurrentActivityWatchdog(activityProvider) diff --git a/core/src/androidTest/java/com/emarsys/core/api/AsyncProxyTest.kt b/core/src/androidTest/java/com/emarsys/core/api/AsyncProxyTest.kt index a80fdbca..ac6f786d 100644 --- a/core/src/androidTest/java/com/emarsys/core/api/AsyncProxyTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/api/AsyncProxyTest.kt @@ -2,13 +2,12 @@ package com.emarsys.core.api import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.ThreadSpy -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import java.util.concurrent.Callable import java.util.concurrent.CountDownLatch @@ -16,11 +15,8 @@ class AsyncProxyTest { private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() } diff --git a/core/src/androidTest/java/com/emarsys/core/api/LogExceptionProxyTest.kt b/core/src/androidTest/java/com/emarsys/core/api/LogExceptionProxyTest.kt index 96361533..33270a75 100644 --- a/core/src/androidTest/java/com/emarsys/core/api/LogExceptionProxyTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/api/LogExceptionProxyTest.kt @@ -8,26 +8,24 @@ import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.util.log.LogLevel import com.emarsys.core.util.log.Logger import com.emarsys.core.util.log.entry.CrashLog -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.* +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify import java.lang.reflect.InvocationTargetException import java.util.concurrent.CountDownLatch + class LogExceptionProxyTest { private lateinit var mockLogger: Logger private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Before + @BeforeEach fun setUp() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() mockLogger = mock() @@ -41,7 +39,7 @@ class LogExceptionProxyTest { setupCoreComponent(dependencyContainer) } - @After + @AfterEach fun tearDown() { tearDownCoreComponent() } diff --git a/core/src/androidTest/java/com/emarsys/core/app/AppLifecycleObserverTest.kt b/core/src/androidTest/java/com/emarsys/core/app/AppLifecycleObserverTest.kt index d6be66c8..b80222c0 100644 --- a/core/src/androidTest/java/com/emarsys/core/app/AppLifecycleObserverTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/app/AppLifecycleObserverTest.kt @@ -8,12 +8,11 @@ import androidx.lifecycle.LifecycleRegistry import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.session.Session -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -26,11 +25,8 @@ class AppLifecycleObserverTest { private lateinit var mockLifecycleOwner: LifecycleOwner private lateinit var uiHandler: Handler - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { uiHandler = Handler(Looper.getMainLooper()) mockSession = mock() diff --git a/core/src/androidTest/java/com/emarsys/core/concurrency/ConcurrentHandlerHolderFactoryTest.kt b/core/src/androidTest/java/com/emarsys/core/concurrency/ConcurrentHandlerHolderFactoryTest.kt index c0fc8ede..09193f6d 100644 --- a/core/src/androidTest/java/com/emarsys/core/concurrency/ConcurrentHandlerHolderFactoryTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/concurrency/ConcurrentHandlerHolderFactoryTest.kt @@ -1,28 +1,23 @@ package com.emarsys.core.concurrency import com.emarsys.core.handler.ConcurrentHandlerHolder -import com.emarsys.testUtil.TimeoutUtils.timeoutRule -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + class ConcurrentHandlerHolderFactoryTest { private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - var timeout: TestRule = timeoutRule - @Before + @BeforeEach fun setUp() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() } - @After + @AfterEach fun tearDown() { concurrentHandlerHolder.coreLooper.quit() } diff --git a/core/src/androidTest/java/com/emarsys/core/concurrency/CoreHandlerTest.kt b/core/src/androidTest/java/com/emarsys/core/concurrency/CoreHandlerTest.kt index 4eba3f84..04410470 100644 --- a/core/src/androidTest/java/com/emarsys/core/concurrency/CoreHandlerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/concurrency/CoreHandlerTest.kt @@ -1,11 +1,11 @@ package com.emarsys.core.concurrency -import com.emarsys.testUtil.TimeoutUtils.timeoutRule import android.os.HandlerThread -import io.kotlintest.shouldBe -import org.junit.* -import org.junit.rules.TestRule -import java.lang.RuntimeException +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import java.util.concurrent.CountDownLatch class CoreHandlerTest { @@ -13,11 +13,7 @@ class CoreHandlerTest { private lateinit var handlerThread: HandlerThread private lateinit var failingRunnable: Runnable - @Rule - @JvmField - var timeout: TestRule = timeoutRule - - @Before + @BeforeEach fun setUp() { val threadName = "test" handlerThread = HandlerThread(threadName) @@ -26,15 +22,15 @@ class CoreHandlerTest { failingRunnable = Runnable { throw RuntimeException("error") } } - @After + @AfterEach fun tearDown() { handlerThread.quit() } @Test fun testConstructor_innerLooper_isInitialized() { - Assert.assertNotNull(handler.looper) - Assert.assertEquals(handlerThread.name, handler.looper.thread.name) + handler.looper shouldNotBe null + handlerThread.name shouldBe handler.looper.thread.name } @Test diff --git a/core/src/androidTest/java/com/emarsys/core/connection/ConnectionProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/connection/ConnectionProviderTest.kt index 3b9d858a..04b37be0 100644 --- a/core/src/androidTest/java/com/emarsys/core/connection/ConnectionProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/connection/ConnectionProviderTest.kt @@ -1,15 +1,13 @@ package com.emarsys.core.connection import com.emarsys.core.request.model.RequestModel -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.matchers.beTheSameInstanceAs -import io.kotlintest.should -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.Mockito.`when` +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.should +import io.kotest.matchers.types.beTheSameInstanceAs +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.Mockito.mock +import org.mockito.Mockito.`when` import java.net.URL class ConnectionProviderTest { @@ -20,11 +18,8 @@ class ConnectionProviderTest { private lateinit var provider: ConnectionProvider - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { provider = ConnectionProvider() } @@ -41,13 +36,14 @@ class ConnectionProviderTest { connection.url should beTheSameInstanceAs(url) } - @Test(expected = IllegalArgumentException::class) + @Test fun testProvideConnection_shouldNotAcceptHttpRequestModel() { val url = URL(HTTP_PATH) + shouldThrow { + val requestModel = mock(RequestModel::class.java) + `when`(requestModel.url).thenReturn(url) - val requestModel = mock(RequestModel::class.java) - `when`(requestModel.url).thenReturn(url) - - provider.provideConnection(requestModel) + provider.provideConnection(requestModel) + } } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/connection/ConnectionWatchDogTest.kt b/core/src/androidTest/java/com/emarsys/core/connection/ConnectionWatchDogTest.kt index b2f231e8..dee11c25 100644 --- a/core/src/androidTest/java/com/emarsys/core/connection/ConnectionWatchDogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/connection/ConnectionWatchDogTest.kt @@ -11,28 +11,24 @@ import com.emarsys.core.worker.DefaultWorker import com.emarsys.testUtil.ConnectionTestUtils.getContextMockWithAppContextWithConnectivityManager import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.ReflectionTestUtils -import com.emarsys.testUtil.TimeoutUtils.timeoutRule +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe import io.mockk.Runs import io.mockk.every import io.mockk.just import io.mockk.mockk import io.mockk.verify -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + @SdkSuppress(minSdkVersion = Build.VERSION_CODES.P) class ConnectionWatchDogTest { private lateinit var context: Context private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - var timeout: TestRule = timeoutRule - @Before + @BeforeEach fun setup() { context = getTargetContext().applicationContext concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() @@ -43,7 +39,7 @@ class ConnectionWatchDogTest { val watchDog = ConnectionWatchDog(context, concurrentHandlerHolder) val manager: ConnectivityManager = ReflectionTestUtils.getInstanceField(watchDog, "connectivityManager")!! - Assert.assertNotNull(manager) + manager shouldNotBe null } @Test @@ -95,13 +91,14 @@ class ConnectionWatchDogTest { NetworkCapabilities.TRANSPORT_WIFI ) val watchDog = ConnectionWatchDog(contextMock, concurrentHandlerHolder) - Assert.assertTrue(watchDog.isConnected) + + watchDog.isConnected shouldBe true } @Test fun testIsConnected_Offline() { val contextMock = getContextMockWithAppContextWithConnectivityManager(false, -1) val watchDog = ConnectionWatchDog(contextMock, concurrentHandlerHolder) - Assert.assertFalse(watchDog.isConnected) + watchDog.isConnected shouldBe false } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/connection/ConnectivityChangeReceiverTest.kt b/core/src/androidTest/java/com/emarsys/core/connection/ConnectivityChangeReceiverTest.kt index 225bd813..7ef86038 100644 --- a/core/src/androidTest/java/com/emarsys/core/connection/ConnectivityChangeReceiverTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/connection/ConnectivityChangeReceiverTest.kt @@ -7,13 +7,10 @@ import androidx.test.platform.app.InstrumentationRegistry import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.fake.FakeConnectionChangeListener import com.emarsys.core.handler.ConcurrentHandlerHolder -import com.emarsys.testUtil.TimeoutUtils.timeoutRule -import io.kotlintest.shouldBe -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import java.util.concurrent.CountDownLatch @@ -22,12 +19,10 @@ class ConnectivityChangeReceiverTest { private lateinit var mockListener: ConnectionChangeListener private lateinit var context: Context - @Rule - @JvmField - var timeout: TestRule = timeoutRule + lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Before + @BeforeEach fun setup() { context = InstrumentationRegistry.getInstrumentation().targetContext concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() @@ -35,7 +30,7 @@ class ConnectivityChangeReceiverTest { mockListener = mock() } - @After + @AfterEach fun tearDown() { concurrentHandlerHolder.coreLooper.quit() } diff --git a/core/src/androidTest/java/com/emarsys/core/connection/Connectivity_getConnectionState_ParameterizedTest.kt b/core/src/androidTest/java/com/emarsys/core/connection/Connectivity_getConnectionState_ParameterizedTest.kt index 4afb96c1..d25087e5 100644 --- a/core/src/androidTest/java/com/emarsys/core/connection/Connectivity_getConnectionState_ParameterizedTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/connection/Connectivity_getConnectionState_ParameterizedTest.kt @@ -7,32 +7,33 @@ import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.testUtil.ConnectionTestUtils.getConnectivityManagerMock import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.ReflectionTestUtils.setInstanceField -import com.emarsys.testUtil.TimeoutUtils.timeoutRule -import io.kotlintest.data.forall -import io.kotlintest.shouldBe -import io.kotlintest.tables.row -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.data.forAll +import io.kotest.data.row +import io.kotest.matchers.shouldBe +import kotlinx.coroutines.runBlocking +import org.junit.jupiter.api.Test + @SdkSuppress(minSdkVersion = Build.VERSION_CODES.P) class Connectivity_getConnectionState_ParameterizedTest { - @Rule - @JvmField - var timeout: TestRule = timeoutRule + @Test - fun testGetConnectionState_connectionWatchDog() { - forall( - row(false, NetworkCapabilities.TRANSPORT_WIFI, ConnectionState.DISCONNECTED), - row(false, NetworkCapabilities.TRANSPORT_CELLULAR, ConnectionState.DISCONNECTED), - row(false, NetworkCapabilities.TRANSPORT_ETHERNET, ConnectionState.DISCONNECTED), - row(false, NetworkCapabilities.TRANSPORT_VPN, ConnectionState.DISCONNECTED), + fun testGetConnectionState_connectionWatchDog() = runBlocking { + forAll( + row(false, NetworkCapabilities.TRANSPORT_WIFI, ConnectionState.DISCONNECTED), + row(false, NetworkCapabilities.TRANSPORT_CELLULAR, ConnectionState.DISCONNECTED), + row(false, NetworkCapabilities.TRANSPORT_ETHERNET, ConnectionState.DISCONNECTED), + row(false, NetworkCapabilities.TRANSPORT_VPN, ConnectionState.DISCONNECTED), - row(true, NetworkCapabilities.TRANSPORT_WIFI, ConnectionState.CONNECTED), - row(true, NetworkCapabilities.TRANSPORT_CELLULAR, ConnectionState.CONNECTED_MOBILE_DATA), - row(true, NetworkCapabilities.TRANSPORT_ETHERNET, ConnectionState.CONNECTED), - row(true, NetworkCapabilities.TRANSPORT_VPN, ConnectionState.CONNECTED) + row(true, NetworkCapabilities.TRANSPORT_WIFI, ConnectionState.CONNECTED), + row( + true, + NetworkCapabilities.TRANSPORT_CELLULAR, + ConnectionState.CONNECTED_MOBILE_DATA + ), + row(true, NetworkCapabilities.TRANSPORT_ETHERNET, ConnectionState.CONNECTED), + row(true, NetworkCapabilities.TRANSPORT_VPN, ConnectionState.CONNECTED) ) { isConnected, connectionType, expectedConnectionState -> val connectionWatchDog = ConnectionWatchDog( getTargetContext(), ConcurrentHandlerHolderFactory.create() diff --git a/core/src/androidTest/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolverTest.kt b/core/src/androidTest/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolverTest.kt index 56ac3b74..229a8bc7 100644 --- a/core/src/androidTest/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolverTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolverTest.kt @@ -1,106 +1,125 @@ package com.emarsys.core.contentresolver.hardwareid +import android.content.Context import android.database.Cursor import android.net.Uri -import android.test.ProviderTestCase2 -import android.test.mock.MockContentProvider import com.emarsys.core.crypto.HardwareIdentificationCrypto import com.emarsys.core.database.DatabaseContract +import com.emarsys.core.device.HardwareIdentification import com.emarsys.core.provider.hardwareid.HardwareIdProviderTest -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.doReturn -import org.mockito.kotlin.mock -import org.mockito.kotlin.verify -import org.mockito.kotlin.verifyNoInteractions +import io.kotest.matchers.shouldBe +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify -class HardwareIdContentResolverTest : ProviderTestCase2(FakeContentProvider::class.java, "com.emarsys.test") { +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +class HardwareIdContentResolverTest { companion object { - private val SHARED_PACKAGE_NAMES = listOf("emarsys.test", "com.emarsys.test", "com.android.test") + private val SHARED_PACKAGE_NAMES = + listOf("emarsys.test", "com.emarsys.test", "com.android.test") private const val ENCRYPTED_HARDWARE_ID = "encrypted_shared_hardware_id" private const val SALT = "testSalt" private const val IV = "testIv" } + private var mockContext: Context = mockk() private lateinit var contentResolver: HardwareIdContentResolver private lateinit var mockHardwareIdentificationCrypto: HardwareIdentificationCrypto - - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Before - override fun setUp() { - super.setUp() - mockHardwareIdentificationCrypto = mock() - contentResolver = HardwareIdContentResolver(mockContext, mockHardwareIdentificationCrypto, SHARED_PACKAGE_NAMES) + private lateinit var mockCursor: Cursor + + @BeforeEach + fun setUp() { + mockCursor = mockk(relaxed = true) { + every { moveToFirst() } returns true + every { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_ENCRYPTED_HARDWARE_ID) } returns 0 + every { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_SALT) } returns 1 + every { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_IV) } returns 2 + every { getString(0) } returns HardwareIdProviderTest.ENCRYPTED_HARDWARE_ID + every { getString(1) } returns HardwareIdProviderTest.SALT + every { getString(2) } returns HardwareIdProviderTest.IV + } + every { + mockContext.contentResolver.query( + any(), + any(), + any(), + any(), + any() + ) + } returns mockCursor + + mockHardwareIdentificationCrypto = mockk() + every { + mockHardwareIdentificationCrypto.decrypt( + any(), + any(), + any() + ) + } returns "HARDWARE_ID" + every { mockHardwareIdentificationCrypto.encrypt(any()) } returns HardwareIdentification( + ENCRYPTED_HARDWARE_ID, + SALT, + IV + ) + contentResolver = HardwareIdContentResolver( + mockContext, + mockHardwareIdentificationCrypto, + SHARED_PACKAGE_NAMES + ) } @Test fun testProvideHardwareId_shouldGetHardwareId_fromContentResolver() { - FakeContentProvider.numberOfInvocation = 0 - contentResolver.resolveHardwareId() - verify(mockHardwareIdentificationCrypto).decrypt(ENCRYPTED_HARDWARE_ID, SALT, IV) - FakeContentProvider.numberOfInvocation shouldBe 1 + verify { mockHardwareIdentificationCrypto.decrypt(ENCRYPTED_HARDWARE_ID, SALT, IV) } } @Test fun testProvideHardwareId_shouldNotGetHardwareId_fromContentResolver() { - FakeContentProvider.numberOfInvocation = 0 - FakeContentProvider.mockCursor = mock { - on { moveToFirst() } doReturn false - on { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_ENCRYPTED_HARDWARE_ID) } doReturn 0 - on { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_SALT) } doReturn 1 - on { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_IV) } doReturn 2 - on { getString(0) } doReturn HardwareIdProviderTest.ENCRYPTED_HARDWARE_ID - on { getString(1) } doReturn HardwareIdProviderTest.SALT - on { getString(2) } doReturn HardwareIdProviderTest.IV + val mockCursor: Cursor = mockk { + every { moveToFirst() } returns false + every { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_ENCRYPTED_HARDWARE_ID) } returns 0 + every { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_SALT) } returns 1 + every { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_IV) } returns 2 + every { getString(0) } returns HardwareIdProviderTest.ENCRYPTED_HARDWARE_ID + every { getString(1) } returns HardwareIdProviderTest.SALT + every { getString(2) } returns HardwareIdProviderTest.IV } - + val mockContext: Context = mockk() + every { + mockContext.contentResolver.query( + any(), + any(), + any(), + any(), + any() + ) + } returns mockCursor + val contentResolver = HardwareIdContentResolver( + mockContext, + mockHardwareIdentificationCrypto, + SHARED_PACKAGE_NAMES + ) contentResolver.resolveHardwareId() - verifyNoInteractions(mockHardwareIdentificationCrypto) - FakeContentProvider.numberOfInvocation shouldBe 1 + verify(exactly = 0) { mockHardwareIdentificationCrypto.decrypt(any(), any(), any()) } + verify(exactly = 0) { mockHardwareIdentificationCrypto.encrypt(any()) } } @Test fun testProvideHardwareId_shouldReturnFalse_whenSharedPackageNamesIsMissing() { - FakeContentProvider.numberOfInvocation = 0 - val contentResolver = HardwareIdContentResolver(mockContext, mockHardwareIdentificationCrypto, null) + val contentResolver = + HardwareIdContentResolver(mockContext, mockHardwareIdentificationCrypto, null) val result = contentResolver.resolveHardwareId() - FakeContentProvider.numberOfInvocation = 0 - verifyNoInteractions(mockHardwareIdentificationCrypto) + verify(exactly = 0) { mockHardwareIdentificationCrypto.decrypt(any(), any(), any()) } + verify(exactly = 0) { mockHardwareIdentificationCrypto.encrypt(any()) } result shouldBe null } } - -open class FakeContentProvider : MockContentProvider() { - companion object { - var numberOfInvocation = 0 - - var mockCursor: Cursor = mock { - on { moveToFirst() } doReturn true - on { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_ENCRYPTED_HARDWARE_ID) } doReturn 0 - on { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_SALT) } doReturn 1 - on { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_IV) } doReturn 2 - on { getString(0) } doReturn HardwareIdProviderTest.ENCRYPTED_HARDWARE_ID - on { getString(1) } doReturn HardwareIdProviderTest.SALT - on { getString(2) } doReturn HardwareIdProviderTest.IV - } - } - - override fun query(uri: Uri, p1: Array?, p2: String?, p3: Array?, p4: String?): Cursor? { - numberOfInvocation++ - return mockCursor - } -} \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/crypto/CryptoTest.kt b/core/src/androidTest/java/com/emarsys/core/crypto/CryptoTest.kt index 4257c2d6..96e26bf8 100644 --- a/core/src/androidTest/java/com/emarsys/core/crypto/CryptoTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/crypto/CryptoTest.kt @@ -1,9 +1,9 @@ package com.emarsys.core.crypto import android.util.Base64 -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.Test +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.Test import java.security.KeyFactory import java.security.PublicKey import java.security.spec.X509EncodedKeySpec diff --git a/core/src/androidTest/java/com/emarsys/core/crypto/HardwareIdentificationCryptoTest.kt b/core/src/androidTest/java/com/emarsys/core/crypto/HardwareIdentificationCryptoTest.kt index 663c28c0..2788ca27 100644 --- a/core/src/androidTest/java/com/emarsys/core/crypto/HardwareIdentificationCryptoTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/crypto/HardwareIdentificationCryptoTest.kt @@ -1,9 +1,9 @@ package com.emarsys.core.crypto import com.emarsys.core.device.HardwareIdentification -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Test +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.whenever @@ -23,7 +23,7 @@ class HardwareIdentificationCryptoTest { private lateinit var hardwareIdentificationCryptoWithoutSecret: HardwareIdentificationCrypto private lateinit var mockCrypto: Crypto - @Before + @BeforeEach fun setUp() { mockCrypto = mock() diff --git a/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabaseTest.kt b/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabaseTest.kt index 53a0d1f6..6ef57c53 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabaseTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabaseTest.kt @@ -5,24 +5,22 @@ import com.emarsys.core.database.trigger.TriggerEvent import com.emarsys.core.database.trigger.TriggerKey import com.emarsys.core.database.trigger.TriggerType import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe + +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.mock class DelegatingCoreSQLiteDatabaseTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var db: DelegatingCoreSQLiteDatabase private lateinit var triggerMap: MutableMap> - @Before + @BeforeEach fun init() { val coreDbHelper = CoreDbHelper(InstrumentationRegistry.getTargetContext().applicationContext, mutableMapOf()) @@ -40,6 +38,6 @@ class DelegatingCoreSQLiteDatabaseTest { db.registerTrigger(triggerKey.tableName, triggerKey.triggerType, triggerKey.triggerEvent, mock(Runnable::class.java)) } - Assert.assertEquals(count, triggerMap[triggerKey]?.size) + triggerMap[triggerKey]?.size shouldBe count } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest.kt b/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest.kt index f44b96fe..efbe7441 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest.kt @@ -7,50 +7,26 @@ import com.emarsys.core.database.trigger.TriggerKey import com.emarsys.core.database.trigger.TriggerType import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Assert.assertEquals -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.junit.runner.RunWith -import org.junit.runners.Parameterized +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.MethodSource import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions -@RunWith(Parameterized::class) class DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Parameterized.Parameter - lateinit var tableName: String - - @Parameterized.Parameter(1) - lateinit var triggerType: TriggerType - - @Parameterized.Parameter(2) - lateinit var triggerEvent: TriggerEvent - - @Parameterized.Parameter(3) - lateinit var setup: Runnable - - @Parameterized.Parameter(4) - lateinit var trigger: Runnable - - @Parameterized.Parameter(5) - lateinit var action: Runnable - private lateinit var registeredTriggerMap: MutableMap> - @Before + @BeforeEach fun init() { DatabaseTestUtils.deleteCoreDatabase() - val coreDbHelper = CoreDbHelper(InstrumentationRegistry.getTargetContext().applicationContext, mutableMapOf()) + val coreDbHelper = CoreDbHelper( + InstrumentationRegistry.getTargetContext().applicationContext, + mutableMapOf() + ) registeredTriggerMap = mutableMapOf() db = DelegatingCoreSQLiteDatabase(coreDbHelper.writableDatabase, registeredTriggerMap) @@ -59,11 +35,19 @@ class DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest { mockRunnable = mock() } - @Test - fun testTrigger() { + @ParameterizedTest + @MethodSource("data") + fun testTrigger( + tableName: String, + triggerType: TriggerType, + triggerEvent: TriggerEvent, + setup: Runnable, + trigger: Runnable, + action: Runnable + ) { setup.run() - val unusedTriggerMap = createUnusedTriggerMap() + val unusedTriggerMap = createUnusedTriggerMap(tableName, triggerEvent) unusedTriggerMap.forEach { (key, trigger) -> db.registerTrigger(key.tableName, key.triggerType, key.triggerEvent, trigger) } @@ -75,7 +59,10 @@ class DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest { verify(mockRunnable).run() } - private fun createUnusedTriggerMap(): Map { + private fun createUnusedTriggerMap( + tableName: String, + triggerEvent: TriggerEvent + ): Map { return TriggerType.values().flatMap { type -> TriggerEvent.values().map { event -> type to event @@ -109,74 +96,73 @@ class DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest { } @JvmStatic - @Parameterized.Parameters fun data(): Collection> { return listOf( - arrayOf( - TABLE_NAME, - TriggerType.BEFORE, - TriggerEvent.INSERT, - Runnable { - - }, - Runnable { - db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { - assertEquals(0, it.count) - } - mockRunnable.run() - }, - Runnable { - db.insert(TABLE_NAME, null, contentValues) - }), - arrayOf( - TABLE_NAME, - TriggerType.AFTER, - TriggerEvent.INSERT, - Runnable { - - }, - Runnable { - db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { - assertEquals(1, it.count) - } - mockRunnable.run() - }, - Runnable { - db.insert(TABLE_NAME, null, contentValues) - }), - arrayOf( - TABLE_NAME, - TriggerType.BEFORE, - TriggerEvent.DELETE, - Runnable { - db.insert(TABLE_NAME, null, contentValues) - }, - Runnable { - db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { - assertEquals(1, it.count) - } - mockRunnable.run() - }, - Runnable { - db.delete(TABLE_NAME, null, null) - }), - arrayOf( - TABLE_NAME, - TriggerType.AFTER, - TriggerEvent.DELETE, - Runnable { - db.insert(TABLE_NAME, null, contentValues) - }, - Runnable { - db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { - assertEquals(0, it.count) - } - mockRunnable.run() - }, - Runnable { - db.delete(TABLE_NAME, null, null) - }) + arrayOf( + TABLE_NAME, + TriggerType.BEFORE, + TriggerEvent.INSERT, + Runnable { + + }, + Runnable { + db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { + it.count shouldBe 0 + } + mockRunnable.run() + }, + Runnable { + db.insert(TABLE_NAME, null, contentValues) + }), + arrayOf( + TABLE_NAME, + TriggerType.AFTER, + TriggerEvent.INSERT, + Runnable { + + }, + Runnable { + db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { + it.count shouldBe 1 + } + mockRunnable.run() + }, + Runnable { + db.insert(TABLE_NAME, null, contentValues) + }), + arrayOf( + TABLE_NAME, + TriggerType.BEFORE, + TriggerEvent.DELETE, + Runnable { + db.insert(TABLE_NAME, null, contentValues) + }, + Runnable { + db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { + it.count shouldBe 1 + } + mockRunnable.run() + }, + Runnable { + db.delete(TABLE_NAME, null, null) + }), + arrayOf( + TABLE_NAME, + TriggerType.AFTER, + TriggerEvent.DELETE, + Runnable { + db.insert(TABLE_NAME, null, contentValues) + }, + Runnable { + db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { + it.count shouldBe 0 + } + mockRunnable.run() + }, + Runnable { + db.delete(TABLE_NAME, null, null) + }) ) } } -} +} \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_triggerRecursion_parameterizedTest.kt b/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_triggerRecursion_parameterizedTest.kt index d40f5b3d..b536ad14 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_triggerRecursion_parameterizedTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_triggerRecursion_parameterizedTest.kt @@ -6,37 +6,25 @@ import com.emarsys.core.database.trigger.TriggerEvent import com.emarsys.core.database.trigger.TriggerType import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.junit.runner.RunWith -import org.junit.runners.Parameterized +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.MethodSource import org.mockito.Mockito import org.mockito.Mockito.mock -@RunWith(Parameterized::class) class DelegatingCoreSQLiteDatabase_triggerRecursion_parameterizedTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var mockRunnable: Runnable + private lateinit var db: DelegatingCoreSQLiteDatabase - @Parameterized.Parameter - lateinit var triggerType: TriggerType - - @Parameterized.Parameter(1) - lateinit var triggerEvent: TriggerEvent - - @Parameterized.Parameter(2) - lateinit var triggerAction: Runnable - - @Before + @BeforeEach fun init() { DatabaseTestUtils.deleteCoreDatabase() - val coreDbHelper = CoreDbHelper(InstrumentationRegistry.getTargetContext().applicationContext, mutableMapOf()) + val coreDbHelper = CoreDbHelper( + InstrumentationRegistry.getTargetContext().applicationContext, + mutableMapOf() + ) db = DelegatingCoreSQLiteDatabase(coreDbHelper.writableDatabase, mutableMapOf()) db.backingDatabase.execSQL(CREATE) @@ -44,8 +32,13 @@ class DelegatingCoreSQLiteDatabase_triggerRecursion_parameterizedTest { mockRunnable = mock(Runnable::class.java) } - @Test - fun testRegisterTrigger_doesNotRunInto_recursiveTriggerLoop() { + @ParameterizedTest + @MethodSource("data") + fun testRegisterTrigger_doesNotRunInto_recursiveTriggerLoop( + triggerType: TriggerType, + triggerEvent: TriggerEvent, + triggerAction: Runnable + ) { val trigger = Runnable { triggerAction.run() mockRunnable.run() @@ -64,55 +57,50 @@ class DelegatingCoreSQLiteDatabase_triggerRecursion_parameterizedTest { private const val COLUMN_2 = "column2" const val CREATE = "CREATE TABLE $TABLE_NAME ($COLUMN_1 TEXT, $COLUMN_2 INTEGER);" - private lateinit var mockRunnable: Runnable - private lateinit var db: DelegatingCoreSQLiteDatabase - private val contentValues = ContentValues().apply { put(COLUMN_1, "value") put(COLUMN_2, 1234) } + } - @JvmStatic - @Parameterized.Parameters - fun data(): Collection> { - return listOf( - arrayOf( - TriggerType.BEFORE, - TriggerEvent.INSERT, - Runnable { - db.insert(TABLE_NAME, null, contentValues) - }), - arrayOf( - TriggerType.AFTER, - TriggerEvent.INSERT, - Runnable { - db.insert(TABLE_NAME, null, contentValues) - }), - arrayOf( - TriggerType.BEFORE, - TriggerEvent.DELETE, - Runnable { - db.delete(TABLE_NAME, null, null) - }), - arrayOf( - TriggerType.AFTER, - TriggerEvent.DELETE, - Runnable { - db.delete(TABLE_NAME, null, null) - }), - arrayOf( - TriggerType.BEFORE, - TriggerEvent.UPDATE, - Runnable { - db.update(TABLE_NAME, contentValues,null, null) - }), - arrayOf( - TriggerType.AFTER, - TriggerEvent.UPDATE, - Runnable { - db.update(TABLE_NAME, contentValues,null, null) - }) - ) - } + fun data(): Collection> { + return listOf( + arrayOf( + TriggerType.BEFORE, + TriggerEvent.INSERT, + Runnable { + db.insert(TABLE_NAME, null, contentValues) + }), + arrayOf( + TriggerType.AFTER, + TriggerEvent.INSERT, + Runnable { + db.insert(TABLE_NAME, null, contentValues) + }), + arrayOf( + TriggerType.BEFORE, + TriggerEvent.DELETE, + Runnable { + db.delete(TABLE_NAME, null, null) + }), + arrayOf( + TriggerType.AFTER, + TriggerEvent.DELETE, + Runnable { + db.delete(TABLE_NAME, null, null) + }), + arrayOf( + TriggerType.BEFORE, + TriggerEvent.UPDATE, + Runnable { + db.update(TABLE_NAME, contentValues, null, null) + }), + arrayOf( + TriggerType.AFTER, + TriggerEvent.UPDATE, + Runnable { + db.update(TABLE_NAME, contentValues, null, null) + }) + ) } -} +} \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/database/helper/AbstractDbHelperTest.kt b/core/src/androidTest/java/com/emarsys/core/database/helper/AbstractDbHelperTest.kt index 43489299..41aee479 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/helper/AbstractDbHelperTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/helper/AbstractDbHelperTest.kt @@ -1,25 +1,20 @@ package com.emarsys.core.database.helper import android.content.Context -import com.emarsys.testUtil.TimeoutUtils.timeoutRule -import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext - import android.database.sqlite.SQLiteDatabase import com.emarsys.core.database.trigger.TriggerKey -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import java.lang.IllegalArgumentException -import java.util.HashMap +import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test class AbstractDbHelperTest { private class DummyDbHelper( - context: Context, - databaseName: String, - databaseVersion: Int, - triggerMap: MutableMap>) : AbstractDbHelper(context, databaseName, databaseVersion, triggerMap) { + context: Context, + databaseName: String, + databaseVersion: Int, + triggerMap: MutableMap> + ) : AbstractDbHelper(context, databaseName, databaseVersion, triggerMap) { override fun onCreate(db: SQLiteDatabase) {} override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {} } @@ -28,19 +23,16 @@ class AbstractDbHelperTest { private lateinit var dbHelper: AbstractDbHelper private lateinit var triggerMap: MutableMap> - @Rule - @JvmField - var timeout: TestRule = timeoutRule - @Before + @BeforeEach fun init() { context = getTargetContext() triggerMap = mutableMapOf() dbHelper = DummyDbHelper( - context, - "name", - 1, - triggerMap + context, + "name", + 1, + triggerMap ) } @@ -49,7 +41,7 @@ class AbstractDbHelperTest { val db = dbHelper.readableCoreDatabase val expected = dbHelper.readableDatabase val result = db.backingDatabase - Assert.assertEquals(expected, result) + result shouldBe expected } @Test @@ -57,6 +49,6 @@ class AbstractDbHelperTest { val db = dbHelper.writableCoreDatabase val expected = dbHelper.writableDatabase val result = db.backingDatabase - Assert.assertEquals(expected, result) + result shouldBe expected } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/database/helper/CoreDbHelperTest.kt b/core/src/androidTest/java/com/emarsys/core/database/helper/CoreDbHelperTest.kt index f66b9086..9922deef 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/helper/CoreDbHelperTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/helper/CoreDbHelperTest.kt @@ -4,14 +4,12 @@ import android.database.Cursor import android.database.sqlite.SQLiteDatabase import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.matchers.collections.shouldContain -import io.kotlintest.shouldBe -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.collections.shouldContain +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + class CoreDbHelperTest { @@ -19,14 +17,12 @@ class CoreDbHelperTest { const val LATEST_DB_VERSION = 5 } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var dbHelper: CoreDbHelper private lateinit var db: SQLiteDatabase - @Before + @BeforeEach fun init() { DatabaseTestUtils.deleteCoreDatabase() dbHelper = CoreDbHelper( @@ -36,7 +32,7 @@ class CoreDbHelperTest { DatabaseTestUtils.dropAllTables(db) } - @After + @AfterEach fun tearDown() { db.close() } diff --git a/core/src/androidTest/java/com/emarsys/core/database/repository/AbstractSqliteRepositoryTest.kt b/core/src/androidTest/java/com/emarsys/core/database/repository/AbstractSqliteRepositoryTest.kt index 96734168..4a0b83ed 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/repository/AbstractSqliteRepositoryTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/repository/AbstractSqliteRepositoryTest.kt @@ -22,17 +22,20 @@ import com.emarsys.core.request.model.RequestModel import com.emarsys.core.util.serialization.SerializationUtils.serializableToBlob import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.anyNotNull -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.Mockito -import org.mockito.kotlin.* -import java.util.* +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.doThrow +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever class AbstractSqliteRepositoryTest { @@ -54,11 +57,8 @@ class AbstractSqliteRepositoryTest { private lateinit var dummySpecification: SqlSpecification private lateinit var testConcurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun init() { DatabaseTestUtils.deleteCoreDatabase() @@ -66,9 +66,9 @@ class AbstractSqliteRepositoryTest { ConcurrentHandlerHolderFactory.create() dummySpecification = sqlSpecification( - DISTINCT, - COLUMNS, - SELECTION, + DISTINCT, + COLUMNS, + SELECTION, SELECTION_ARGS, GROUP_BY, HAVING, diff --git a/core/src/androidTest/java/com/emarsys/core/database/repository/specification/EverythingTest.kt b/core/src/androidTest/java/com/emarsys/core/database/repository/specification/EverythingTest.kt index 7e06c246..4d713b4c 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/repository/specification/EverythingTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/repository/specification/EverythingTest.kt @@ -7,25 +7,21 @@ import com.emarsys.core.shard.ShardModel import com.emarsys.core.shard.ShardModelRepository import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.matchers.beEmpty -import io.kotlintest.should -import io.kotlintest.shouldBe +import io.kotest.matchers.collections.beEmpty +import io.kotest.matchers.should +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + class EverythingTest { private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun init() { DatabaseTestUtils.deleteCoreDatabase() concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() diff --git a/core/src/androidTest/java/com/emarsys/core/database/repository/specification/FilterByRequestIdsTest.kt b/core/src/androidTest/java/com/emarsys/core/database/repository/specification/FilterByRequestIdsTest.kt index b0e56db7..f9a10fe5 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/repository/specification/FilterByRequestIdsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/repository/specification/FilterByRequestIdsTest.kt @@ -9,20 +9,14 @@ import com.emarsys.core.request.model.RequestModelRepository import com.emarsys.core.request.model.specification.FilterByRequestIds import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import java.util.* +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test class FilterByRequestIdsTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var repository: RequestModelRepository private lateinit var requestModel1: RequestModel @@ -30,7 +24,7 @@ class FilterByRequestIdsTest { private lateinit var requestModel3: RequestModel private lateinit var requestModel4: RequestModel - @Before + @BeforeEach fun init() { DatabaseTestUtils.deleteCoreDatabase() val timestampProvider = TimestampProvider() diff --git a/core/src/androidTest/java/com/emarsys/core/database/repository/specification/QueryLatestRequestModelTest.kt b/core/src/androidTest/java/com/emarsys/core/database/repository/specification/QueryLatestRequestModelTest.kt index 8343e159..8df447c0 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/repository/specification/QueryLatestRequestModelTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/repository/specification/QueryLatestRequestModelTest.kt @@ -9,23 +9,19 @@ import com.emarsys.core.request.model.RequestModelRepository import com.emarsys.core.request.model.specification.QueryLatestRequestModel import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + class QueryLatestRequestModelTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule private lateinit var specification: QueryLatestRequestModel - @Before + @BeforeEach fun init() { DatabaseTestUtils.deleteCoreDatabase() specification = QueryLatestRequestModel() diff --git a/core/src/androidTest/java/com/emarsys/core/device/LanguageProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/device/LanguageProviderTest.kt index a236c02f..eef063e8 100644 --- a/core/src/androidTest/java/com/emarsys/core/device/LanguageProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/device/LanguageProviderTest.kt @@ -2,30 +2,27 @@ package com.emarsys.core.device import android.os.Build.VERSION_CODES.P import androidx.test.filters.SdkSuppress -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import java.util.* +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import java.util.Locale class LanguageProviderTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule private lateinit var languageProvider: LanguageProvider - @Before + @BeforeEach fun setUp() { languageProvider = LanguageProvider() } - @Test(expected = IllegalArgumentException::class) + @Test fun testProvideLanguage_localeMustNotBeNull() { - languageProvider.provideLanguage(null) + shouldThrow { + languageProvider.provideLanguage(null) + } } @Test @@ -45,7 +42,9 @@ class LanguageProviderTest { @Test @SdkSuppress(minSdkVersion = P) fun testProvideLanguage_shouldReturnCorrectLanguageCode_whenLocaleBuilderUsed() { - val result = languageProvider.provideLanguage(Locale.Builder().setLanguage("zh").setScript("Hans").setRegion("CN").build()) + val result = languageProvider.provideLanguage( + Locale.Builder().setLanguage("zh").setScript("Hans").setRegion("CN").build() + ) result shouldBe "zh-Hans-CN" } diff --git a/core/src/androidTest/java/com/emarsys/core/endpoint/ServiceEndpointProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/endpoint/ServiceEndpointProviderTest.kt index 44423ca2..d2552161 100644 --- a/core/src/androidTest/java/com/emarsys/core/endpoint/ServiceEndpointProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/endpoint/ServiceEndpointProviderTest.kt @@ -1,13 +1,12 @@ package com.emarsys.core.endpoint import com.emarsys.core.storage.StringStorage -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito class ServiceEndpointProviderTest { @@ -16,14 +15,12 @@ class ServiceEndpointProviderTest { const val DEFAULT_ENDPOINT = "https://default.emarsys.com" } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var serviceEndpointProvider: ServiceEndpointProvider private lateinit var mockServiceUrlStorage: StringStorage - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun setUp() { mockServiceUrlStorage = Mockito.mock(StringStorage::class.java) diff --git a/core/src/androidTest/java/com/emarsys/core/feature/FeatureRegistryTest.kt b/core/src/androidTest/java/com/emarsys/core/feature/FeatureRegistryTest.kt index b1ac73ad..7b9c29ed 100644 --- a/core/src/androidTest/java/com/emarsys/core/feature/FeatureRegistryTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/feature/FeatureRegistryTest.kt @@ -1,14 +1,14 @@ package com.emarsys.core.feature import com.emarsys.core.api.experimental.FlipperFeature -import com.emarsys.testUtil.TimeoutUtils.timeoutRule -import com.emarsys.core.feature.FeatureRegistry.reset -import com.emarsys.core.feature.FeatureRegistry.isFeatureEnabled -import com.emarsys.core.feature.FeatureRegistry.enableFeature import com.emarsys.core.feature.FeatureRegistry.disableFeature -import io.kotlintest.shouldBe -import org.junit.* -import org.junit.rules.TestRule +import com.emarsys.core.feature.FeatureRegistry.enableFeature +import com.emarsys.core.feature.FeatureRegistry.isFeatureEnabled +import com.emarsys.core.feature.FeatureRegistry.reset +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.whenever @@ -18,11 +18,8 @@ class FeatureRegistryTest { private lateinit var feature3: FlipperFeature private lateinit var features: List - @Rule - @JvmField - var timeout: TestRule = timeoutRule - @Before + @BeforeEach fun setUp() { reset() feature1 = mock() @@ -34,7 +31,7 @@ class FeatureRegistryTest { features = listOf(feature1, feature2, feature3) } - @After + @AfterEach fun tearDown() { reset() } diff --git a/core/src/androidTest/java/com/emarsys/core/notification/NotificationManagerHelperTest.kt b/core/src/androidTest/java/com/emarsys/core/notification/NotificationManagerHelperTest.kt index 1cedaf7f..763fca20 100644 --- a/core/src/androidTest/java/com/emarsys/core/notification/NotificationManagerHelperTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/notification/NotificationManagerHelperTest.kt @@ -1,13 +1,12 @@ package com.emarsys.core.notification import com.emarsys.core.api.notification.ChannelSettings -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.mock class NotificationManagerHelperTest { @@ -21,11 +20,8 @@ class NotificationManagerHelperTest { private lateinit var mockNotificationManagerProxy: NotificationManagerProxy private lateinit var notificationManagerHelper: NotificationManagerHelper - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockNotificationManagerProxy = mock(NotificationManagerProxy::class.java) notificationManagerHelper = NotificationManagerHelper(mockNotificationManagerProxy) diff --git a/core/src/androidTest/java/com/emarsys/core/provider/activity/CurrentActivityProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/provider/activity/CurrentActivityProviderTest.kt index 9c532947..69cac77f 100644 --- a/core/src/androidTest/java/com/emarsys/core/provider/activity/CurrentActivityProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/provider/activity/CurrentActivityProviderTest.kt @@ -1,12 +1,9 @@ package com.emarsys.core.provider.activity import android.app.Activity -import com.emarsys.testUtil.TimeoutUtils.timeoutRule -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import java.lang.ref.WeakReference @@ -20,11 +17,8 @@ class CurrentActivityProviderTest { val activity2: Activity = mock() } - @Rule - @JvmField - var timeout: TestRule = timeoutRule - @Before + @BeforeEach fun setUp() { mockFallbackActivityProvider = mock() provider = CurrentActivityProvider(WeakReference(null), mockFallbackActivityProvider) diff --git a/core/src/androidTest/java/com/emarsys/core/provider/hardwareid/HardwareIdProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/provider/hardwareid/HardwareIdProviderTest.kt index b7b8ae1e..51ec2f98 100644 --- a/core/src/androidTest/java/com/emarsys/core/provider/hardwareid/HardwareIdProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/provider/hardwareid/HardwareIdProviderTest.kt @@ -7,15 +7,16 @@ import com.emarsys.core.database.repository.SqlSpecification import com.emarsys.core.device.HardwareIdentification import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.storage.Storage -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.* +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions class HardwareIdProviderTest { @@ -45,11 +46,8 @@ class HardwareIdProviderTest { private lateinit var mockUUIDProvider: UUIDProvider private lateinit var mockRepository: Repository - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockStorage = mock() mockUUIDProvider = mock { diff --git a/core/src/androidTest/java/com/emarsys/core/provider/random/RandomProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/provider/random/RandomProviderTest.kt index 17e0fc65..5590774b 100644 --- a/core/src/androidTest/java/com/emarsys/core/provider/random/RandomProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/provider/random/RandomProviderTest.kt @@ -1,8 +1,8 @@ package com.emarsys.core.provider.random -import io.kotlintest.matchers.doubles.shouldBeGreaterThanOrEqual -import io.kotlintest.matchers.doubles.shouldBeLessThanOrEqual -import org.junit.Test +import io.kotest.matchers.doubles.shouldBeGreaterThanOrEqual +import io.kotest.matchers.doubles.shouldBeLessThanOrEqual +import org.junit.jupiter.api.Test class RandomProviderTest { diff --git a/core/src/androidTest/java/com/emarsys/core/provider/timestamp/TimestampProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/provider/timestamp/TimestampProviderTest.kt index 31675b3a..ecf4470d 100644 --- a/core/src/androidTest/java/com/emarsys/core/provider/timestamp/TimestampProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/provider/timestamp/TimestampProviderTest.kt @@ -1,25 +1,15 @@ -package com.emarsys.core.provider.timestamp; +package com.emarsys.core.provider.timestamp -import com.emarsys.testUtil.TimeoutUtils; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; - -public class TimestampProviderTest { - - @Rule - public TestRule timeout = TimeoutUtils.getTimeoutRule(); +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.Test +class TimestampProviderTest { @Test - public void testProvideTimestamp_returnsTheCurrentTimestamp() { - long before = System.currentTimeMillis(); - long actual = new TimestampProvider().provideTimestamp(); - long after = System.currentTimeMillis(); - - Assert.assertTrue(before <= actual); - Assert.assertTrue(actual <= after); + fun testProvideTimestamp_returnsTheCurrentTimestamp() { + val before = System.currentTimeMillis() + val actual = TimestampProvider().provideTimestamp() + val after = System.currentTimeMillis() + (before <= actual) shouldBe true + (actual <= after) shouldBe true } - } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/provider/uuid/UUIDProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/provider/uuid/UUIDProviderTest.kt index addbe9a2..0b93cc6f 100644 --- a/core/src/androidTest/java/com/emarsys/core/provider/uuid/UUIDProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/provider/uuid/UUIDProviderTest.kt @@ -1,24 +1,12 @@ -package com.emarsys.core.provider.uuid; - -import static org.junit.Assert.assertNotNull; - -import com.emarsys.testUtil.TimeoutUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; - - -public class UUIDProviderTest { - - @Rule - public TestRule timeout = TimeoutUtils.getTimeoutRule(); +package com.emarsys.core.provider.uuid +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.Test +class UUIDProviderTest { @Test - public void testProvideId_returnsNotNullId() { - UUIDProvider provider = new UUIDProvider(); - assertNotNull(provider.provideId()); + fun testProvideId_returnsNotNullId() { + val provider = UUIDProvider() + provider.provideId() shouldNotBe null } - } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/provider/version/VersionProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/provider/version/VersionProviderTest.kt index cf002694..9d6a7b50 100644 --- a/core/src/androidTest/java/com/emarsys/core/provider/version/VersionProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/provider/version/VersionProviderTest.kt @@ -1,21 +1,17 @@ package com.emarsys.core.provider.version -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + class VersionProviderTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule private lateinit var versionProvider: VersionProvider - @Before + @BeforeEach fun setUp() { versionProvider = VersionProvider() } diff --git a/core/src/androidTest/java/com/emarsys/core/request/RequestManagerDennaTest.kt b/core/src/androidTest/java/com/emarsys/core/request/RequestManagerDennaTest.kt index 2c2eecb4..1d5f45d0 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/RequestManagerDennaTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/RequestManagerDennaTest.kt @@ -23,14 +23,11 @@ import com.emarsys.testUtil.ConnectionTestUtils.checkConnection import com.emarsys.testUtil.DatabaseTestUtils.deleteCoreDatabase import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.TestUrls.DENNA_ECHO -import com.emarsys.testUtil.TimeoutUtils.timeoutRule +import io.kotest.matchers.shouldBe import org.json.JSONObject -import org.junit.After -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer import org.mockito.kotlin.mock @@ -48,13 +45,10 @@ class RequestManagerDennaTest { private lateinit var uuidProvider: UUIDProvider private lateinit var coreCompletionHandlerMiddlewareProvider: CoreCompletionHandlerMiddlewareProvider - @Rule - @JvmField - var timeout: TestRule = timeoutRule private lateinit var mockRequestModelMapper: Mapper - @Before + @BeforeEach fun init() { deleteCoreDatabase() val requestModelMappers: MutableList> = mutableListOf() @@ -115,7 +109,7 @@ class RequestManagerDennaTest { headers["Header2"] = "value2" } - @After + @AfterEach fun tearDown() { concurrentHandlerHolder.coreLooper.quit() } @@ -130,18 +124,19 @@ class RequestManagerDennaTest { manager.submit(model, null) latch.await() - Assert.assertEquals(null, fakeCompletionHandler.exception) - Assert.assertEquals(0, fakeCompletionHandler.onErrorCount.toLong()) - Assert.assertEquals(1, fakeCompletionHandler.onSuccessCount.toLong()) - Assert.assertEquals(200, fakeCompletionHandler.successResponseModel.statusCode.toLong()) + fakeCompletionHandler.exception shouldBe null + fakeCompletionHandler.onErrorCount.toLong() shouldBe 0 + fakeCompletionHandler.onSuccessCount.toLong() shouldBe 1 + fakeCompletionHandler.successResponseModel.statusCode.toLong() shouldBe 200 val responseJson = JSONObject(fakeCompletionHandler.successResponseModel.body!!) val headers = responseJson["headers"] as JSONObject - Assert.assertEquals("value1", headers["Header1".lowercase()]) - Assert.assertEquals("value2", headers["Header2".lowercase()]) - Assert.assertEquals("application/json", headers["Accept".lowercase()]) - Assert.assertEquals("application/x-www-form-urlencoded", headers["Content".lowercase()]) - Assert.assertEquals("GET", responseJson["method"]) - Assert.assertFalse(responseJson.has("body")) + headers["Header1".lowercase()] shouldBe "value1" + headers["Header2".lowercase()] shouldBe "value2" + headers["Accept".lowercase()] shouldBe "application/json" + headers["Content".lowercase()] shouldBe "application/x-www-form-urlencoded" + responseJson["method"] shouldBe "GET" + + responseJson.has("body") shouldBe false } @Test @@ -163,25 +158,25 @@ class RequestManagerDennaTest { manager.submit(model, null) latch.await() - Assert.assertEquals(null, fakeCompletionHandler.exception) - Assert.assertEquals(0, fakeCompletionHandler.onErrorCount.toLong()) - Assert.assertEquals(1, fakeCompletionHandler.onSuccessCount.toLong()) - Assert.assertEquals(200, fakeCompletionHandler.successResponseModel.statusCode.toLong()) + fakeCompletionHandler.exception shouldBe null + fakeCompletionHandler.onErrorCount.toLong() shouldBe 0 + fakeCompletionHandler.onSuccessCount.toLong() shouldBe 1 + fakeCompletionHandler.successResponseModel.statusCode.toLong() shouldBe 200 val responseJson = JSONObject(fakeCompletionHandler.successResponseModel.body!!) val headers = responseJson.getJSONObject("headers") val body = responseJson.getJSONObject("body") - Assert.assertEquals("value1", headers["Header1".lowercase()]) - Assert.assertEquals("value2", headers["Header2".lowercase()]) - Assert.assertEquals("application/json", headers["Accept".lowercase()]) - Assert.assertEquals("application/x-www-form-urlencoded", headers["Content".lowercase()]) - Assert.assertEquals("POST", responseJson["method"]) - Assert.assertEquals("val1", body["key1"]) - Assert.assertEquals("val2", body["key2"]) - Assert.assertEquals("val3", body["key3"]) - Assert.assertEquals(4, body["key4"]) + headers["Header1".lowercase()] shouldBe "value1" + headers["Header2".lowercase()] shouldBe "value2" + headers["Accept".lowercase()] shouldBe "application/json" + headers["Content".lowercase()] shouldBe "application/x-www-form-urlencoded" + responseJson["method"] shouldBe "POST" + body["key1"] shouldBe "val1" + body["key2"] shouldBe "val2" + body["key3"] shouldBe "val3" + body["key4"] shouldBe 4 val soDeepJson = body.getJSONObject("deepKey") - Assert.assertEquals("deepValue1", soDeepJson.getString("deep1")) - Assert.assertEquals("deepValue2", soDeepJson.getString("deep2")) + soDeepJson.getString("deep1") shouldBe "deepValue1" + soDeepJson.getString("deep2") shouldBe "deepValue2" } @Test @@ -192,18 +187,18 @@ class RequestManagerDennaTest { ).build() manager.submit(model, null) latch.await() - Assert.assertEquals(null, fakeCompletionHandler.exception) - Assert.assertEquals(0, fakeCompletionHandler.onErrorCount.toLong()) - Assert.assertEquals(1, fakeCompletionHandler.onSuccessCount.toLong()) - Assert.assertEquals(200, fakeCompletionHandler.successResponseModel.statusCode.toLong()) + fakeCompletionHandler.exception shouldBe null + fakeCompletionHandler.onErrorCount.toLong() shouldBe 0 + fakeCompletionHandler.onSuccessCount.toLong() shouldBe 1 + fakeCompletionHandler.successResponseModel.statusCode.toLong() shouldBe 200 val responseJson = JSONObject(fakeCompletionHandler.successResponseModel!!.body!!) val headers = responseJson.getJSONObject("headers") - Assert.assertEquals("value1", headers["Header1".lowercase()]) - Assert.assertEquals("value2", headers["Header2".lowercase()]) - Assert.assertEquals("application/json", headers["Accept".lowercase()]) - Assert.assertEquals("application/x-www-form-urlencoded", headers["Content".lowercase()]) - Assert.assertEquals("PUT", responseJson["method"]) - Assert.assertFalse(responseJson.has("body")) + headers["Header1".lowercase()] shouldBe "value1" + headers["Header2".lowercase()] shouldBe "value2" + headers["Accept".lowercase()] shouldBe "application/json" + headers["Content".lowercase()] shouldBe "application/x-www-form-urlencoded" + responseJson["method"] shouldBe "PUT" + responseJson.has("body") shouldBe false } @Test @@ -214,17 +209,17 @@ class RequestManagerDennaTest { ).build() manager.submit(model, null) latch.await() - Assert.assertEquals(null, fakeCompletionHandler.exception) - Assert.assertEquals(0, fakeCompletionHandler.onErrorCount.toLong()) - Assert.assertEquals(1, fakeCompletionHandler.onSuccessCount.toLong()) - Assert.assertEquals(200, fakeCompletionHandler.successResponseModel.statusCode.toLong()) + fakeCompletionHandler.exception shouldBe null + fakeCompletionHandler.onErrorCount.toLong() shouldBe 0 + fakeCompletionHandler.onSuccessCount.toLong() shouldBe 1 + fakeCompletionHandler.successResponseModel.statusCode.toLong() shouldBe 200 val responseJson = JSONObject(fakeCompletionHandler.successResponseModel!!.body!!) val headers = responseJson.getJSONObject("headers") - Assert.assertEquals("value1", headers["Header1".lowercase()]) - Assert.assertEquals("value2", headers["Header2".lowercase()]) - Assert.assertEquals("application/json", headers["Accept".lowercase()]) - Assert.assertEquals("application/x-www-form-urlencoded", headers["Content".lowercase()]) - Assert.assertEquals("DELETE", responseJson["method"]) - Assert.assertFalse(responseJson.has("body")) + headers["Header1".lowercase()] shouldBe "value1" + headers["Header2".lowercase()] shouldBe "value2" + headers["Accept".lowercase()] shouldBe "application/json" + headers["Content".lowercase()] shouldBe "application/x-www-form-urlencoded" + responseJson["method"] shouldBe "DELETE" + responseJson.has("body") shouldBe false } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/request/RequestManagerOfflineTest.kt b/core/src/androidTest/java/com/emarsys/core/request/RequestManagerOfflineTest.kt index 5274c36e..5070cb5b 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/RequestManagerOfflineTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/RequestManagerOfflineTest.kt @@ -24,17 +24,13 @@ import com.emarsys.core.worker.DefaultWorker import com.emarsys.core.worker.Worker import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.be -import io.kotlintest.matchers.beEmpty -import io.kotlintest.should -import io.kotlintest.shouldBe +import io.kotest.matchers.collections.beEmpty +import io.kotest.matchers.should +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import java.io.IOException import java.util.concurrent.CountDownLatch @@ -44,9 +40,7 @@ class RequestManagerOfflineTest { const val URL = "https://www.emarsys.com/" } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var connectionStates: Array private lateinit var requestResults: Array @@ -66,7 +60,7 @@ class RequestManagerOfflineTest { private lateinit var coreCompletionHandlerMiddlewareProvider: CoreCompletionHandlerMiddlewareProvider private lateinit var mockProxyProvider: CompletionHandlerProxyProvider - @Before + @BeforeEach fun setup() { watchDogCountDown = 0 completionHandlerCountDown = 0 @@ -76,7 +70,7 @@ class RequestManagerOfflineTest { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() } - @After + @AfterEach fun tearDown() { concurrentHandlerHolder.coreLooper.quit() concurrentHandlerHolder.networkLooper.quit() @@ -227,7 +221,7 @@ class RequestManagerOfflineTest { requestRepository.remove(FilterByRequestIds(arrayOf(lastNormal.id))) } - requestRepository.query(Everything()).size should be(1) + requestRepository.query(Everything()).size shouldBe 1 } @Suppress("UNCHECKED_CAST") diff --git a/core/src/androidTest/java/com/emarsys/core/request/RequestManagerTest.kt b/core/src/androidTest/java/com/emarsys/core/request/RequestManagerTest.kt index 6a81909a..57e5072f 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/RequestManagerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/RequestManagerTest.kt @@ -26,16 +26,18 @@ import com.emarsys.testUtil.ConnectionTestUtils.checkConnection import com.emarsys.testUtil.DatabaseTestUtils.deleteCoreDatabase import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.ReflectionTestUtils -import com.emarsys.testUtil.RetryUtils.retryRule import com.emarsys.testUtil.TestUrls.DENNA_ECHO import com.emarsys.testUtil.TestUrls.customResponse -import com.emarsys.testUtil.TimeoutUtils.timeoutRule import com.emarsys.testUtil.mockito.ThreadSpy +import io.kotest.matchers.shouldBe import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext -import org.junit.* -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +import org.junitpioneer.jupiter.RetryingTest import org.mockito.kotlin.* import java.net.UnknownHostException import java.util.concurrent.CountDownLatch @@ -64,15 +66,8 @@ class RequestManagerTest { private lateinit var callbackRegistryThreadSpy: ThreadSpy> private lateinit var shardRepositoryThreadSpy: ThreadSpy> - @Rule - @JvmField - var timeout: TestRule = timeoutRule - - @Rule - @JvmField - var retry: TestRule = retryRule - @Before + @BeforeEach fun setUp() { deleteCoreDatabase() val requestModelMappers: MutableList> = mutableListOf() @@ -160,12 +155,13 @@ class RequestManagerTest { ) } - @After + @AfterEach fun tearDown() { concurrentHandlerHolder.coreLooper.quit() } @Test + @RetryingTest(3) fun testSubmit_shouldAddRequestModelToQueue() { manager.submit( requestModel, @@ -177,6 +173,7 @@ class RequestManagerTest { } @Test + @RetryingTest(3) fun testSubmit_withRequestModel_shouldInvokeRunOnTheWorker() { val worker = mock() ReflectionTestUtils.setInstanceField(manager, "worker", worker) @@ -188,6 +185,7 @@ class RequestManagerTest { } @Test + @RetryingTest(3) fun testSubmit_withRequestModel_executesRunnableOn_CoreSDKHandlerThread() { runBlocking { withContext(Dispatchers.IO) { @@ -199,6 +197,7 @@ class RequestManagerTest { } @Test + @RetryingTest(3) fun testSubmit_withRequestModel_Success() { whenever(mockConnectionWatchDog.isConnected).thenReturn(true, false) whenever(mockRequestRepository.isEmpty()).thenReturn(false, false, true) @@ -207,12 +206,14 @@ class RequestManagerTest { ).thenReturn(listOf(requestModel), emptyList()) manager.submit(requestModel, null) completionHandlerLatch.await() - Assert.assertEquals(requestModel.id, fakeCompletionHandler.successId) - Assert.assertEquals(1, fakeCompletionHandler.onSuccessCount.toLong()) - Assert.assertEquals(0, fakeCompletionHandler.onErrorCount.toLong()) + + fakeCompletionHandler.successId shouldBe requestModel.id + fakeCompletionHandler.onSuccessCount.toLong() shouldBe 1 + fakeCompletionHandler.onErrorCount shouldBe 0 } @Test + @RetryingTest(3) fun testSubmit_withRequestModel_shouldRegisterCallbackToRegistry() { val completionListener = mock() @@ -222,6 +223,7 @@ class RequestManagerTest { } @Test + @RetryingTest(3) fun testSubmit_withRequestModel_shouldRegister_null_ToRegistryAsWell() { manager.submit(requestModel, null) @@ -230,6 +232,7 @@ class RequestManagerTest { @Test + @RetryingTest(3) fun testSubmitNow_withoutCompletionHandler_shouldCallProxyProviderForCompletionHandler() { whenever(mockDelegatorCompletionHandlerProvider.provide(any(), any())).doReturn( mockDefaultHandler @@ -245,6 +248,7 @@ class RequestManagerTest { } @Test + @RetryingTest(3) fun testSubmitNow_shouldCallProxyProviderForCompletionHandler() { manager.submitNow(requestModel, fakeCompletionHandler) verify(mockDelegatorCompletionHandlerProvider).provide( @@ -256,6 +260,7 @@ class RequestManagerTest { } @Test + @RetryingTest(3) fun testSubmitNow_shouldCallProxyProviderForCompletionHandler_withScope() { val mockOtherHandler: Handler = mock() manager.submitNow(requestModel, fakeCompletionHandler, mockOtherHandler) @@ -268,12 +273,14 @@ class RequestManagerTest { } @Test + @RetryingTest(3) fun testSubmitNow_shouldCallRestClientsExecuteWithGivenParameters() { manager.submitNow(requestModel, fakeCompletionHandler) verify(mockRestClient).execute(requestModel, mockDefaultHandler) } @Test + @RetryingTest(3) fun testSubmitNow_shouldCallRestClient_withDefaultHandler() { manager.submitNow(requestModel) @@ -281,6 +288,7 @@ class RequestManagerTest { } @Test + @RetryingTest(3) fun testError_callbackWithResponseContainsRequestModel() { requestModel = RequestModel.Builder(timestampProvider, uuidProvider).url(customResponse(405)) @@ -292,13 +300,15 @@ class RequestManagerTest { ).thenReturn(listOf(requestModel), emptyList()) manager.submit(requestModel, null) completionHandlerLatch.await() - Assert.assertEquals(requestModel.id, fakeCompletionHandler.errorId) - Assert.assertEquals(0, fakeCompletionHandler.onSuccessCount.toLong()) - Assert.assertEquals(1, fakeCompletionHandler.onErrorCount.toLong()) - Assert.assertEquals(405, fakeCompletionHandler.failureResponseModel.statusCode.toLong()) + + fakeCompletionHandler.errorId shouldBe requestModel.id + fakeCompletionHandler.onSuccessCount.toLong() shouldBe 0 + fakeCompletionHandler.onErrorCount shouldBe 1 + fakeCompletionHandler.failureResponseModel.statusCode.toLong() shouldBe 405 } @Test + @RetryingTest(3) fun testError_withRequestModel_callbackWithException() { requestModel = RequestModel.Builder(timestampProvider, uuidProvider) .url("https://www.nosuchwebsite.emarsys.com").method(RequestMethod.GET).build() @@ -307,16 +317,16 @@ class RequestManagerTest { whenever(mockRequestRepository.query(any())).thenReturn(listOf(requestModel), emptyList()) manager.submit(requestModel, null) completionHandlerLatch.await() - Assert.assertEquals(requestModel.id, fakeCompletionHandler.errorId) - Assert.assertEquals(0, fakeCompletionHandler.onSuccessCount.toLong()) - Assert.assertEquals(1, fakeCompletionHandler.onErrorCount.toLong()) - Assert.assertEquals( - (UnknownHostException() as Exception).javaClass, - fakeCompletionHandler.exception.javaClass - ) + + fakeCompletionHandler.errorId shouldBe requestModel.id + fakeCompletionHandler.onSuccessCount.toLong() shouldBe 0 + fakeCompletionHandler.onErrorCount shouldBe 1 + fakeCompletionHandler.exception.javaClass shouldBe UnknownHostException().javaClass + } @Test + @RetryingTest(3) fun testSubmit_shouldAddShardModelToDatabase() { manager.submit(shardModel) runBlocking { @@ -325,6 +335,7 @@ class RequestManagerTest { } @Test + @RetryingTest(3) fun testSubmit_withShardModel_executesRunnableOn_CoreSDKHandlerThread() { runBlocking { withContext(Dispatchers.IO) { diff --git a/core/src/androidTest/java/com/emarsys/core/request/RequestTaskTest.kt b/core/src/androidTest/java/com/emarsys/core/request/RequestTaskTest.kt index 49bd8826..aea3e1ed 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/RequestTaskTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/RequestTaskTest.kt @@ -3,12 +3,12 @@ package com.emarsys.core.request import com.emarsys.core.connection.ConnectionProvider import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.request.model.RequestModel -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule + +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.fail + import org.mockito.kotlin.doReturn import org.mockito.kotlin.doThrow import org.mockito.kotlin.mock @@ -20,9 +20,7 @@ class RequestTaskTest { private lateinit var connectionProvider: ConnectionProvider private lateinit var mockTimestampProvider: TimestampProvider - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + companion object { private const val WRONG_URL = "https://localhost/missing" @@ -30,7 +28,7 @@ class RequestTaskTest { private const val TIMESTAMP_2: Long = 1600 } - @Before + @BeforeEach fun setUp() { connectionProvider = ConnectionProvider() mockTimestampProvider = mock() @@ -55,7 +53,7 @@ class RequestTaskTest { try { requestTask.execute() } catch (e: Exception) { - Assert.fail("Request Task should handle exception: " + e.message) + fail("Request Task should handle exception: " + e.message) } } diff --git a/core/src/androidTest/java/com/emarsys/core/request/RestClientTest.kt b/core/src/androidTest/java/com/emarsys/core/request/RestClientTest.kt index 4de69558..d867ab27 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/RestClientTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/RestClientTest.kt @@ -16,13 +16,12 @@ import com.emarsys.core.testUtil.RequestModelTestUtils import com.emarsys.testUtil.ConnectionTestUtils import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.TestUrls -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -42,12 +41,9 @@ class RestClientTest { private lateinit var requestModelMappers: List> private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Suppress("UNCHECKED_CAST") - @Before + @BeforeEach fun setup() { ConnectionTestUtils.checkConnection(InstrumentationRegistry.getTargetContext()) diff --git a/core/src/androidTest/java/com/emarsys/core/request/factory/CoreCompletionHandlerMiddlewareProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/request/factory/CoreCompletionHandlerMiddlewareProviderTest.kt index 46256597..579edf94 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/factory/CoreCompletionHandlerMiddlewareProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/factory/CoreCompletionHandlerMiddlewareProviderTest.kt @@ -9,14 +9,11 @@ import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel import com.emarsys.core.worker.CoreCompletionHandlerMiddleware import com.emarsys.core.worker.Worker -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.matchers.beInstanceOf -import io.kotlintest.should -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.should +import io.kotest.matchers.types.beInstanceOf +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.eq import org.mockito.kotlin.mock @@ -25,9 +22,7 @@ import java.util.concurrent.CountDownLatch class CoreCompletionHandlerMiddlewareProviderTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var mockRequestRepository: Repository private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder @@ -39,7 +34,7 @@ class CoreCompletionHandlerMiddlewareProviderTest { private lateinit var latch: CountDownLatch private lateinit var runnableFactory: RunnableFactory - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun setUp() { latch = CountDownLatch(1) diff --git a/core/src/androidTest/java/com/emarsys/core/request/model/CompositeRequestModelTest.kt b/core/src/androidTest/java/com/emarsys/core/request/model/CompositeRequestModelTest.kt index 49f36302..46451e05 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/model/CompositeRequestModelTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/model/CompositeRequestModelTest.kt @@ -2,15 +2,11 @@ package com.emarsys.core.request.model import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import java.net.URL -import java.util.* class CompositeRequestModelTest { @@ -23,16 +19,14 @@ class CompositeRequestModelTest { val ORIGINAL_IDS = arrayOf("uuid") } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var timestampProvider: TimestampProvider private lateinit var uuidProvider: UUIDProvider private lateinit var payload: Map private lateinit var headers: Map - @Before + @BeforeEach fun setUp() { payload = createPayload() headers = createHeaders() diff --git a/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelRepositoryTest.kt b/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelRepositoryTest.kt index af00b321..8fc2b1d7 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelRepositoryTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelRepositoryTest.kt @@ -18,20 +18,17 @@ import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.util.serialization.SerializationUtils import com.emarsys.testUtil.DatabaseTestUtils.deleteCoreDatabase import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext -import com.emarsys.testUtil.TimeoutUtils.timeoutRule +import com.emarsys.testUtil.mockito.whenever +import io.kotest.matchers.shouldBe import org.json.JSONException -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.Mockito import java.util.* class RequestModelRepositoryTest { - @Rule - @JvmField - var timeout: TestRule = timeoutRule + companion object { private const val URL_EMARSYS = "https://www.emarsys.com" @@ -52,7 +49,7 @@ class RequestModelRepositoryTest { private var headers: HashMap? = null private var payload: HashMap? = null - @Before + @BeforeEach fun init() { deleteCoreDatabase() context = getTargetContext() @@ -72,45 +69,46 @@ class RequestModelRepositoryTest { @Test fun testContentValuesFromItem() { val result = repository!!.contentValuesFromItem(request) - Assert.assertEquals(request!!.id, result.getAsString(REQUEST_COLUMN_NAME_REQUEST_ID)) - Assert.assertEquals(request!!.method.name, result.getAsString(REQUEST_COLUMN_NAME_METHOD)) - Assert.assertEquals(request!!.url.toString(), result.getAsString(REQUEST_COLUMN_NAME_URL)) - Assert.assertArrayEquals( + result.getAsString(REQUEST_COLUMN_NAME_REQUEST_ID) shouldBe request!!.id + result.getAsString(REQUEST_COLUMN_NAME_METHOD) shouldBe request!!.method.name + result.getAsString(REQUEST_COLUMN_NAME_URL) shouldBe request!!.url.toString() + Assertions.assertArrayEquals( SerializationUtils.serializableToBlob( request!!.headers ), result.getAsByteArray(REQUEST_COLUMN_NAME_HEADERS) ) - Assert.assertArrayEquals( + Assertions.assertArrayEquals( SerializationUtils.serializableToBlob( request!!.payload ), result.getAsByteArray(REQUEST_COLUMN_NAME_PAYLOAD) ) - Assert.assertEquals( + Assertions.assertEquals( request!!.timestamp, result.getAsLong(REQUEST_COLUMN_NAME_TIMESTAMP) as Long ) - Assert.assertEquals(request!!.ttl, result.getAsLong(REQUEST_COLUMN_NAME_TTL) as Long) + Assertions.assertEquals(request!!.ttl, result.getAsLong(REQUEST_COLUMN_NAME_TTL) as Long) } @Test fun testItemFromCursor() { val cursor = Mockito.mock(Cursor::class.java) - Mockito.`when`(cursor.getColumnIndexOrThrow(REQUEST_COLUMN_NAME_REQUEST_ID)).thenReturn(0) - Mockito.`when`(cursor.getString(0)).thenReturn(REQUEST_ID) - Mockito.`when`(cursor.getColumnIndexOrThrow(REQUEST_COLUMN_NAME_METHOD)).thenReturn(1) - Mockito.`when`(cursor.getString(1)).thenReturn(RequestMethod.GET.name) - Mockito.`when`(cursor.getColumnIndexOrThrow(REQUEST_COLUMN_NAME_URL)).thenReturn(2) - Mockito.`when`(cursor.getString(2)).thenReturn(URL) - Mockito.`when`(cursor.getColumnIndexOrThrow(REQUEST_COLUMN_NAME_HEADERS)).thenReturn(3) - Mockito.`when`(cursor.getBlob(3)).thenReturn(SerializationUtils.serializableToBlob(headers)) - Mockito.`when`(cursor.getColumnIndexOrThrow(REQUEST_COLUMN_NAME_PAYLOAD)).thenReturn(4) - Mockito.`when`(cursor.getBlob(4)).thenReturn(SerializationUtils.serializableToBlob(payload)) - Mockito.`when`(cursor.getColumnIndexOrThrow(REQUEST_COLUMN_NAME_TIMESTAMP)).thenReturn(5) - Mockito.`when`(cursor.getLong(5)).thenReturn(TIMESTAMP) - Mockito.`when`(cursor.getColumnIndexOrThrow(REQUEST_COLUMN_NAME_TTL)).thenReturn(6) - Mockito.`when`(cursor.getLong(6)).thenReturn(TTL) + whenever(cursor.getColumnIndexOrThrow(REQUEST_COLUMN_NAME_REQUEST_ID)).thenReturn(0) + whenever(cursor.getString(0)).thenReturn(REQUEST_ID) + whenever(cursor.getColumnIndexOrThrow(REQUEST_COLUMN_NAME_METHOD)).thenReturn(1) + whenever(cursor.getString(1)).thenReturn(RequestMethod.GET.name) + whenever(cursor.getColumnIndexOrThrow(REQUEST_COLUMN_NAME_URL)).thenReturn(2) + whenever(cursor.getString(2)).thenReturn(URL) + whenever(cursor.getColumnIndexOrThrow(REQUEST_COLUMN_NAME_HEADERS)).thenReturn(3) + whenever(cursor.getBlob(3)).thenReturn(SerializationUtils.serializableToBlob(headers)) + whenever(cursor.getColumnIndexOrThrow(REQUEST_COLUMN_NAME_PAYLOAD)).thenReturn(4) + whenever(cursor.getBlob(4)).thenReturn(SerializationUtils.serializableToBlob(payload)) + whenever(cursor.getColumnIndexOrThrow(REQUEST_COLUMN_NAME_TIMESTAMP)).thenReturn(5) + whenever(cursor.getLong(5)).thenReturn(TIMESTAMP) + whenever(cursor.getColumnIndexOrThrow(REQUEST_COLUMN_NAME_TTL)).thenReturn(6) + whenever(cursor.getLong(6)).thenReturn(TTL) val result = repository!!.itemFromCursor(cursor) - Assert.assertEquals(request, result) + + result shouldBe request } @Test @@ -129,8 +127,8 @@ class RequestModelRepositoryTest { 300, "id2" ) - val expected = Arrays.asList(model1, model2) - Assert.assertEquals(expected, result) + val expected = listOf(model1, model2) + result shouldBe expected } @Throws(JSONException::class) diff --git a/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelTest.kt b/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelTest.kt index 7536338b..7cb8155a 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelTest.kt @@ -3,15 +3,14 @@ package com.emarsys.core.request.model import android.net.Uri import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe + +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito import java.net.URL import java.util.* @@ -27,11 +26,8 @@ class RequestModelTest { private lateinit var timestampProvider: TimestampProvider private lateinit var uuidProvider: UUIDProvider - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun init() { url = "https://google.com" method = RequestMethod.PUT @@ -48,18 +44,18 @@ class RequestModelTest { @Throws(Exception::class) fun testBuilder_mandatoryArgumentsInitialized() { val result = RequestModel.Builder(timestampProvider, uuidProvider) - .url(url) - .build() - Assert.assertEquals(URL(url), result.url) + .url(url) + .build() + result.url shouldBe URL(url) } @Test fun testBuilder_optionalArgumentsInitializedWithDefaultValue() { val result = RequestModel.Builder(timestampProvider, uuidProvider).url(url).build() - Assert.assertEquals(HashMap(), result.headers) - Assert.assertEquals(null, result.payload) - Assert.assertEquals(RequestMethod.POST, result.method) - Assert.assertEquals(Long.MAX_VALUE, result.ttl) + result.headers shouldBe HashMap() + result.payload shouldBe null + result.method shouldBe RequestMethod.POST + result.ttl shouldBe Long.MAX_VALUE } @Test @@ -76,17 +72,18 @@ class RequestModelTest { val queryParams: MutableMap = HashMap() queryParams["q1"] = "v1" val result = RequestModel.Builder(timestampProvider, uuidProvider) - .url(url) - .method(method) - .payload(payload) - .headers(headers) - .queryParams(queryParams) - .ttl(ttl) - .build() + .url(url) + .method(method) + .payload(payload) + .headers(headers) + .queryParams(queryParams) + .ttl(ttl) + .build() val id = result.id val timestamp = result.timestamp val urlWithQueryParams = "$url?q1=v1" - val expected = RequestModel(urlWithQueryParams, method, payload, headers, timestamp, ttl, id) + val expected = + RequestModel(urlWithQueryParams, method, payload, headers, timestamp, ttl, id) result shouldBe expected } @@ -97,8 +94,8 @@ class RequestModelTest { val timestamp = 1L whenever(timestampProvider.provideTimestamp()).thenReturn(timestamp) val result = RequestModel.Builder(timestampProvider, uuidProvider) - .url(url) - .build() + .url(url) + .build() result.timestamp shouldBe timestamp } @@ -108,9 +105,10 @@ class RequestModelTest { val requestId = "REQUEST_ID" Mockito.`when`(uuidProvider.provideId()).thenReturn(requestId) val result = RequestModel.Builder(timestampProvider, uuidProvider) - .url(url) - .build() - Assert.assertEquals(requestId, result.id) + .url(url) + .build() + + result.id shouldBe requestId } @Test @@ -118,12 +116,12 @@ class RequestModelTest { val queryParams: MutableMap = HashMap() queryParams["key1"] = "value1" val result = RequestModel.Builder(timestampProvider, uuidProvider) - .url("https://emarsys.com") - .queryParams(queryParams).build() + .url("https://emarsys.com") + .queryParams(queryParams).build() val uri = Uri.parse(result.url.toString()) - Assert.assertEquals("emarsys.com", uri.host) - Assert.assertEquals("value1", uri.getQueryParameter("key1")) - Assert.assertEquals(1, uri.queryParameterNames.size.toLong()) + uri.host shouldBe "emarsys.com" + uri.getQueryParameter("key1") shouldBe "value1" + uri.queryParameterNames.size.toLong() shouldBe 1 } @Test @@ -132,28 +130,28 @@ class RequestModelTest { queryParams["key1"] = "value1" queryParams["key2"] = "value2" val result = RequestModel.Builder(timestampProvider, uuidProvider) - .url("https://emarsys.com") - .queryParams(queryParams).build() + .url("https://emarsys.com") + .queryParams(queryParams).build() val uri = Uri.parse(result.url.toString()) - Assert.assertEquals("emarsys.com", uri.host) - Assert.assertEquals("value1", uri.getQueryParameter("key1")) - Assert.assertEquals("value2", uri.getQueryParameter("key2")) - Assert.assertEquals(2, uri.queryParameterNames.size.toLong()) + uri.host shouldBe "emarsys.com" + uri.getQueryParameter("key1") shouldBe "value1" + uri.getQueryParameter("key2") shouldBe "value2" + uri.queryParameterNames.size.toLong() shouldBe 2 } @Test fun testBuilder_ignoresEmptyMap() { val result = RequestModel.Builder(timestampProvider, uuidProvider) - .url("https://emarsys.com") - .queryParams(HashMap()).build() - Assert.assertEquals("https://emarsys.com", result.url.toString()) + .url("https://emarsys.com") + .queryParams(HashMap()).build() + result.url.toString() shouldBe "https://emarsys.com" } @Test fun testBuilder_from() { val expected = RequestModel(url, method, payload, headers, timestamp, ttl, id) val result = RequestModel.Builder(expected).build() - Assert.assertEquals(expected, result) + result shouldBe expected } private fun createPayload(): Map { diff --git a/core/src/androidTest/java/com/emarsys/core/request/model/specification/FilterByUrlPatternTest.kt b/core/src/androidTest/java/com/emarsys/core/request/model/specification/FilterByUrlPatternTest.kt index ea4eefc6..1529ffd0 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/model/specification/FilterByUrlPatternTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/model/specification/FilterByUrlPatternTest.kt @@ -10,20 +10,17 @@ import com.emarsys.core.request.model.RequestModel import com.emarsys.core.request.model.RequestModelRepository import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.matchers.collections.shouldContainAll -import io.kotlintest.shouldBe +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.collections.shouldContainAll +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + class FilterByUrlPatternTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule private lateinit var specification: FilterByUrlPattern private lateinit var pattern: String @@ -31,7 +28,7 @@ class FilterByUrlPatternTest { private lateinit var timestampProvider: TimestampProvider private lateinit var uuidProvider: UUIDProvider - @Before + @BeforeEach fun init() { DatabaseTestUtils.deleteCoreDatabase() pattern = "root/___/_%/event" @@ -60,9 +57,11 @@ class FilterByUrlPatternTest { } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_patternMustNotBeNull() { - FilterByUrlPattern(null) + shouldThrow { + FilterByUrlPattern(null) + } } @Test diff --git a/core/src/androidTest/java/com/emarsys/core/resource/MetaDataReaderTest.kt b/core/src/androidTest/java/com/emarsys/core/resource/MetaDataReaderTest.kt index e08cf263..1be90226 100644 --- a/core/src/androidTest/java/com/emarsys/core/resource/MetaDataReaderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/resource/MetaDataReaderTest.kt @@ -1,103 +1,116 @@ -package com.emarsys.core.resource; - -import android.content.Context; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.os.Bundle; - -import com.emarsys.testUtil.InstrumentationRegistry; -import com.emarsys.testUtil.TimeoutUtils; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; -import org.mockito.Mockito; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class MetaDataReaderTest { - - private MetaDataReader reader; - - @Rule - public TestRule timeout = TimeoutUtils.getTimeoutRule(); - - @Before - public void setUp() throws Exception { - reader = new MetaDataReader(); +package com.emarsys.core.resource + +import android.content.Context +import android.content.pm.ApplicationInfo +import android.os.Bundle +import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.ArgumentMatchers +import org.mockito.Mockito + +class MetaDataReaderTest { + private var reader: MetaDataReader? = null + + @BeforeEach + @Throws(Exception::class) + fun setUp() { + reader = MetaDataReader() } - @Test(expected = IllegalArgumentException.class) - public void testGetIntOrNull_context_mustNotBeNull() throws Exception { - reader.getInt(null, "key"); + @Test + fun testGetIntOrNull_context_mustNotBeNull() { + shouldThrow { + reader!!.getInt(null, "key") + } } - @Test(expected = IllegalArgumentException.class) - public void testGetIntOrNull_key_mustNotBeNull() throws Exception { - reader.getInt(InstrumentationRegistry.getTargetContext(), null); + @Test + fun testGetIntOrNull_key_mustNotBeNull() { + shouldThrow { + reader!!.getInt(getTargetContext(), null) + } } @Test - public void testGetIntOrNull_returnsValue_ifExists() throws PackageManager.NameNotFoundException { - ApplicationInfo applicationInfo = new ApplicationInfo(); - Bundle bundle = new Bundle(); - bundle.putInt("something", 42); - applicationInfo.metaData = bundle; - - Context context = mock(Context.class, Mockito.RETURNS_DEEP_STUBS); - when(context.getPackageManager().getApplicationInfo(nullable(String.class), anyInt())).thenReturn(applicationInfo); - - assertEquals(42, reader.getInt(context, "something")); + fun testGetIntOrNull_returnsValue_ifExists() { + val applicationInfo = ApplicationInfo() + val bundle = Bundle() + bundle.putInt("something", 42) + applicationInfo.metaData = bundle + val context = Mockito.mock(Context::class.java, Mockito.RETURNS_DEEP_STUBS) + Mockito.`when`( + context.packageManager.getApplicationInfo( + ArgumentMatchers.nullable( + String::class.java + ), ArgumentMatchers.anyInt() + ) + ).thenReturn(applicationInfo) + reader!!.getInt(context, "something").toLong() shouldBe 42 } @Test - public void getIntOrNull_shouldReturnNull_ifThereIsNoValue() throws PackageManager.NameNotFoundException { - ApplicationInfo applicationInfo = new ApplicationInfo(); - applicationInfo.metaData = new Bundle(); - - Context context = mock(Context.class, Mockito.RETURNS_DEEP_STUBS); - when(context.getPackageManager().getApplicationInfo(nullable(String.class), anyInt())).thenReturn(applicationInfo); - - assertEquals(0, reader.getInt(context, "something")); + fun intOrNull_shouldReturnNull_ifThereIsNoValue() { + + val applicationInfo = ApplicationInfo() + applicationInfo.metaData = Bundle() + val context = Mockito.mock(Context::class.java, Mockito.RETURNS_DEEP_STUBS) + Mockito.`when`( + context.packageManager.getApplicationInfo( + ArgumentMatchers.nullable( + String::class.java + ), ArgumentMatchers.anyInt() + ) + ).thenReturn(applicationInfo) + reader!!.getInt(context, "something").toLong() shouldBe 0 } - @Test(expected = IllegalArgumentException.class) - public void testGetInt_context_mustNotBeNull() throws Exception { - reader.getInt(null, "key", 0); + @Test + fun testGetInt_context_mustNotBeNull() { + shouldThrow { + reader!!.getInt(null, "key", 0) + } } - @Test(expected = IllegalArgumentException.class) - public void testGetInt_key_mustNotBeNull() throws Exception { - reader.getInt(InstrumentationRegistry.getTargetContext(), null, 0); + @Test + fun testGetInt_key_mustNotBeNull() { + shouldThrow { + reader!!.getInt(getTargetContext(), null, 0) + } } @Test - public void testGetInt_returnsValue_ifExists() throws PackageManager.NameNotFoundException { - ApplicationInfo applicationInfo = new ApplicationInfo(); - Bundle bundle = new Bundle(); - bundle.putInt("something", 43); - applicationInfo.metaData = bundle; - - Context context = mock(Context.class, Mockito.RETURNS_DEEP_STUBS); - when(context.getPackageManager().getApplicationInfo(nullable(String.class), anyInt())).thenReturn(applicationInfo); - - assertEquals(43, reader.getInt(context, "something", -1)); + fun testGetInt_returnsValue_ifExists() { + val applicationInfo = ApplicationInfo() + val bundle = Bundle() + bundle.putInt("something", 43) + applicationInfo.metaData = bundle + val context = Mockito.mock(Context::class.java, Mockito.RETURNS_DEEP_STUBS) + Mockito.`when`( + context.packageManager.getApplicationInfo( + ArgumentMatchers.nullable( + String::class.java + ), ArgumentMatchers.anyInt() + ) + ).thenReturn(applicationInfo) + reader!!.getInt(context, "something", -1).toLong() shouldBe 43 } @Test - public void getInt_shouldReturnDefaultValue_ifThereIsNoValue() throws PackageManager.NameNotFoundException { - ApplicationInfo applicationInfo = new ApplicationInfo(); - applicationInfo.metaData = new Bundle(); - - Context context = mock(Context.class, Mockito.RETURNS_DEEP_STUBS); - when(context.getPackageManager().getApplicationInfo(nullable(String.class), anyInt())).thenReturn(applicationInfo); - - assertEquals(0, reader.getInt(context, "something")); - assertEquals(200, reader.getInt(context, "something", 200)); + fun int_shouldReturnDefaultValue_ifThereIsNoValue() { + val applicationInfo = ApplicationInfo() + applicationInfo.metaData = Bundle() + val context = Mockito.mock(Context::class.java, Mockito.RETURNS_DEEP_STUBS) + Mockito.`when`( + context.packageManager.getApplicationInfo( + ArgumentMatchers.nullable( + String::class.java + ), ArgumentMatchers.anyInt() + ) + ).thenReturn(applicationInfo) + reader!!.getInt(context, "something").toLong() shouldBe 0 + reader!!.getInt(context, "something", 200).toLong() shouldBe 200 } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/response/AbstractResponseHandlerTest.kt b/core/src/androidTest/java/com/emarsys/core/response/AbstractResponseHandlerTest.kt index 237a5d02..760c2ae8 100644 --- a/core/src/androidTest/java/com/emarsys/core/response/AbstractResponseHandlerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/response/AbstractResponseHandlerTest.kt @@ -1,20 +1,19 @@ package com.emarsys.core.response -import com.emarsys.testUtil.TimeoutUtils.timeoutRule -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.* +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever class AbstractResponseHandlerTest { private lateinit var abstractResponseHandler: AbstractResponseHandler - @Rule - @JvmField - var timeout: TestRule = timeoutRule - @Before + @BeforeEach fun init() { abstractResponseHandler = mock() } diff --git a/core/src/androidTest/java/com/emarsys/core/response/ResponseHandlersProcessorTest.kt b/core/src/androidTest/java/com/emarsys/core/response/ResponseHandlersProcessorTest.kt index ba0f53ff..6b7b8f85 100644 --- a/core/src/androidTest/java/com/emarsys/core/response/ResponseHandlersProcessorTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/response/ResponseHandlersProcessorTest.kt @@ -1,30 +1,29 @@ package com.emarsys.core.response -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.matchers.collections.shouldContainAll -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.collections.shouldContainAll +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.inOrder import org.mockito.Mockito.mock class ResponseHandlersProcessorTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule private lateinit var responseHandlersProcessor: ResponseHandlersProcessor - @Before + @BeforeEach fun setUp() { responseHandlersProcessor = ResponseHandlersProcessor() } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_responseHandlers_mustNotBeNull() { - ResponseHandlersProcessor(null) + shouldThrow { + ResponseHandlersProcessor(null) + } } @Test @@ -44,9 +43,11 @@ class ResponseHandlersProcessorTest { } } - @Test(expected = IllegalArgumentException::class) + @Test fun testAddReponseHandler_responseHandlers_mustNotBeNull() { - responseHandlersProcessor.addResponseHandlers(null) + shouldThrow { + responseHandlersProcessor.addResponseHandlers(null) + } } @Test diff --git a/core/src/androidTest/java/com/emarsys/core/response/ResponseModelTest.kt b/core/src/androidTest/java/com/emarsys/core/response/ResponseModelTest.kt index f9a81be9..da27a7f5 100644 --- a/core/src/androidTest/java/com/emarsys/core/response/ResponseModelTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/response/ResponseModelTest.kt @@ -2,15 +2,15 @@ package com.emarsys.core.response import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.request.model.RequestModel -import com.emarsys.testUtil.TimeoutUtils +import io.kotest.matchers.shouldBe import org.json.JSONException import org.json.JSONObject -import org.junit.Assert.assertEquals -import org.junit.Assert.assertNull -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule + + +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import java.net.HttpCookie @@ -31,11 +31,8 @@ class ResponseModelTest { private lateinit var mockTimestampProvider: TimestampProvider private lateinit var mockRequestModel: RequestModel - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun init() { statusCode = 200 message = "OK" @@ -53,78 +50,83 @@ class ResponseModelTest { @Throws(JSONException::class) fun testGetParsedBody_whenBodyIsAValidJson() { val responseModel = ResponseModel( - 200, - "", - mapOf(), - mapOf(), - "{ 'foo': 'bar', 'a': 1, 'nested': { 'b': 'c' }}", - timestamp, - mockRequestModel) + 200, + "", + mapOf(), + mapOf(), + "{ 'foo': 'bar', 'a': 1, 'nested': { 'b': 'c' }}", + timestamp, + mockRequestModel + ) val result = responseModel.parsedBody val expected = JSONObject() - .put("foo", "bar") - .put("a", 1) - .put("nested", JSONObject().put("b", "c")) + .put("foo", "bar") + .put("a", 1) + .put("nested", JSONObject().put("b", "c")) - assertEquals(expected.toString(), result.toString()) + result.toString() shouldBe expected.toString() } @Test @Throws(JSONException::class) fun testGetParsedBody_whenBodyIsAnInvalidJson() { val responseModel = ResponseModel( - 200, - "", - mapOf(), - mapOf(), - "Not valid json", - timestamp, - mockRequestModel) + 200, + "", + mapOf(), + mapOf(), + "Not valid json", + timestamp, + mockRequestModel + ) val result = responseModel.parsedBody - assertNull(result) + result shouldBe null } @Test @Throws(JSONException::class) fun testGetParsedBody_whenBodyIsNull() { val responseModel = ResponseModel( - 200, - "", - mapOf(), - mapOf(), - null, - timestamp, - mockRequestModel) + 200, + "", + mapOf(), + mapOf(), + null, + timestamp, + mockRequestModel + ) val result = responseModel.parsedBody - assertNull(result) + result shouldBe null } @Test fun testBuilder_withAllArguments() { - val expected = ResponseModel(statusCode, message, headers, cookies, body, timestamp, mockRequestModel) + val expected = + ResponseModel(statusCode, message, headers, cookies, body, timestamp, mockRequestModel) val result = ResponseModel.Builder(mockTimestampProvider) - .statusCode(statusCode) - .message(message) - .headers(listHeaders) - .body(body) - .requestModel(mockRequestModel) - .build() - assertEquals(expected, result) + .statusCode(statusCode) + .message(message) + .headers(listHeaders) + .body(body) + .requestModel(mockRequestModel) + .build() + result shouldBe expected } @Test fun testBuilder_withMandatoryArguments() { - val expected = ResponseModel(statusCode, message, mapOf(), mapOf(), body, timestamp, mockRequestModel) + val expected = + ResponseModel(statusCode, message, mapOf(), mapOf(), body, timestamp, mockRequestModel) val result = ResponseModel.Builder(mockTimestampProvider) - .statusCode(statusCode) - .message(message) - .body(body) - .requestModel(mockRequestModel) - .build() - assertEquals(expected, result) + .statusCode(statusCode) + .message(message) + .body(body) + .requestModel(mockRequestModel) + .build() + result shouldBe expected } @Test @@ -133,7 +135,7 @@ class ResponseModelTest { val inputList = listOf("alma", "korte", "szilva", "malna") val delimiter = ", " val actual = inputList.joinToString(delimiter) - assertEquals(expected, actual) + actual shouldBe expected } @Test @@ -147,7 +149,7 @@ class ResponseModelTest { inputHeaders["two"] = listOf("korte", "malna") val result = ResponseModel.Builder().convertHeaders(inputHeaders) - assertEquals(expected, result) + result shouldBe expected } @Test @@ -155,67 +157,72 @@ class ResponseModelTest { val headers = mapOf("content" to "application/x-www-form-urlencoded") val headersAsList = headers.wrapValuesInList() - val expected = ResponseModel(statusCode, message, headers, mapOf(), null, timestamp, mockRequestModel) + val expected = + ResponseModel(statusCode, message, headers, mapOf(), null, timestamp, mockRequestModel) val result = ResponseModel.Builder(mockTimestampProvider) - .statusCode(statusCode) - .headers(headersAsList) - .message(message) - .body(null) - .requestModel(mockRequestModel) - .build() - - assertEquals(expected, result) + .statusCode(statusCode) + .headers(headersAsList) + .message(message) + .body(null) + .requestModel(mockRequestModel) + .build() + + result shouldBe expected } @Test fun testBuilder_cookiesAreSetWithHeaders_setCookieCaseInsensitive() { val headers = mapOf( - null to "HTTP/1.1 200 OK", - "content" to "application/x-www-form-urlencoded", - "Set-Cookie" to "cdv=AAABBB;Path=/;Expires=Fri, 20-Sep-2019 14:30:24 GMT, s=ASDF1234", - "set-cookie" to "UserID=JohnDoe; Max-Age=3600; Version=1" + null to "HTTP/1.1 200 OK", + "content" to "application/x-www-form-urlencoded", + "Set-Cookie" to "cdv=AAABBB;Path=/;Expires=Fri, 20-Sep-2019 14:30:24 GMT, s=ASDF1234", + "set-cookie" to "UserID=JohnDoe; Max-Age=3600; Version=1" ) val headersAsList = mapOf>( - null to listOf("HTTP/1.1 200 OK"), - "content" to listOf("application/x-www-form-urlencoded"), - "Set-Cookie" to listOf( - "cdv=AAABBB;Path=/;Expires=Fri, 20-Sep-2019 14:30:24 GMT", - "s=ASDF1234" - ), - "set-cookie" to listOf("UserID=JohnDoe; Max-Age=3600; Version=1") + null to listOf("HTTP/1.1 200 OK"), + "content" to listOf("application/x-www-form-urlencoded"), + "Set-Cookie" to listOf( + "cdv=AAABBB;Path=/;Expires=Fri, 20-Sep-2019 14:30:24 GMT", + "s=ASDF1234" + ), + "set-cookie" to listOf("UserID=JohnDoe; Max-Age=3600; Version=1") ) val cookies = mapOf( - "cdv" to HttpCookie.parse("Set-Cookie: cdv=AAABBB;Path=/;Expires=Fri, 20-Sep-2019 14:30:24 GMT").first(), - "s" to HttpCookie.parse("Set-Cookie: s=ASDF1234").first(), - "UserID" to HttpCookie.parse("Set-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1").first() + "cdv" to HttpCookie.parse("Set-Cookie: cdv=AAABBB;Path=/;Expires=Fri, 20-Sep-2019 14:30:24 GMT") + .first(), + "s" to HttpCookie.parse("Set-Cookie: s=ASDF1234").first(), + "UserID" to HttpCookie.parse("Set-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1") + .first() ) - val expected = ResponseModel(statusCode, message, headers, cookies, null, timestamp, mockRequestModel) + val expected = + ResponseModel(statusCode, message, headers, cookies, null, timestamp, mockRequestModel) val result = ResponseModel.Builder(mockTimestampProvider) - .statusCode(statusCode) - .headers(headersAsList) - .message(message) - .body(null) - .requestModel(mockRequestModel) - .build() - - assertEquals(expected, result) + .statusCode(statusCode) + .headers(headersAsList) + .message(message) + .body(null) + .requestModel(mockRequestModel) + .build() + + result shouldBe expected } private fun createHeaders(): Map { return mapOf( - "content" to "application/x-www-form-urlencoded", - "set-cookie" to "UserID=JohnDoe; Max-Age=3600; Version=1" + "content" to "application/x-www-form-urlencoded", + "set-cookie" to "UserID=JohnDoe; Max-Age=3600; Version=1" ) } - private fun Map.wrapValuesInList(): Map> = this.mapValues { listOf(it.value) } + private fun Map.wrapValuesInList(): Map> = + this.mapValues { listOf(it.value) } private fun createCookies(): Map { return mapOf( - "UserID" to HttpCookie("UserID", "JohnDoe") + "UserID" to HttpCookie("UserID", "JohnDoe") ) } diff --git a/core/src/androidTest/java/com/emarsys/core/shard/ShardModelRepositoryTest.kt b/core/src/androidTest/java/com/emarsys/core/shard/ShardModelRepositoryTest.kt index 326e9342..1c871d39 100644 --- a/core/src/androidTest/java/com/emarsys/core/shard/ShardModelRepositoryTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/shard/ShardModelRepositoryTest.kt @@ -13,12 +13,13 @@ import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.util.serialization.SerializationUtils.serializableToBlob import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.Assertions + +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import java.io.Serializable @@ -30,9 +31,6 @@ class ShardModelRepositoryTest { private lateinit var payload: Map private lateinit var context: Context - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule companion object { const val TYPE: String = "type1" @@ -41,7 +39,7 @@ class ShardModelRepositoryTest { const val SHARD_ID = "shard_id" } - @Before + @BeforeEach fun init() { DatabaseTestUtils.deleteCoreDatabase() context = InstrumentationRegistry.getTargetContext() @@ -61,11 +59,14 @@ class ShardModelRepositoryTest { @Test fun testContentValuesFromItem() { val result = repository.contentValuesFromItem(shardModel) - Assert.assertEquals(shardModel.id, result.getAsString(SHARD_COLUMN_ID)) - Assert.assertEquals(shardModel.type, result.getAsString(SHARD_COLUMN_TYPE)) - Assert.assertArrayEquals(serializableToBlob(shardModel.data), result.getAsByteArray(SHARD_COLUMN_DATA)) - Assert.assertEquals(shardModel.timestamp, result.getAsLong(SHARD_COLUMN_TIMESTAMP)) - Assert.assertEquals(shardModel.ttl, result.getAsLong(SHARD_COLUMN_TTL)) + result.getAsString(SHARD_COLUMN_ID) shouldBe shardModel.id + result.getAsString(SHARD_COLUMN_TYPE) shouldBe shardModel.type + result.getAsLong(SHARD_COLUMN_TIMESTAMP) shouldBe shardModel.timestamp + result.getAsLong(SHARD_COLUMN_TTL) shouldBe shardModel.ttl + Assertions.assertArrayEquals( + serializableToBlob(shardModel.data), + result.getAsByteArray(SHARD_COLUMN_DATA) + ) } @Test @@ -87,6 +88,6 @@ class ShardModelRepositoryTest { whenever(cursor.getColumnIndexOrThrow(SHARD_COLUMN_TTL)).thenReturn(4) whenever(cursor.getLong(4)).thenReturn(TTL) - Assert.assertEquals(shardModel, repository.itemFromCursor(cursor)) + repository.itemFromCursor(cursor) shouldBe shardModel } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/shard/ShardModelTest.kt b/core/src/androidTest/java/com/emarsys/core/shard/ShardModelTest.kt index 53a59f10..83c63045 100644 --- a/core/src/androidTest/java/com/emarsys/core/shard/ShardModelTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/shard/ShardModelTest.kt @@ -2,14 +2,12 @@ package com.emarsys.core.shard import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Assert.assertEquals -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.Mockito.`when` +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.Mockito.mock +import org.mockito.Mockito.`when` class ShardModelTest { @@ -25,11 +23,8 @@ class ShardModelTest { private lateinit var uuidProvider: UUIDProvider private lateinit var payload: Map - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun init() { payload = createPayload() timestampProvider = mock(TimestampProvider::class.java) @@ -38,164 +33,190 @@ class ShardModelTest { `when`(uuidProvider.provideId()).thenReturn(UUID) } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_idMustNotBeNull() { - ShardModel(null, TYPE, mapOf(), 0, 0) + shouldThrow { + ShardModel(null, TYPE, mapOf(), 0, 0) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_typeMustNotBeNull() { - ShardModel(ID, null, mapOf(), 0, 0) + shouldThrow { + ShardModel(ID, null, mapOf(), 0, 0) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_dataMustNotBeNull() { - ShardModel(ID, TYPE, null, 0, 0) + shouldThrow { + ShardModel(ID, TYPE, null, 0, 0) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testBuilder_timestampProvider_mustBeNotNull() { - ShardModel.Builder(null, uuidProvider) + shouldThrow { + ShardModel.Builder(null, uuidProvider) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testBuilder_uuidProvider_mustBeNotNull() { - ShardModel.Builder(timestampProvider, null) + shouldThrow { + ShardModel.Builder(timestampProvider, null) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testBuilder_type_mustBeSet() { - ShardModel.Builder(timestampProvider, uuidProvider) + shouldThrow { + ShardModel.Builder(timestampProvider, uuidProvider) .build() + } } @Test fun testBuilder_id_shouldBeInitialized_byUUIDProvider() { val shardModel = ShardModel.Builder(timestampProvider, uuidProvider) - .type("") - .build() + .type("") + .build() - assertEquals(UUID, shardModel.id) + shardModel.id shouldBe UUID } @Test fun testBuilder_timestamp_shouldBeInitialized_byTimestampProvider() { val shardModel = ShardModel.Builder(timestampProvider, uuidProvider) - .type("") - .build() + .type("") + .build() - assertEquals(TIMESTAMP, shardModel.timestamp) + shardModel.timestamp shouldBe TIMESTAMP } @Test fun testBuilder_ttl_shouldHave_defaultValue() { val shardModel = ShardModel.Builder(timestampProvider, uuidProvider) - .type("") - .build() + .type("") + .build() - assertEquals(TTL, shardModel.ttl) + shardModel.ttl shouldBe TTL } @Test fun testBuilder_data_shouldHave_defaultValue() { val shardModel = ShardModel.Builder(timestampProvider, uuidProvider) - .type("") - .build() + .type("") + .build() - assertEquals(mapOf(), shardModel.data) + shardModel.data shouldBe mapOf() } @Test fun testBuilder_ttl_shouldBeSet() { val shardModel = ShardModel.Builder(timestampProvider, uuidProvider) - .type("") - .ttl(321L) - .build() + .type("") + .ttl(321L) + .build() - assertEquals(321L, shardModel.ttl) + shardModel.ttl shouldBe 321L } @Test fun testBuilder_type_shouldBeSet() { val shardModel = ShardModel.Builder(timestampProvider, uuidProvider) - .type(TYPE) - .build() + .type(TYPE) + .build() - assertEquals(TYPE, shardModel.type) + shardModel.type shouldBe TYPE } @Test fun testBuilder_shouldConcatenate_complexPayload_fromTypeAndData() { val shard: ShardModel = ShardModel.Builder(timestampProvider, uuidProvider) - .type(TYPE) - .payloadEntry("key", createPayload()) - .payloadEntry("key2", 234567890.9876543) - .build() + .type(TYPE) + .payloadEntry("key", createPayload()) + .payloadEntry("key2", 234567890.9876543) + .build() val expectedPayload = - mapOf( - "key" to mapOf( - "key1" to "231213", - "key2" to listOf( - mapOf("item1" to "item_1", - "itemKey2" to 19.9, - "itemKey3" to 1), - mapOf("item2" to "item_2", - "itemKey4" to 29.7, - "itemKey5" to 3) - ) + mapOf( + "key" to mapOf( + "key1" to "231213", + "key2" to listOf( + mapOf( + "item1" to "item_1", + "itemKey2" to 19.9, + "itemKey3" to 1 ), - "key2" to 234567890.9876543) + mapOf( + "item2" to "item_2", + "itemKey4" to 29.7, + "itemKey5" to 3 + ) + ) + ), + "key2" to 234567890.9876543 + ) - assertEquals(expectedPayload, shard.data) + shard.data shouldBe expectedPayload } @Test fun testBuilder_with_requiredArguments() { val shard: ShardModel = ShardModel.Builder(timestampProvider, uuidProvider) - .type(TYPE) - .build() + .type(TYPE) + .build() val expected = ShardModel(UUID, TYPE, mapOf(), TIMESTAMP, TTL) - assertEquals(expected, shard) + shard shouldBe expected } @Test fun testBuilder_with_allArguments() { val shard: ShardModel = ShardModel.Builder(timestampProvider, uuidProvider) - .type(TYPE) - .payloadEntry("key1", payload) - .payloadEntries(mapOf( - "key2" to "value2", - "key3" to 4.1415 - )) - .ttl(312L) - .build() + .type(TYPE) + .payloadEntry("key1", payload) + .payloadEntries( + mapOf( + "key2" to "value2", + "key3" to 4.1415 + ) + ) + .ttl(312L) + .build() val expected = ShardModel( - UUID, - TYPE, - mapOf( - "key1" to payload, - "key2" to "value2", - "key3" to 4.1415), - TIMESTAMP, - 312L) + UUID, + TYPE, + mapOf( + "key1" to payload, + "key2" to "value2", + "key3" to 4.1415 + ), + TIMESTAMP, + 312L + ) - assertEquals(expected, shard) + shard shouldBe expected } private fun createPayload(): Map { return mapOf( - "key1" to "231213", - "key2" to listOf( - mapOf("item1" to "item_1", - "itemKey2" to 19.9, - "itemKey3" to 1), - mapOf("item2" to "item_2", - "itemKey4" to 29.7, - "itemKey5" to 3)) + "key1" to "231213", + "key2" to listOf( + mapOf( + "item1" to "item_1", + "itemKey2" to 19.9, + "itemKey3" to 1 + ), + mapOf( + "item2" to "item_2", + "itemKey4" to 29.7, + "itemKey5" to 3 + ) + ) ) } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardIdsTest.kt b/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardIdsTest.kt index cffa95cb..098410bd 100644 --- a/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardIdsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardIdsTest.kt @@ -9,13 +9,13 @@ import com.emarsys.core.shard.ShardModel import com.emarsys.core.shard.ShardModelRepository import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + class FilterByShardIdsTest { @@ -24,11 +24,8 @@ class FilterByShardIdsTest { private lateinit var shardModelRepository: ShardModelRepository private lateinit var concurrentHadlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun init() { DatabaseTestUtils.deleteCoreDatabase() context = InstrumentationRegistry.getTargetContext().applicationContext @@ -46,10 +43,12 @@ class FilterByShardIdsTest { shardModelRepository = ShardModelRepository(coreDbHelper, concurrentHadlerHolder) } - @Test(expected = IllegalArgumentException::class) + @Test fun testDeleteRow_withInvalidArgument() { - runBlocking { - shardModelRepository.remove(FilterByShardIds(null)) + shouldThrow { + runBlocking { + shardModelRepository.remove(FilterByShardIds(null)) + } } } diff --git a/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardTypeTest.kt b/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardTypeTest.kt index 45b62710..7864e494 100644 --- a/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardTypeTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardTypeTest.kt @@ -8,19 +8,16 @@ import com.emarsys.core.shard.ShardModel import com.emarsys.core.shard.ShardModelRepository import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + class FilterByShardTypeTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule companion object { const val TYPE = "type1" @@ -31,7 +28,7 @@ class FilterByShardTypeTest { private lateinit var repository: ShardModelRepository private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Before + @BeforeEach fun setUp() { DatabaseTestUtils.deleteCoreDatabase() specification = FilterByShardType(TYPE) @@ -53,9 +50,11 @@ class FilterByShardTypeTest { } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_mustNotBeNull() { - FilterByShardType(null) + shouldThrow { + FilterByShardType(null) + } } @Test diff --git a/core/src/androidTest/java/com/emarsys/core/storage/AbstractStorageTest.kt b/core/src/androidTest/java/com/emarsys/core/storage/AbstractStorageTest.kt index 1858f38d..d747a600 100644 --- a/core/src/androidTest/java/com/emarsys/core/storage/AbstractStorageTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/storage/AbstractStorageTest.kt @@ -2,13 +2,13 @@ package com.emarsys.core.storage import android.content.SharedPreferences import com.emarsys.testUtil.ReflectionTestUtils -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.CALLS_REAL_METHODS import org.mockito.kotlin.mock import org.mockito.kotlin.times @@ -22,26 +22,26 @@ class AbstractStorageTest { private lateinit var mockSharedPreferences: SharedPreferences private lateinit var mockStorage: AbstractStorage - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun setUp() { mockSharedPreferences = mock() - mockStorage = (mock(defaultAnswer = CALLS_REAL_METHODS) as AbstractStorage) + mockStorage = + (mock(defaultAnswer = CALLS_REAL_METHODS) as AbstractStorage) ReflectionTestUtils.setInstanceField(mockStorage, "store", mockSharedPreferences) } - @Test(expected = java.lang.IllegalArgumentException::class) + @Test fun testConstructor_storeMustNotBeNull() { - object : AbstractStorage(null) { - override fun persistValue(store: SharedPreferences?, value: String?) = TODO() + shouldThrow { + object : AbstractStorage(null) { + override fun persistValue(store: SharedPreferences?, value: String?) = TODO() - override fun readPersistedValue(store: SharedPreferences?) = TODO() + override fun readPersistedValue(store: SharedPreferences?) = TODO() - override fun removePersistedValue(store: SharedPreferences?) = TODO() + override fun removePersistedValue(store: SharedPreferences?) = TODO() + } } } diff --git a/core/src/androidTest/java/com/emarsys/core/storage/BooleanStorageTest.kt b/core/src/androidTest/java/com/emarsys/core/storage/BooleanStorageTest.kt index 2b8b0318..dfa167a7 100644 --- a/core/src/androidTest/java/com/emarsys/core/storage/BooleanStorageTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/storage/BooleanStorageTest.kt @@ -1,13 +1,15 @@ package com.emarsys.core.storage import android.content.SharedPreferences -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.Mockito.* +import io.kotest.assertions.throwables.shouldThrow +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.Mockito.anyBoolean +import org.mockito.Mockito.anyString +import org.mockito.Mockito.mock +import org.mockito.Mockito.verify +import org.mockito.Mockito.verifyNoMoreInteractions class BooleanStorageTest { @@ -21,11 +23,8 @@ class BooleanStorageTest { private lateinit var storage: BooleanStorage private lateinit var storageKey: StorageKey - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { storageKey = mock(StorageKey::class.java).apply { whenever(key).thenReturn(KEY) @@ -43,9 +42,11 @@ class BooleanStorageTest { storage = BooleanStorage(storageKey, sharedPreferences) } - @Test(expected = NullPointerException::class) + @Test fun testConstructor_valueReturnedByKey_mustNotBeNull() { - BooleanStorage(mock(StorageKey::class.java), sharedPreferences) + shouldThrow { + BooleanStorage(mock(StorageKey::class.java), sharedPreferences) + } } @Test diff --git a/core/src/androidTest/java/com/emarsys/core/storage/CoreStorageKeyTest.kt b/core/src/androidTest/java/com/emarsys/core/storage/CoreStorageKeyTest.kt index b9116027..32fff1f9 100644 --- a/core/src/androidTest/java/com/emarsys/core/storage/CoreStorageKeyTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/storage/CoreStorageKeyTest.kt @@ -1,26 +1,23 @@ package com.emarsys.core.storage -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.data.forall -import io.kotlintest.shouldBe -import io.kotlintest.tables.row -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.data.forAll +import io.kotest.data.row +import io.kotest.matchers.shouldBe +import kotlinx.coroutines.runBlocking +import org.junit.jupiter.api.Test + class CoreStorageKeyTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + @Test - fun testGetKey() { + fun testGetKey() = runBlocking { CoreStorageKey.values().map { "core_${it.name.lowercase()}" }.zip(CoreStorageKey.values()) { stringValue, enum -> row(enum, stringValue) }.let { - forall(*it.toTypedArray()) { input, expected -> + forAll(*it.toTypedArray()) { input, expected -> input.key shouldBe expected } } diff --git a/core/src/androidTest/java/com/emarsys/core/storage/DefaultKeyValueStoreTest.kt b/core/src/androidTest/java/com/emarsys/core/storage/DefaultKeyValueStoreTest.kt index a36873ea..2bfd8d94 100644 --- a/core/src/androidTest/java/com/emarsys/core/storage/DefaultKeyValueStoreTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/storage/DefaultKeyValueStoreTest.kt @@ -4,13 +4,13 @@ import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import org.junit.After -import org.junit.Assert.* -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + class DefaultKeyValueStoreTest { companion object { @@ -24,131 +24,159 @@ class DefaultKeyValueStoreTest { private const val KEY6 = "key6" } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule private lateinit var store: DefaultKeyValueStore private lateinit var prefs: SharedPreferences - @Before + @BeforeEach @SuppressLint("ApplySharedPref") fun init() { prefs = InstrumentationRegistry.getTargetContext() - .applicationContext - .getSharedPreferences("DefaultKeysStoreTest", Context.MODE_PRIVATE) + .applicationContext + .getSharedPreferences("DefaultKeysStoreTest", Context.MODE_PRIVATE) prefs.edit().clear().commit() store = DefaultKeyValueStore(prefs) } - @After + @AfterEach fun tearDown() { prefs.edit().clear().commit() } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_shouldNotAcceptNullContext() { - DefaultKeyValueStore(null) + shouldThrow { + DefaultKeyValueStore(null) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testPutString_shouldNotAcceptNullKey() { - store.putString(null, "value") + shouldThrow { + store.putString(null, "value") + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testPutString_shouldNotAcceptNullValue() { - store.putString("key", null) + shouldThrow { + store.putString("key", null) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testPutInt_shouldNotAcceptNullKey() { - store.putInt(null, 0) + shouldThrow { + store.putInt(null, 0) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testPutLong_shouldNotAcceptNullKey() { - store.putLong(null, 0) + shouldThrow { + store.putLong(null, 0) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testPutFloat_shouldNotAcceptNullKey() { - store.putFloat(null, 0f) + shouldThrow { + store.putFloat(null, 0f) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testPutDouble_shouldNotAcceptNullKey() { - store.putDouble(null, 0.0) + shouldThrow { + store.putDouble(null, 0.0) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testPutBoolean_shouldNotAcceptNullKey() { - store.putBoolean(null, false) + shouldThrow { + store.putBoolean(null, false) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testGetString_shouldNotAcceptNullKey() { - store.getString(null) + shouldThrow { + store.getString(null) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testGetInt_shouldNotAcceptNullKey() { - store.getInt(null) + shouldThrow { + store.getInt(null) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testGetLong_shouldNotAcceptNullKey() { - store.getLong(null) + shouldThrow { + store.getLong(null) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testGetFloat_shouldNotAcceptNullKey() { - store.getFloat(null) + shouldThrow { + store.getFloat(null) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testGetDouble_shouldNotAcceptNullKey() { - store.getDouble(null) + shouldThrow { + store.getDouble(null) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testGetBoolean_shouldNotAcceptNullKey() { - store.getBoolean(null) + shouldThrow { + store.getBoolean(null) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testRemove_shouldNotAcceptNullKey() { - store.remove(null) + shouldThrow { + store.remove(null) + } } @Test fun test_put_get_string_shouldStoreValue() { store.putString(KEY, "value") - assertEquals("value", store.getString(KEY)) + store.getString(KEY) shouldBe "value" } @Test fun test_put_get_int_shouldStoreValue() { store.putInt(KEY, 342) - assertEquals(342, store.getInt(KEY)) + store.getInt(KEY) shouldBe 342 } @Test fun test_put_get_long_shouldStoreValue() { store.putLong(KEY, 33L) - assertEquals(33L, store.getLong(KEY)) + store.getLong(KEY) shouldBe 33L } @Test fun test_put_get_float_shouldStoreValue() { store.putFloat(KEY, 2.4f) - assertEquals(2.4f, store.getFloat(KEY), DELTA.toFloat()) + store + Assertions.assertEquals(2.4f, store.getFloat(KEY), DELTA.toFloat()) } @Test fun test_put_get_double_shouldStoreValue() { store.putDouble(KEY, 0.2) - assertEquals(0.2, store.getDouble(KEY), DELTA) + Assertions.assertEquals(0.2, store.getDouble(KEY), DELTA) } @Test @@ -159,65 +187,65 @@ class DefaultKeyValueStoreTest { store.putDouble(KEY4, java.lang.Double.POSITIVE_INFINITY) store.putDouble(KEY5, java.lang.Double.NEGATIVE_INFINITY) - assertEquals(java.lang.Double.MAX_VALUE, store.getDouble(KEY1), DELTA) - assertEquals(java.lang.Double.MIN_VALUE, store.getDouble(KEY2), DELTA) - assertEquals(java.lang.Double.NaN, store.getDouble(KEY3), DELTA) - assertEquals(java.lang.Double.POSITIVE_INFINITY, store.getDouble(KEY4), DELTA) - assertEquals(java.lang.Double.NEGATIVE_INFINITY, store.getDouble(KEY5), DELTA) + Assertions.assertEquals(java.lang.Double.MAX_VALUE, store.getDouble(KEY1), DELTA) + Assertions.assertEquals(java.lang.Double.MIN_VALUE, store.getDouble(KEY2), DELTA) + Assertions.assertEquals(java.lang.Double.NaN, store.getDouble(KEY3), DELTA) + Assertions.assertEquals(java.lang.Double.POSITIVE_INFINITY, store.getDouble(KEY4), DELTA) + Assertions.assertEquals(java.lang.Double.NEGATIVE_INFINITY, store.getDouble(KEY5), DELTA) } @Test fun test_put_get_boolean_shouldStoreValue() { store.putBoolean(KEY, true) - assertEquals(true, store.getBoolean(KEY)) + store.getBoolean(KEY) shouldBe true } @Test fun testPut_shouldOverridePreviousValues_withTheSameKey() { store.putString(KEY, "value") - assertEquals("value", store.getString(KEY)) + store.getString(KEY) shouldBe "value" store.putInt(KEY, 23) - assertEquals(23, store.getInt(KEY)) + store.getInt(KEY) shouldBe 23 store.putLong(KEY, 88111) - assertEquals(88111, store.getLong(KEY)) + store.getLong(KEY) shouldBe 88111 store.putFloat(KEY, 765.23f) - assertEquals(765.23f, store.getFloat(KEY), DELTA.toFloat()) + Assertions.assertEquals(765.23f, store.getFloat(KEY), DELTA.toFloat()) store.putDouble(KEY, 0.03013) - assertEquals(0.03013, store.getDouble(KEY), DELTA) + Assertions.assertEquals(0.03013, store.getDouble(KEY), DELTA) store.putBoolean(KEY, true) - assertEquals(true, store.getBoolean(KEY)) + store.getBoolean(KEY) shouldBe true } @Test fun testRemove() { store.putString(KEY1, "value") store.remove(KEY1) - assertNull(store.getString(KEY1)) + store.getString(KEY1) shouldBe null store.putInt(KEY2, 567) store.remove(KEY2) - assertEquals(0, store.getInt(KEY2)) + store.getInt(KEY2) shouldBe 0 store.putLong(KEY3, 888) store.remove(KEY3) - assertEquals(0, store.getLong(KEY3)) + store.getLong(KEY3) shouldBe 0 store.putFloat(KEY4, 44.2f) store.remove(KEY4) - assertEquals(0.0f, store.getFloat(KEY4), DELTA.toFloat()) + Assertions.assertEquals(0.0f, store.getFloat(KEY4), DELTA.toFloat()) store.putDouble(KEY5, 120120.0301) store.remove(KEY5) - assertEquals(0.0, store.getDouble(KEY5), DELTA) + Assertions.assertEquals(0.0, store.getDouble(KEY5), DELTA) store.putBoolean(KEY6, true) store.remove(KEY6) - assertEquals(false, store.getBoolean(KEY6)) + store.getBoolean(KEY6) shouldBe false } @Test @@ -227,9 +255,9 @@ class DefaultKeyValueStoreTest { store.remove(KEY) - assertEquals(2, store.size) - assertEquals(70, store.getInt(KEY1)) - assertEquals("value", store.getString(KEY2)) + store.size shouldBe 2 + store.getInt(KEY1) shouldBe 70 + store.getString(KEY2) shouldBe "value" } @Test @@ -237,7 +265,7 @@ class DefaultKeyValueStoreTest { store.putBoolean(KEY, true) store.clear() - assertEquals(0, store.size) + store.size shouldBe 0 } @Test @@ -246,11 +274,11 @@ class DefaultKeyValueStoreTest { store.putLong(KEY2, 18) store.putBoolean(KEY3, true) - assertEquals(3, store.size) + store.size shouldBe 3 store.remove(KEY2) - assertEquals(2, store.size) + store.size shouldBe 2 } @Test @@ -258,7 +286,7 @@ class DefaultKeyValueStoreTest { store.putBoolean(KEY, true) store.clear() - assertTrue(store.isEmpty) + store.isEmpty shouldBe true } @Test @@ -266,6 +294,6 @@ class DefaultKeyValueStoreTest { store.putInt("key2", 18) store.putInt("key3", 10) - assertFalse(store.isEmpty) + store.isEmpty shouldBe false } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/storage/SecureSharedPreferencesProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/storage/SecureSharedPreferencesProviderTest.kt index a049dc36..c0df4afc 100644 --- a/core/src/androidTest/java/com/emarsys/core/storage/SecureSharedPreferencesProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/storage/SecureSharedPreferencesProviderTest.kt @@ -4,25 +4,22 @@ import android.content.Context import android.content.Context.MODE_PRIVATE import android.content.SharedPreferences import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + class SecureSharedPreferencesProviderTest { private lateinit var sharedPreferencesProvider: SecureSharedPreferencesProvider - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var context: Context private lateinit var oldSharedPrefs: SharedPreferences - @Before + @BeforeEach fun setUp() { context = InstrumentationRegistry.getTargetContext().applicationContext oldSharedPrefs = context.getSharedPreferences("test_shared_prefs", MODE_PRIVATE) diff --git a/core/src/androidTest/java/com/emarsys/core/storage/StringStorageTest.kt b/core/src/androidTest/java/com/emarsys/core/storage/StringStorageTest.kt index 9ecb6790..bcea4ae0 100644 --- a/core/src/androidTest/java/com/emarsys/core/storage/StringStorageTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/storage/StringStorageTest.kt @@ -1,13 +1,14 @@ package com.emarsys.core.storage import android.content.SharedPreferences -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.Mockito.* +import io.kotest.assertions.throwables.shouldThrow +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.Mockito.anyString +import org.mockito.Mockito.mock +import org.mockito.Mockito.verify +import org.mockito.Mockito.verifyNoMoreInteractions class StringStorageTest { @@ -21,12 +22,8 @@ class StringStorageTest { private lateinit var storage: StringStorage private lateinit var storageKey: StorageKey - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Before + @BeforeEach fun setUp() { storageKey = mock(StorageKey::class.java).apply { whenever(key).thenReturn(KEY) @@ -44,19 +41,25 @@ class StringStorageTest { storage = StringStorage(storageKey, sharedPreferences) } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_key_mustNotBeNull() { - StringStorage(null, sharedPreferences) + shouldThrow { + StringStorage(null, sharedPreferences) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_valueReturnedByKey_mustNotBeNull() { - StringStorage(mock(StorageKey::class.java), sharedPreferences) + shouldThrow { + StringStorage(mock(StorageKey::class.java), sharedPreferences) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_sharedPreference_mustNotBeNull() { - StringStorage(storageKey, null) + shouldThrow { + StringStorage(storageKey, null) + } } @Test diff --git a/core/src/androidTest/java/com/emarsys/core/util/AssertTest.kt b/core/src/androidTest/java/com/emarsys/core/util/AssertTest.kt index b0448489..81a90a6a 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/AssertTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/AssertTest.kt @@ -1,22 +1,19 @@ package com.emarsys.core.util -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Assert.assertEquals -import org.junit.Assert.fail -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import java.util.* + +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.fail class AssertTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Test(expected = IllegalArgumentException::class) + @Test fun testNotNull_shouldThrowException_whenArgumentIsNull() { - Assert.notNull(null, "") + shouldThrow { + Assert.notNull(null, "") + } } @Test @@ -35,18 +32,22 @@ class AssertTest { Assert.notNull(null, message) fail("Should throw exception") } catch (e: Exception) { - assertEquals(message, e.message) + e.message shouldBe message } } - @Test(expected = IllegalArgumentException::class) + @Test fun testElementsNotNull_array_shouldThrowException_whenArgumentIsNull() { - Assert.elementsNotNull(null as Array?, "") + shouldThrow { + Assert.elementsNotNull(null as Array?, "") + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testElementsNotNull_array_shouldThrowException_whenContainsNullElement() { - Assert.elementsNotNull(arrayOf(Any(), Any(), null, Any()), "") + shouldThrow { + Assert.elementsNotNull(arrayOf(Any(), Any(), null, Any()), "") + } } @Test @@ -56,7 +57,7 @@ class AssertTest { Assert.elementsNotNull(arrayOf(Any(), Any(), null, Any()), message) fail("Should throw exception") } catch (iae: IllegalArgumentException) { - assertEquals(message, iae.message) + iae.message shouldBe message } } @@ -78,14 +79,18 @@ class AssertTest { } } - @Test(expected = IllegalArgumentException::class) + @Test fun testElementsNotNull_list_shouldThrowException_whenArgumentIsNull() { - Assert.elementsNotNull(null as List<*>?, "") + shouldThrow { + Assert.elementsNotNull(null as List<*>?, "") + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testElementsNotNull_list_shouldThrowException_whenContainsNullElement() { - Assert.elementsNotNull(listOf(Any(), Any(), null, Any()), "") + shouldThrow { + Assert.elementsNotNull(listOf(Any(), Any(), null, Any()), "") + } } @Test @@ -95,7 +100,7 @@ class AssertTest { Assert.elementsNotNull(listOf(Any(), Any(), null, Any()), message) fail("Should throw exception") } catch (iae: IllegalArgumentException) { - assertEquals(message, iae.message) + iae.message shouldBe message } } @@ -117,14 +122,18 @@ class AssertTest { } } - @Test(expected = IllegalArgumentException::class) + @Test fun testNotEmpty_array_shouldNotAcceptNull() { - Assert.notEmpty(null as Array?, "message") + shouldThrow { + Assert.notEmpty(null as Array?, "message") + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testNotEmpty_array_shouldThrowException_whenArrayIsEmpty() { - Assert.notEmpty(arrayOf(), "") + shouldThrow { + Assert.notEmpty(arrayOf(), "") + } } @Test @@ -134,7 +143,7 @@ class AssertTest { Assert.notEmpty(arrayOf(), message) fail("Should throw exception") } catch (iae: IllegalArgumentException) { - assertEquals(message, iae.message) + iae.message shouldBe message } } @@ -144,7 +153,7 @@ class AssertTest { Assert.notEmpty(arrayOf(), null) fail("Should throw exception") } catch (iae: IllegalArgumentException) { - assertEquals("Argument must not be empty!", iae.message) + iae.message shouldBe "Argument must not be empty!" } } @@ -157,15 +166,19 @@ class AssertTest { } } - @Test(expected = IllegalArgumentException::class) + @Test fun testNotEmpty_list_shouldNotAcceptNull() { - Assert.notEmpty(null as List<*>?, "message") + shouldThrow { + Assert.notEmpty(null as List<*>?, "message") + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testNotEmpty_list_shouldThrowException_whenArrayIsEmpty() { - Assert.notEmpty(listOf(), "") + shouldThrow { + Assert.notEmpty(listOf(), "") + } } @Test @@ -175,7 +188,7 @@ class AssertTest { Assert.notEmpty(listOf(), message) fail("Should throw exception") } catch (iae: IllegalArgumentException) { - assertEquals(message, iae.message) + iae.message shouldBe message } } @@ -185,7 +198,7 @@ class AssertTest { Assert.notEmpty(listOf(), null) fail("Should throw exception") } catch (iae: IllegalArgumentException) { - assertEquals("Argument must not be empty!", iae.message) + iae.message shouldBe "Argument must not be empty!" } } @@ -204,7 +217,7 @@ class AssertTest { Assert.positiveInt(0, null) fail("Should throw exception") } catch (iae: IllegalArgumentException) { - assertEquals("Argument must be greater than zero!", iae.message) + iae.message shouldBe "Argument must be greater than zero!" } } @@ -214,7 +227,7 @@ class AssertTest { Assert.positiveInt(null, null) fail("Should throw exception") } catch (iae: java.lang.IllegalArgumentException) { - assertEquals("Argument must not be null!", iae.message) + iae.message shouldBe "Argument must not be null!" } } @@ -224,7 +237,7 @@ class AssertTest { Assert.positiveInt(-10, null) fail("Should throw exception") } catch (iae: java.lang.IllegalArgumentException) { - assertEquals("Argument must be greater than zero!", iae.message) + iae.message shouldBe "Argument must be greater than zero!" } } diff --git a/core/src/androidTest/java/com/emarsys/core/util/DatabaseUtilTest.kt b/core/src/androidTest/java/com/emarsys/core/util/DatabaseUtilTest.kt index 4200ff4a..2e49a831 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/DatabaseUtilTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/DatabaseUtilTest.kt @@ -1,20 +1,16 @@ package com.emarsys.core.util -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Assert -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule + +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.Test + class DatabaseUtilTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun testGenerateInStatement_shouldGenerateValidStatementEnding() { val result = DatabaseUtil.generateInStatement("request_id", arrayOf("123", "12", "1")) - Assert.assertEquals("request_id IN (?, ?, ?)", result) + result shouldBe "request_id IN (?, ?, ?)" } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/util/ExceptionExtensionsKtTest.kt b/core/src/androidTest/java/com/emarsys/core/util/ExceptionExtensionsKtTest.kt index 9138b412..b6ed282a 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/ExceptionExtensionsKtTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/ExceptionExtensionsKtTest.kt @@ -1,7 +1,7 @@ package com.emarsys.core.util -import io.kotlintest.shouldBe -import org.junit.Test +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.Test class ExceptionExtensionsKtTest { diff --git a/core/src/androidTest/java/com/emarsys/core/util/FileDownloaderTest.kt b/core/src/androidTest/java/com/emarsys/core/util/FileDownloaderTest.kt index db36a390..f4c0f85c 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/FileDownloaderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/FileDownloaderTest.kt @@ -5,16 +5,17 @@ import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.testUtil.FileTestUtils import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext -import com.emarsys.testUtil.RetryUtils.retryRule import com.emarsys.testUtil.TestUrls.LARGE_IMAGE import com.emarsys.testUtil.TestUrls.customResponse -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Assert.* -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe + +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test +import org.junitpioneer.jupiter.RetryingTest + import java.io.ByteArrayOutputStream import java.io.File import java.io.FileInputStream @@ -27,44 +28,42 @@ class FileDownloaderTest { private lateinit var context: Context private lateinit var fileDownloader: FileDownloader - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Rule - @JvmField - var retry: TestRule = retryRule - - @Before + @BeforeEach fun setUp() { context = getTargetContext() fileDownloader = FileDownloader(context) } @Test + @RetryingTest(3) fun testDownload_shouldNotReturnNull_whenUrlIsCorrect() { - assertNotNull(fileDownloader.download(LARGE_IMAGE)) + fileDownloader.download(LARGE_IMAGE) shouldNotBe null } @Test + @RetryingTest(3) fun testDownload_shouldReturnNull_whenSchemeIsNotHttps() { - assertNull(fileDownloader.download("little://cat")) + fileDownloader.download("little://cat") shouldBe null } @Test + @RetryingTest(3) fun testDownload_shouldReturnNull_whenResourceDoesNotExist() { val result = fileDownloader.download(customResponse(404)) result shouldBe null } @Test + @RetryingTest(3) fun testDownload_returnedPathShouldExist() { val filePath = fileDownloader.download(LARGE_IMAGE) val file = File(filePath!!) - assertTrue(file.exists()) + file.exists() shouldBe true } @Test + @RetryingTest(3) fun testDownload_downloadedAndRemoteFileShouldBeTheSame() { val latch = CountDownLatch(1) val concurrentHandlerHolder: ConcurrentHandlerHolder = @@ -78,12 +77,10 @@ class FileDownloaderTest { val fileInputStream: InputStream = FileInputStream(file) val remoteInputStream = fileDownloader.inputStreamFromUrl(path) try { - assertTrue( - Arrays.equals( - convertToByteArray(fileInputStream), - convertToByteArray(remoteInputStream!!) - ) - ) + Arrays.equals( + convertToByteArray(fileInputStream), + convertToByteArray(remoteInputStream!!) + ) shouldBe true } finally { fileInputStream.close() remoteInputStream?.close() @@ -94,34 +91,39 @@ class FileDownloaderTest { } @Test + @RetryingTest(3) fun testDelete_shouldDeleteTheFile() { val filePath = createTempFile() val file = File(filePath) - assertTrue(file.exists()) + file.exists() shouldBe true fileDownloader.delete(filePath) - assertFalse(file.exists()) + file.exists() shouldBe false } - @Test(expected = IllegalArgumentException::class) + @Test fun testDelete_shouldThrowException_whenFileIsNotExist() { - fileDownloader.delete("file:///invalidFile.file") + shouldThrow { + fileDownloader.delete("file:///invalidFile.file") + } } @Test + @RetryingTest(3) fun testWriteReadFileIntoString() { val cacheFolder = context.cacheDir val fileName = UUID.randomUUID().toString() val fileUrl = File(cacheFolder, fileName).absolutePath val expected = "ContentOfTheFile\nNew line" FileTestUtils.writeToFile(expected, fileUrl) - assertEquals(expected, fileDownloader.readFileIntoString(fileUrl)) + fileDownloader.readFileIntoString(fileUrl) shouldBe expected } @Test + @RetryingTest(3) fun testReadURLIntoString() { fileDownloader.download(LARGE_IMAGE)?.let { val expected = fileDownloader.readFileIntoString(it) - assertEquals(expected, fileDownloader.readURLIntoString(LARGE_IMAGE)) + fileDownloader.readURLIntoString(LARGE_IMAGE) shouldBe expected } } diff --git a/core/src/androidTest/java/com/emarsys/core/util/HeaderUtilsInstrumentationTest.kt b/core/src/androidTest/java/com/emarsys/core/util/HeaderUtilsInstrumentationTest.kt index 7f33968a..83867167 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/HeaderUtilsInstrumentationTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/HeaderUtilsInstrumentationTest.kt @@ -1,30 +1,23 @@ -package com.emarsys.core.util; +package com.emarsys.core.util -import com.emarsys.testUtil.TimeoutUtils; +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.Test -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; +class HeaderUtilsInstrumentationTest { + private val username = "user" -import static org.junit.Assert.assertEquals; - -public class HeaderUtilsInstrumentationTest { - - private final String username = "user"; - - @Rule - public TestRule timeout = TimeoutUtils.getTimeoutRule(); - - @Test(expected = IllegalArgumentException.class) - public void testCreateBasicAuth_usernameShouldNotBeNull(){ - HeaderUtils.createBasicAuth(null); + @Test + fun testCreateBasicAuth_usernameShouldNotBeNull() { + shouldThrow { + HeaderUtils.createBasicAuth(null) + } } @Test - public void testCreateBasicAuth_shouldCreateCorrectBasicAuthString() throws Exception { - String expected = "Basic dXNlcjo="; - String result = HeaderUtils.createBasicAuth(username); - assertEquals(expected, result); + fun testCreateBasicAuth_shouldCreateCorrectBasicAuthString() { + val expected = "Basic dXNlcjo=" + val result = HeaderUtils.createBasicAuth(username) + result shouldBe expected } - } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/util/ImageUtilsTest.kt b/core/src/androidTest/java/com/emarsys/core/util/ImageUtilsTest.kt index be01c2b2..e4036ef0 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/ImageUtilsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/ImageUtilsTest.kt @@ -7,16 +7,15 @@ import com.emarsys.core.notification.NotificationManagerHelper import com.emarsys.core.provider.hardwareid.HardwareIdProvider import com.emarsys.core.provider.version.VersionProvider import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext -import com.emarsys.testUtil.RetryUtils -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.copyInputStreamToFile -import io.kotlintest.matchers.numerics.shouldBeLessThan -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.comparables.shouldBeLessThan +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test +import org.junitpioneer.jupiter.RetryingTest + import org.mockito.Mockito import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer @@ -36,21 +35,17 @@ class ImageUtilsTest { private lateinit var mockLanguageProvider: LanguageProvider private lateinit var mockVersionProvider: VersionProvider - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Rule - @JvmField - var retry: TestRule = RetryUtils.retryRule - @Before + @BeforeEach fun setup() { mockFileDownloader = mock { on { download(any(), any()) } doAnswer { val fileContent = getTargetContext().resources.openRawResource( - getTargetContext().resources.getIdentifier("emarsys_test_image", - "raw", getTargetContext().packageName)) + getTargetContext().resources.getIdentifier( + "emarsys_test_image", + "raw", getTargetContext().packageName + ) + ) val file = File(getTargetContext().cacheDir.toURI().toURL().path + "/testFile.tmp") file.copyInputStreamToFile(fileContent) file.toURI().toURL().path @@ -72,23 +67,25 @@ class ImageUtilsTest { } deviceInfo = DeviceInfo( - getTargetContext(), - mockHardwareIdProvider, - mockVersionProvider, - mockLanguageProvider, - Mockito.mock(NotificationManagerHelper::class.java), - isAutomaticPushSendingEnabled = true, - isGooglePlayAvailable = true + getTargetContext(), + mockHardwareIdProvider, + mockVersionProvider, + mockLanguageProvider, + Mockito.mock(NotificationManagerHelper::class.java), + isAutomaticPushSendingEnabled = true, + isGooglePlayAvailable = true ) } @Test + @RetryingTest(3) fun testLoadOptimizedBitmap_returnsNull_whenImageUrlIsNull() { ImageUtils.loadOptimizedBitmap(mockFileDownloader, null, deviceInfo) shouldBe null } @Test + @RetryingTest(3) fun testLoadOptimizedBitmap_withRemoteUrl_CleansUpTempFile() { clearCache() getTargetContext().cacheDir.list()?.size shouldBe 0 @@ -97,6 +94,7 @@ class ImageUtilsTest { } @Test + @RetryingTest(3) fun testLoadOptimizedBitmap_withLocalFile_ShouldNotCleanUpLocalFile() { clearCache() val fileUrl = mockFileDownloader.download(IMAGE_URL) @@ -112,6 +110,7 @@ class ImageUtilsTest { } @Test + @RetryingTest(3) fun testLoadOptimizedBitmap_withRemoteUrl() { val bitmap = ImageUtils.loadOptimizedBitmap(mockFileDownloader, IMAGE_URL, deviceInfo) bitmap shouldNotBe null @@ -120,6 +119,7 @@ class ImageUtilsTest { } @Test + @RetryingTest(3) fun testCalculateInSampleSize_returnedValueShouldBe4_whenRequestedWidthIs1080_widthIs2500() { val options = BitmapFactory.Options().apply { outWidth = 2500 diff --git a/core/src/androidTest/java/com/emarsys/core/util/JsonUtilsTest.kt b/core/src/androidTest/java/com/emarsys/core/util/JsonUtilsTest.kt index 288c6cfe..4f0e389e 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/JsonUtilsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/JsonUtilsTest.kt @@ -5,15 +5,15 @@ import com.emarsys.core.util.JsonUtils.fromMap import com.emarsys.core.util.JsonUtils.merge import com.emarsys.core.util.JsonUtils.toFlatMap import com.emarsys.core.util.JsonUtils.toFlatMapIncludingNulls -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe import org.json.JSONArray import org.json.JSONException import org.json.JSONObject -import org.junit.Assert -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule + + +import org.junit.jupiter.api.Test + import java.util.* class JsonUtilsTest { @@ -33,9 +33,6 @@ class JsonUtilsTest { const val KEY_12 = "key12" } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun testFromMap_emptyMap() { @@ -50,31 +47,32 @@ class JsonUtilsTest { @Throws(JSONException::class) fun testFromMap_basicValues() { val input = mapOf( - KEY_1 to 2, - KEY_2 to 200.toShort(), - KEY_3 to 212.toByte(), - KEY_4 to 4L, - KEY_5 to 4.0f, - KEY_6 to 0.7, - KEY_7 to true, - KEY_8 to false, - KEY_9 to "string", - KEY_10 to 'c', - KEY_11 to JSONArray(listOf("a", 1, "b")), - KEY_12 to JSONObject().put("a", "a").put("b", 2)) + KEY_1 to 2, + KEY_2 to 200.toShort(), + KEY_3 to 212.toByte(), + KEY_4 to 4L, + KEY_5 to 4.0f, + KEY_6 to 0.7, + KEY_7 to true, + KEY_8 to false, + KEY_9 to "string", + KEY_10 to 'c', + KEY_11 to JSONArray(listOf("a", 1, "b")), + KEY_12 to JSONObject().put("a", "a").put("b", 2) + ) val expected: JSONObject = JSONObject() - .put(KEY_1, 2) - .put(KEY_2, 200.toShort()) - .put(KEY_3, 212.toByte()) - .put(KEY_4, 4L) - .put(KEY_5, 4.0) - .put(KEY_6, 0.7) - .put(KEY_7, true) - .put(KEY_8, false) - .put(KEY_9, "string") - .put(KEY_10, "c") - .put(KEY_11, JSONArray(listOf("a", 1, "b"))) - .put(KEY_12, JSONObject().put("a", "a").put("b", 2)) + .put(KEY_1, 2) + .put(KEY_2, 200.toShort()) + .put(KEY_3, 212.toByte()) + .put(KEY_4, 4L) + .put(KEY_5, 4.0) + .put(KEY_6, 0.7) + .put(KEY_7, true) + .put(KEY_8, false) + .put(KEY_9, "string") + .put(KEY_10, "c") + .put(KEY_11, JSONArray(listOf("a", 1, "b"))) + .put(KEY_12, JSONObject().put("a", "a").put("b", 2)) val result = fromMap(input) result.toString() shouldBe expected.toString() @@ -84,31 +82,37 @@ class JsonUtilsTest { @Throws(JSONException::class) fun testFromMap_nestedMap() { val input = mapOf( - KEY_1 to mapOf( - "a" to "a", - "b" to 2, - "nested1" to mapOf( - "c" to "cc", - "d" to 20 - ), - "nested2" to mapOf( - "e" to "ee", - "f" to "ff" - ) + KEY_1 to mapOf( + "a" to "a", + "b" to 2, + "nested1" to mapOf( + "c" to "cc", + "d" to 20 ), - KEY_2 to false + "nested2" to mapOf( + "e" to "ee", + "f" to "ff" + ) + ), + KEY_2 to false ) val expected = JSONObject() - .put(KEY_1, JSONObject() - .put("a", "a") - .put("b", 2) - .put("nested1", JSONObject() - .put("c", "cc") - .put("d", 20)) - .put("nested2", JSONObject() - .put("e", "ee") - .put("f", "ff"))) - .put(KEY_2, false) + .put( + KEY_1, JSONObject() + .put("a", "a") + .put("b", 2) + .put( + "nested1", JSONObject() + .put("c", "cc") + .put("d", 20) + ) + .put( + "nested2", JSONObject() + .put("e", "ee") + .put("f", "ff") + ) + ) + .put(KEY_2, false) val result = fromMap(input) @@ -119,30 +123,43 @@ class JsonUtilsTest { @Throws(JSONException::class) fun testFromMap_nestedArray_withInnerObjects() { val deeplyNested = mapOf( - KEY_5 to "value") + KEY_5 to "value" + ) val nested1 = mapOf( - KEY_2 to 3, - KEY_3 to false, - KEY_4 to deeplyNested) + KEY_2 to 3, + KEY_3 to false, + KEY_4 to deeplyNested + ) val nested2 = mapOf( - KEY_6 to 4, - KEY_7 to "meid") + KEY_6 to 4, + KEY_7 to "meid" + ) val list = listOf( - nested1, - nested2) + nested1, + nested2 + ) val input = mapOf( - KEY_1 to list) + KEY_1 to list + ) val expected = JSONObject() - .put(KEY_1, - JSONArray() - .put(JSONObject() - .put(KEY_2, 3) - .put(KEY_3, false) - .put(KEY_4, JSONObject() - .put(KEY_5, "value"))) - .put(JSONObject() - .put(KEY_6, 4) - .put(KEY_7, "meid"))) + .put( + KEY_1, + JSONArray() + .put( + JSONObject() + .put(KEY_2, 3) + .put(KEY_3, false) + .put( + KEY_4, JSONObject() + .put(KEY_5, "value") + ) + ) + .put( + JSONObject() + .put(KEY_6, 4) + .put(KEY_7, "meid") + ) + ) val result = fromMap(input) result.toString() shouldBe expected.toString() @@ -152,31 +169,32 @@ class JsonUtilsTest { @Throws(JSONException::class) fun testFromList_basicValues() { val input = listOf( - 2, - 200.toShort(), - 212.toByte(), - 4L, - 4.0f, - 0.7, - true, - false, - "string", - 'c', - JSONArray(listOf("a", 1, "b")), - JSONObject().put("a", "a").put("b", 2)) + 2, + 200.toShort(), + 212.toByte(), + 4L, + 4.0f, + 0.7, + true, + false, + "string", + 'c', + JSONArray(listOf("a", 1, "b")), + JSONObject().put("a", "a").put("b", 2) + ) val expected: JSONArray = JSONArray() - .put(2) - .put(200.toShort()) - .put(212.toByte()) - .put(4L) - .put(4.0) - .put(0.7) - .put(true) - .put(false) - .put("string") - .put("c") - .put(JSONArray(listOf("a", 1, "b"))) - .put(JSONObject().put("a", "a").put("b", 2)) + .put(2) + .put(200.toShort()) + .put(212.toByte()) + .put(4L) + .put(4.0) + .put(0.7) + .put(true) + .put(false) + .put("string") + .put("c") + .put(JSONArray(listOf("a", 1, "b"))) + .put(JSONObject().put("a", "a").put("b", 2)) val result = fromList(input) result.toString() shouldBe expected.toString() @@ -185,24 +203,28 @@ class JsonUtilsTest { @Test fun testFromList_nestedArray() { val nested = listOf( - "a", - "b", - "c") + "a", + "b", + "c" + ) val input = listOf( - 1, - 4, - false, - nested, - "end") + 1, + 4, + false, + nested, + "end" + ) val expected = JSONArray() - .put(1) - .put(4) - .put(false) - .put(JSONArray() - .put("a") - .put("b") - .put("c")) - .put("end") + .put(1) + .put(4) + .put(false) + .put( + JSONArray() + .put("a") + .put("b") + .put("c") + ) + .put("end") val result = fromList(input) result.toString() shouldBe expected.toString() @@ -212,42 +234,56 @@ class JsonUtilsTest { @Throws(JSONException::class) fun testFromList_withNestedObjects() { val nested1 = mapOf( - KEY_1 to "a", - KEY_2 to 543) + KEY_1 to "a", + KEY_2 to 543 + ) val deeplyNested1 = mapOf( - KEY_4 to false, - KEY_5 to 0.4) + KEY_4 to false, + KEY_5 to 0.4 + ) val deeplyNested2 = mapOf( - KEY_7 to "id", - KEY_8 to 123456789) + KEY_7 to "id", + KEY_8 to 123456789 + ) val nested2 = mapOf( - KEY_3 to deeplyNested1, - KEY_6 to deeplyNested2) + KEY_3 to deeplyNested1, + KEY_6 to deeplyNested2 + ) val input = listOf( - nested1, - "___", - nested2) + nested1, + "___", + nested2 + ) val expected = JSONArray() - .put(JSONObject() - .put(KEY_1, "a") - .put(KEY_2, 543)) - .put("___") - .put(JSONObject() - .put(KEY_3, JSONObject() - .put(KEY_4, false) - .put(KEY_5, 0.4)) - .put(KEY_6, JSONObject() - .put(KEY_7, "id") - .put(KEY_8, 123456789)) - ) + .put( + JSONObject() + .put(KEY_1, "a") + .put(KEY_2, 543) + ) + .put("___") + .put( + JSONObject() + .put( + KEY_3, JSONObject() + .put(KEY_4, false) + .put(KEY_5, 0.4) + ) + .put( + KEY_6, JSONObject() + .put(KEY_7, "id") + .put(KEY_8, 123456789) + ) + ) val result = fromList(input) result.toString() shouldBe expected.toString() } - @Test(expected = IllegalArgumentException::class) + @Test fun testMerge_throwException_ifArgumentListIsEmpty() { - merge() + shouldThrow { + merge() + } } @Test @@ -255,7 +291,7 @@ class JsonUtilsTest { fun testMerge_withOnlyOneElement() { val expected = JSONObject().put("key", "value") val actual = merge(expected) - Assert.assertEquals(expected.toString(), actual.toString()) + actual.toString() shouldBe expected.toString() } @Test @@ -274,19 +310,23 @@ class JsonUtilsTest { @Throws(JSONException::class) fun testMerge_withMultipleElements() { val json1 = JSONObject() - .put("key1", "value1") - .put("key2", "value2") + .put("key1", "value1") + .put("key2", "value2") val json2 = JSONObject() - .put("key2", true) + .put("key2", true) val json3 = JSONObject() val json4 = JSONObject() - .put("key3", - JSONObject().put("nestedKey", 567)) + .put( + "key3", + JSONObject().put("nestedKey", 567) + ) val expected = JSONObject() - .put("key1", "value1") - .put("key2", true) - .put("key3", - JSONObject().put("nestedKey", 567)) + .put("key1", "value1") + .put("key2", true) + .put( + "key3", + JSONObject().put("nestedKey", 567) + ) val actual = merge(json1, json2, json3, json4) actual.toString() shouldBe expected.toString() @@ -303,9 +343,9 @@ class JsonUtilsTest { @Test fun testToFlatMapIncludingNulls_withJsonObjectOfStringAndNullValues() { val input = JSONObject() - .put("key1", "value1") - .put("key2", "null") - .put("key3", "value3") + .put("key1", "value1") + .put("key2", "null") + .put("key3", "value3") val result = toFlatMapIncludingNulls(input) val expected: MutableMap = mutableMapOf() expected["key1"] = "value1" @@ -318,22 +358,23 @@ class JsonUtilsTest { @Test fun testToFlatMapIncludingNulls_withJsonObjectOfMixedValues() { val input = JSONObject() - .put("key1", "value1") - .put("key2", 3.14) - .put("key3", false) - .put("keyWithNull", "null") - .put("key4", JSONObject() - .put("nestedKey1", "nestedValue1") - .put("nestedKey2", 900) - .put("nestedKey3", "null") - ) + .put("key1", "value1") + .put("key2", 3.14) + .put("key3", false) + .put("keyWithNull", "null") + .put( + "key4", JSONObject() + .put("nestedKey1", "nestedValue1") + .put("nestedKey2", 900) + .put("nestedKey3", "null") + ) val result = toFlatMapIncludingNulls(input) val expected: Map = mapOf( - "key1" to "value1", - "key2" to "3.14", - "key3" to "false", - "keyWithNull" to null, - "key4" to """{"nestedKey1":"nestedValue1","nestedKey2":900,"nestedKey3":"null"}""" + "key1" to "value1", + "key2" to "3.14", + "key3" to "false", + "keyWithNull" to null, + "key4" to """{"nestedKey1":"nestedValue1","nestedKey2":900,"nestedKey3":"null"}""" ) result shouldBe expected @@ -343,16 +384,16 @@ class JsonUtilsTest { fun testToFlatMap_withEmptyJsonObject() { val result = toFlatMap(JSONObject()) val expected: Map = HashMap() - Assert.assertEquals(expected, result) + result shouldBe expected } @Test @Throws(JSONException::class) fun testToFlatMap_withJsonObjectOfStringValues() { val input = JSONObject() - .put("key1", "value1") - .put("key2", "value2") - .put("key3", "value3") + .put("key1", "value1") + .put("key2", "value2") + .put("key3", "value3") val result = toFlatMap(input) val expected: MutableMap = HashMap() expected["key1"] = "value1" @@ -366,12 +407,14 @@ class JsonUtilsTest { @Throws(JSONException::class) fun testToFlatMap_withJsonObjectOfStringValuesAndNull() { val input = JSONObject() - .put("key1", "value1") - .put("key2", "value2") - .put("key3", null) - .put("key4", JSONObject() - .put("nestedKey1", "nestedValue1") - .put("nestedKey2", null)) + .put("key1", "value1") + .put("key2", "value2") + .put("key3", null) + .put( + "key4", JSONObject() + .put("nestedKey1", "nestedValue1") + .put("nestedKey2", null) + ) val result = toFlatMap(input) val expected: MutableMap = HashMap() expected["key1"] = "value1" @@ -385,12 +428,14 @@ class JsonUtilsTest { @Throws(JSONException::class) fun testToFlatMap_withJsonObjectOfMixedValues() { val input = JSONObject() - .put("key1", "value1") - .put("key2", 3.14) - .put("key3", false) - .put("key4", JSONObject() - .put("nestedKey1", "nestedValue1") - .put("nestedKey2", 900)) + .put("key1", "value1") + .put("key2", 3.14) + .put("key3", false) + .put( + "key4", JSONObject() + .put("nestedKey1", "nestedValue1") + .put("nestedKey2", 900) + ) val result = toFlatMap(input) val expected: MutableMap = HashMap() expected["key1"] = "value1" @@ -403,7 +448,8 @@ class JsonUtilsTest { @Test fun testToMap() { - val input = JSONObject(mapOf( + val input = JSONObject( + mapOf( "key" to "value", "key2" to 3, "key2.5" to true, @@ -414,33 +460,36 @@ class JsonUtilsTest { "key6" to JSONArray(listOf(JSONArray(listOf("value1")), JSONArray(listOf(1, 2)))), "key7" to JSONArray(listOf(JSONObject(mapOf("key" to "value")))), "key8" to JSONObject(), - "key9" to JSONObject(mapOf( + "key9" to JSONObject( + mapOf( "key" to 1, "key2" to "value2", "key2.5" to true, "key2.6" to null, "key3" to JSONArray(listOf("value1", "value2", "value3")) - )), - )) + ) + ), + ) + ) val expected = mapOf( - "key" to "value", - "key2" to 3, + "key" to "value", + "key2" to 3, + "key2.5" to true, + "key2.6" to null, + "key3" to listOf("value1", "value2", "value3"), + "key4" to listOf(1, 2, 3), + "key5" to listOf(true, false), + "key6" to listOf(listOf("value1"), listOf(1, 2)), + "key7" to listOf(mapOf("key" to "value")), + "key8" to mapOf(), + "key9" to mapOf( + "key" to 1, + "key2" to "value2", "key2.5" to true, "key2.6" to null, - "key3" to listOf("value1", "value2", "value3"), - "key4" to listOf(1, 2, 3), - "key5" to listOf(true, false), - "key6" to listOf(listOf("value1"), listOf(1, 2)), - "key7" to listOf(mapOf("key" to "value")), - "key8" to mapOf(), - "key9" to mapOf( - "key" to 1, - "key2" to "value2", - "key2.5" to true, - "key2.6" to null, - "key3" to listOf("value1", "value2", "value3") - ) + "key3" to listOf("value1", "value2", "value3") + ) ) JsonUtils.toMap(input) shouldBe expected diff --git a/core/src/androidTest/java/com/emarsys/core/util/MapExtensionsKtTest.kt b/core/src/androidTest/java/com/emarsys/core/util/MapExtensionsKtTest.kt index ea4062dc..afd700a5 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/MapExtensionsKtTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/MapExtensionsKtTest.kt @@ -1,7 +1,7 @@ package com.emarsys.core.util -import io.kotlintest.shouldBe -import org.junit.Test +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.Test class MapExtensionsKtTest { diff --git a/core/src/androidTest/java/com/emarsys/core/util/RequestModelUtilsTest.kt b/core/src/androidTest/java/com/emarsys/core/util/RequestModelUtilsTest.kt index 976759da..1e01012b 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/RequestModelUtilsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/RequestModelUtilsTest.kt @@ -3,31 +3,29 @@ package com.emarsys.core.util import com.emarsys.core.request.model.CompositeRequestModel import com.emarsys.core.request.model.RequestMethod import com.emarsys.core.request.model.RequestModel -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe + +import org.junit.jupiter.api.Test + class RequestModelUtilsTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun testExtractIdsFromCompositeRequestModel() { val ids = arrayOf("id1", "id2", "id3") val requestModel = CompositeRequestModel( - "0", - "https://emarsys.com", - RequestMethod.POST, - null, - emptyMap(), - 100, - 900000, - ids) + "0", + "https://emarsys.com", + RequestMethod.POST, + null, + emptyMap(), + 100, + 900000, + ids + ) val result = RequestModelUtils.extractIdsFromCompositeRequestModel(requestModel) @@ -43,15 +41,18 @@ class RequestModelUtilsTest { result shouldBe listOf("requestModelId") } - @Test(expected = IllegalArgumentException::class) + @Test fun testExtractQueryParameters_requestModelMustNotBeNull() { - RequestModelUtils.extractQueryParameters(null) + shouldThrow { + RequestModelUtils.extractQueryParameters(null) + } } @Test fun testExtractQueryParameters_returnsEmptyMap_whenNoQueryParametersFound() { val requestModel = createTestRequestModel( - "https://recommender.scarabresearch.com/merchants/", RequestMethod.GET) + "https://recommender.scarabresearch.com/merchants/", RequestMethod.GET + ) val result = RequestModelUtils.extractQueryParameters(requestModel) val expected = emptyMap() @@ -62,8 +63,9 @@ class RequestModelUtilsTest { @Test fun testExtractExtractQueryParameters_resultMapContainsParameterFromQuery() { val requestModel = createTestRequestModel( - "https://recommender.scarabresearch.com/merchants/merchantId?cp=1", - RequestMethod.GET) + "https://recommender.scarabresearch.com/merchants/merchantId?cp=1", + RequestMethod.GET + ) val result = RequestModelUtils.extractQueryParameters(requestModel) val expected = mapOf("cp" to "1") @@ -74,26 +76,28 @@ class RequestModelUtilsTest { @Test fun testExtractExtractQueryParameters_withMultipleQueryParameters() { val requestModel = createTestRequestModel( - "https://recommender.scarabresearch.com/merchants/merchantId?cp=1&vi=888999888&ci=12345&q3=c", - RequestMethod.GET) + "https://recommender.scarabresearch.com/merchants/merchantId?cp=1&vi=888999888&ci=12345&q3=c", + RequestMethod.GET + ) val result = RequestModelUtils.extractQueryParameters(requestModel) val expected = mapOf( - "cp" to "1", - "vi" to "888999888", - "ci" to "12345", - "q3" to "c") + "cp" to "1", + "vi" to "888999888", + "ci" to "12345", + "q3" to "c" + ) result shouldBe expected } private fun createTestRequestModel(url: String, method: RequestMethod) = RequestModel( - url, - method, - null, - emptyMap(), - 100, - 90000, - "requestModelId" + url, + method, + null, + emptyMap(), + 100, + 90000, + "requestModelId" ) } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/util/SerializationUtilsTest.kt b/core/src/androidTest/java/com/emarsys/core/util/SerializationUtilsTest.kt index b2136cd4..0a2ccede 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/SerializationUtilsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/SerializationUtilsTest.kt @@ -1,52 +1,42 @@ -package com.emarsys.core.util; +package com.emarsys.core.util -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import com.emarsys.core.request.model.RequestMethod; -import com.emarsys.core.request.model.RequestModel; -import com.emarsys.core.util.serialization.SerializationException; -import com.emarsys.core.util.serialization.SerializationUtils; -import com.emarsys.testUtil.TimeoutUtils; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; - -import java.util.HashMap; - -public class SerializationUtilsTest { - - @Rule - public TestRule timeout = TimeoutUtils.getTimeoutRule(); +import com.emarsys.core.request.model.RequestMethod +import com.emarsys.core.request.model.RequestModel +import com.emarsys.core.util.serialization.SerializationUtils +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.Test +class SerializationUtilsTest { @Test - public void testSerialization() throws SerializationException { - HashMap payload = new HashMap<>(); - payload.put("key", "value"); - HashMap nested = new HashMap<>(); - nested.put("key2", "value2"); - nested.put("key3", true); - payload.put("nested", nested); - - HashMap headers = new HashMap<>(); - headers.put("header1", "header-value1"); - headers.put("header2", "header-value2"); - - RequestModel expected = new RequestModel("https://www.google.com", RequestMethod.GET, payload, headers, 999, 101, "id"); - - byte[] blob = SerializationUtils.serializableToBlob(expected); - RequestModel result = (RequestModel) SerializationUtils.blobToSerializable(blob); - - assertEquals(expected, result); + fun testSerialization() { + val payload = HashMap() + payload["key"] = "value" + val nested = HashMap() + nested["key2"] = "value2" + nested["key3"] = true + payload["nested"] = nested + val headers = HashMap() + headers["header1"] = "header-value1" + headers["header2"] = "header-value2" + val expected = RequestModel( + "https://www.google.com", + RequestMethod.GET, + payload, + headers, + 999, + 101, + "id" + ) + val blob = SerializationUtils.serializableToBlob(expected) + val result = SerializationUtils.blobToSerializable(blob) as RequestModel + result shouldBe expected } @Test - public void testSerialization_serializesNullCorrectly() throws SerializationException { - RequestModel requestModel = null; - byte[] bytes = SerializationUtils.serializableToBlob(requestModel); - RequestModel result = (RequestModel) SerializationUtils.blobToSerializable(bytes); - assertNull(result); + fun testSerialization_serializesNullCorrectly() { + val requestModel: RequestModel? = null + val bytes = SerializationUtils.serializableToBlob(requestModel) + val result = SerializationUtils.blobToSerializable(bytes) as RequestModel? + result shouldBe null } - } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/util/SystemUtilsTest.kt b/core/src/androidTest/java/com/emarsys/core/util/SystemUtilsTest.kt index c0bd4352..c821165d 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/SystemUtilsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/SystemUtilsTest.kt @@ -1,17 +1,12 @@ package com.emarsys.core.util -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe + +import org.junit.jupiter.api.Test class SystemUtilsTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun testIsClassFound_java() { diff --git a/core/src/androidTest/java/com/emarsys/core/util/TimestampUtilsTest.kt b/core/src/androidTest/java/com/emarsys/core/util/TimestampUtilsTest.kt index 3894a262..a64c41f8 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/TimestampUtilsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/TimestampUtilsTest.kt @@ -6,17 +6,14 @@ import com.emarsys.core.notification.NotificationManagerHelper import com.emarsys.core.provider.hardwareid.HardwareIdProvider import com.emarsys.core.provider.version.VersionProvider import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext -import com.emarsys.testUtil.TimeoutUtils.timeoutRule -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import java.text.SimpleDateFormat -import java.util.* +import java.util.TimeZone class TimestampUtilsTest { @@ -31,11 +28,8 @@ class TimestampUtilsTest { private lateinit var mockVersionProvider: VersionProvider private lateinit var mockNotificationManagerHelper: NotificationManagerHelper - @JvmField - @Rule - var timeout: TestRule = timeoutRule - @Before + @BeforeEach fun setup() { mockHardwareIdProvider = mock { on { provideHardwareId() } doReturn HARDWARE_ID @@ -52,22 +46,19 @@ class TimestampUtilsTest { @Test fun testFormatTimestampWithUTC() { val deviceTimeZone = DeviceInfo( - getTargetContext(), - mockHardwareIdProvider, - mockVersionProvider, - mockLanguageProvider, - mockNotificationManagerHelper, - isAutomaticPushSendingEnabled = true, - isGooglePlayAvailable = true + getTargetContext(), + mockHardwareIdProvider, + mockVersionProvider, + mockLanguageProvider, + mockNotificationManagerHelper, + isAutomaticPushSendingEnabled = true, + isGooglePlayAvailable = true ).timezone val dateString = "2017-12-07T10:46:09.100" val parser = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS") parser.timeZone = TimeZone.getTimeZone(deviceTimeZone) val date = parser.parse(dateString) val timestamp = date!!.time - Assert.assertEquals( - "2017-12-07T10:46:09.100Z", - TimestampUtils.formatTimestampWithUTC(timestamp) - ) + TimestampUtils.formatTimestampWithUTC(timestamp) shouldBe "2017-12-07T10:46:09.100Z" } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/util/batch/BatchingShardTriggerTest.kt b/core/src/androidTest/java/com/emarsys/core/util/batch/BatchingShardTriggerTest.kt index 8fc59d8a..2ae5cde9 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/batch/BatchingShardTriggerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/batch/BatchingShardTriggerTest.kt @@ -11,15 +11,18 @@ import com.emarsys.core.shard.specification.FilterByShardIds import com.emarsys.core.util.batch.BatchingShardTrigger.RequestStrategy.PERSISTENT import com.emarsys.core.util.batch.BatchingShardTrigger.RequestStrategy.TRANSIENT import com.emarsys.core.util.predicate.Predicate -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.Mockito -import org.mockito.kotlin.* +import org.mockito.kotlin.any +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.inOrder +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.verifyNoMoreInteractions class BatchingShardTriggerTest { @@ -31,11 +34,8 @@ class BatchingShardTriggerTest { private lateinit var mockRequestManager: RequestManager private lateinit var mockConnectionWatchDog: ConnectionWatchDog - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockRepository = mock() mockPredicate = mock { diff --git a/core/src/androidTest/java/com/emarsys/core/util/batch/ListChunkerTest.kt b/core/src/androidTest/java/com/emarsys/core/util/batch/ListChunkerTest.kt index e2f0c841..df93fd3c 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/batch/ListChunkerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/batch/ListChunkerTest.kt @@ -1,49 +1,57 @@ package com.emarsys.core.util.batch import com.emarsys.core.shard.ShardModel -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Assert.assertEquals -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe + +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.mock class ListChunkerTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule private lateinit var chunker: ListChunker - @Before + @BeforeEach fun init() { chunker = ListChunker(1) } - @Test(expected = IllegalArgumentException::class) + @Test fun constructor_chunkSize_mustBeGreaterThanZero() { - ListChunker(0) + shouldThrow { + ListChunker(0) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testMap_shards_mustNotBeNull() { - chunker.map(null) + shouldThrow { + chunker.map(null) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testMap_shards_mustNotBeEmpty() { - chunker.map(listOf()) + shouldThrow { + chunker.map(listOf()) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testMap_shards_mustNotContainNullElements() { - chunker.map(listOf( - mock(ShardModel::class.java), - null, - mock(ShardModel::class.java) - )) + shouldThrow { + chunker.map( + listOf( + mock(ShardModel::class.java), + null, + mock(ShardModel::class.java) + ) + ) + } } @Test @@ -54,7 +62,7 @@ class ListChunkerTest { val expected = listOf(listOf(shard)) val result = chunker.map(input) - assertEquals(expected, result) + result shouldBe expected } @Test @@ -64,7 +72,7 @@ class ListChunkerTest { val expected = input.map { listOf(it) } val result = chunker.map(input) - assertEquals(expected, result) + result shouldBe expected } @Test @@ -76,7 +84,7 @@ class ListChunkerTest { val expected = listOf(input) val result = chunker.map(input) - assertEquals(expected, result) + result shouldBe expected } @Test @@ -88,11 +96,11 @@ class ListChunkerTest { val expected = input.chunked(3) val result = chunker.map(input) - assertEquals(expected, result) + result shouldBe expected } private fun createShardModels(size: Int): List = - (0 until size).map { mock(Any::class.java) } + (0 until size).map { mock(Any::class.java) } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/LogShardListMergerTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/LogShardListMergerTest.kt index 22e5ebe8..03244051 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/LogShardListMergerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/LogShardListMergerTest.kt @@ -7,14 +7,14 @@ import com.emarsys.core.request.model.RequestMethod import com.emarsys.core.request.model.RequestModel import com.emarsys.core.shard.ShardModel import com.emarsys.testUtil.RandomTestUtils -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import org.junit.Assert.assertEquals -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe + +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -35,11 +35,8 @@ class LogShardListMergerTest { private lateinit var uuidProvider: UUIDProvider private lateinit var deviceInfo: DeviceInfo - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { timestampProvider = mock() whenever(timestampProvider.provideTimestamp()).thenReturn(TIMESTAMP) @@ -56,41 +53,61 @@ class LogShardListMergerTest { on { sdkVersion } doReturn "1.6.1" } - merger = LogShardListMerger(timestampProvider, uuidProvider, deviceInfo, APPLICATION_CODE, MERCHANT_ID) + merger = LogShardListMerger( + timestampProvider, + uuidProvider, + deviceInfo, + APPLICATION_CODE, + MERCHANT_ID + ) } - @Test(expected = IllegalArgumentException::class) + @Test fun testMap_shards_mustNotBeNull() { - merger.map(null) + shouldThrow { + merger.map(null) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testMap_shards_mustNotContainNullElements() { - merger.map(listOf( - Mockito.mock(ShardModel::class.java), - null, - Mockito.mock(ShardModel::class.java) - )) + shouldThrow { + merger.map( + listOf( + Mockito.mock(ShardModel::class.java), + null, + Mockito.mock(ShardModel::class.java) + ) + ) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testMap_shards_mustContainAtLeastOneElement() { - merger.map(listOf()) + shouldThrow { + merger.map(listOf()) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_timestampProvider_mustNotBeNull() { - LogShardListMerger(null, uuidProvider, deviceInfo, APPLICATION_CODE, MERCHANT_ID) + shouldThrow { + LogShardListMerger(null, uuidProvider, deviceInfo, APPLICATION_CODE, MERCHANT_ID) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_uuidProvider_mustNotBeNull() { - LogShardListMerger(timestampProvider, null, deviceInfo, APPLICATION_CODE, MERCHANT_ID) + shouldThrow { + LogShardListMerger(timestampProvider, null, deviceInfo, APPLICATION_CODE, MERCHANT_ID) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_deviceInfo_mustNotBeNull() { - LogShardListMerger(timestampProvider, uuidProvider, null, APPLICATION_CODE, MERCHANT_ID) + shouldThrow { + LogShardListMerger(timestampProvider, uuidProvider, null, APPLICATION_CODE, MERCHANT_ID) + } } @Test @@ -103,14 +120,15 @@ class LogShardListMergerTest { val requestPayload = mapOf("logs" to listOf(logData)) val expectedRequestModel = requestModel(requestPayload) - assertEquals(expectedRequestModel, merger.map(listOf(shard))) + merger.map(listOf(shard)) shouldBe expectedRequestModel } @Test fun testMap_multipleElementsInList() { val shards = (1..5).map { randomShardModel() } - val logDatas = shards.map { it.data + mapOf("type" to it.type) + mapOf("deviceInfo" to createDeviceInfo()) } + val logDatas = + shards.map { it.data + mapOf("type" to it.type) + mapOf("deviceInfo" to createDeviceInfo()) } val expectedRequestModel = requestModel(mapOf("logs" to logDatas)) @@ -118,32 +136,33 @@ class LogShardListMergerTest { } private fun randomShardModel() = ShardModel( - RandomTestUtils.randomString(), - "log_${RandomTestUtils.randomString()}", - RandomTestUtils.randomMap(), - RandomTestUtils.randomInt().toLong(), - RandomTestUtils.randomInt().toLong()) + RandomTestUtils.randomString(), + "log_${RandomTestUtils.randomString()}", + RandomTestUtils.randomMap(), + RandomTestUtils.randomInt().toLong(), + RandomTestUtils.randomInt().toLong() + ) private fun requestModel(payload: Map) = RequestModel( - "https://log-dealer.eservice.emarsys.net/v1/log", - RequestMethod.POST, - payload, - mapOf(), - TIMESTAMP, - TTL, - ID + "https://log-dealer.eservice.emarsys.net/v1/log", + RequestMethod.POST, + payload, + mapOf(), + TIMESTAMP, + TTL, + ID ) private fun createDeviceInfo(): Map { return mapOf( - "platform" to "android", - "appVersion" to "1.0.0", - "sdkVersion" to "1.6.1", - "osVersion" to "8.0", - "model" to "Pixel", - "hwId" to "hardwareId", - "applicationCode" to APPLICATION_CODE, - "merchantId" to MERCHANT_ID + "platform" to "android", + "appVersion" to "1.0.0", + "sdkVersion" to "1.6.1", + "osVersion" to "8.0", + "model" to "Pixel", + "hwId" to "hardwareId", + "applicationCode" to APPLICATION_CODE, + "merchantId" to MERCHANT_ID ) } diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/LoggerTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/LoggerTest.kt index 3e3f7c47..85423d67 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/LoggerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/LoggerTest.kt @@ -3,24 +3,33 @@ package com.emarsys.core.util.log import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.database.repository.Repository import com.emarsys.core.database.repository.SqlSpecification -import com.emarsys.core.di.* +import com.emarsys.core.di.CoreComponent +import com.emarsys.core.di.FakeCoreDependencyContainer +import com.emarsys.core.di.core +import com.emarsys.core.di.setupCoreComponent +import com.emarsys.core.di.tearDownCoreComponent import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.shard.ShardModel import com.emarsys.core.storage.StringStorage import com.emarsys.core.util.log.entry.LogEntry -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.ThreadSpy -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.ArgumentCaptor -import org.mockito.kotlin.* +import org.mockito.kotlin.any +import org.mockito.kotlin.capture +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.timeout +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch @@ -32,9 +41,7 @@ class LoggerTest { const val TTL = Long.MAX_VALUE } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder private lateinit var shardRepositoryMock: Repository @@ -45,7 +52,7 @@ class LoggerTest { private lateinit var loggerMock: Logger private lateinit var mockLogLevelStorage: StringStorage - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun init() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() @@ -79,7 +86,7 @@ class LoggerTest { setupCoreComponent(dependencyContainer) } - @After + @AfterEach fun tearDown() { if (CoreComponent.isSetup()) { core().concurrentHandlerHolder.coreLooper.quitSafely() diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/AppEventLogTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/AppEventLogTest.kt index 5be3bf1c..299816e2 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/AppEventLogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/AppEventLogTest.kt @@ -1,15 +1,12 @@ package com.emarsys.core.util.log.entry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe + +import org.junit.jupiter.api.Test + class AppEventLogTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + @Test fun testTopic() { diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/CrashLogTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/CrashLogTest.kt index 39801cb1..20ac3219 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/CrashLogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/CrashLogTest.kt @@ -1,22 +1,18 @@ package com.emarsys.core.util.log.entry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + class CrashLogTest { private lateinit var crashLog: CrashLog private lateinit var exception: Exception - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun init() { exception = ConcurrentModificationException("cause of the exception") crashLog = CrashLog(exception, "testInfo") diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/InAppLogTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/InAppLogTest.kt index 8a9785bf..1f4e36cf 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/InAppLogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/InAppLogTest.kt @@ -4,11 +4,10 @@ package com.emarsys.core.util.log.entry import com.emarsys.core.di.FakeCoreDependencyContainer import com.emarsys.core.di.setupCoreComponent import com.emarsys.core.provider.uuid.UUIDProvider -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -24,9 +23,6 @@ class InAppLogTest { const val endScreenTime = 10L } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun testTopic() { diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/LogEntryKtTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/LogEntryKtTest.kt index b4af7116..b15a0e44 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/LogEntryKtTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/LogEntryKtTest.kt @@ -1,8 +1,8 @@ package com.emarsys.core.util.log.entry import com.emarsys.core.util.log.LogLevel -import io.kotlintest.shouldBe -import org.junit.Test +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.Test import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/MethodNotAlllowedTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/MethodNotAlllowedTest.kt index d484e3bd..eb2e6cae 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/MethodNotAlllowedTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/MethodNotAlllowedTest.kt @@ -1,24 +1,20 @@ package com.emarsys.core.util.log.entry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe + +import org.junit.jupiter.api.Test + class MethodNotAllowedTest { private companion object { const val testCallerMethodName = "testCallerMethodName" val testParameters = mapOf( - "parameter1" to "value1", - "parameter2" to "value2" + "parameter1" to "value1", + "parameter2" to "value2" ) } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun testGetTopic() { diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/OfflineQueueSizeTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/OfflineQueueSizeTest.kt index 284f7dd9..81645479 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/OfflineQueueSizeTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/OfflineQueueSizeTest.kt @@ -1,16 +1,12 @@ package com.emarsys.core.util.log.entry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe + +import org.junit.jupiter.api.Test + class OfflineQueueSizeTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun testTopic() { diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/RequestLogTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/RequestLogTest.kt index 8db77084..54f8429c 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/RequestLogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/RequestLogTest.kt @@ -2,12 +2,11 @@ package com.emarsys.core.util.log.entry import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.whenever @@ -23,11 +22,8 @@ class RequestLogTest { private lateinit var mockRequestModel: RequestModel private lateinit var requestLog: RequestLog - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockRequestModel = mock { on { url }.doReturn(URL("https://emarsys.com")) diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/StatusLogTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/StatusLogTest.kt index dabe7a08..e91b5393 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/StatusLogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/StatusLogTest.kt @@ -1,17 +1,16 @@ package com.emarsys.core.util.log.entry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe -class StatusLogTest{ +import org.junit.jupiter.api.Test + + +class StatusLogTest { private companion object { const val testCallerMethodName = "testCallerMethodName" val testParameters = mapOf( - "parameter1" to "value1", - "parameter2" to "value2" + "parameter1" to "value1", + "parameter2" to "value2" ) val testStatus = mapOf( "key1" to "value1", @@ -22,9 +21,6 @@ class StatusLogTest{ ) } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun testTopic() { diff --git a/core/src/androidTest/java/com/emarsys/core/util/predicate/ListSizeAtLeastTest.kt b/core/src/androidTest/java/com/emarsys/core/util/predicate/ListSizeAtLeastTest.kt index 473e2f41..7d97114a 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/predicate/ListSizeAtLeastTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/predicate/ListSizeAtLeastTest.kt @@ -1,21 +1,17 @@ package com.emarsys.core.util.predicate -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + class ListSizeAtLeastTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule private lateinit var predicate: ListSizeAtLeast - @Before + @BeforeEach fun init() { predicate = ListSizeAtLeast(5) } diff --git a/core/src/androidTest/java/com/emarsys/core/validate/JsonObjectValidatorTest.kt b/core/src/androidTest/java/com/emarsys/core/validate/JsonObjectValidatorTest.kt index 91441c3d..12308bff 100644 --- a/core/src/androidTest/java/com/emarsys/core/validate/JsonObjectValidatorTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/validate/JsonObjectValidatorTest.kt @@ -1,130 +1,137 @@ package com.emarsys.core.validate -import com.emarsys.testUtil.TimeoutUtils +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import io.kotest.matchers.types.shouldBeSameInstanceAs import org.json.JSONObject -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule + +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.mock class JsonObjectValidatorTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule lateinit var json: JSONObject - @Before + @BeforeEach fun init() { json = JSONObject() - .put("key1", "value1") - .put("key2", 3.14) + .put("key1", "value1") + .put("key2", 3.14) } - @Test(expected = IllegalArgumentException::class) + @Test fun testFrom_mustNotAcceptNull() { - JsonObjectValidator.from(null) + shouldThrow { + JsonObjectValidator.from(null) + } } @Test fun testFrom_shouldReturnValidator() { val validator = JsonObjectValidator.from(mock(JSONObject::class.java)) - Assert.assertNotEquals(null, validator) + validator shouldNotBe null } - @Test(expected = IllegalArgumentException::class) + @Test fun testHasField_mustNotAcceptNull() { - JsonObjectValidator.from(mock(JSONObject::class.java)).hasField(null) + shouldThrow { + JsonObjectValidator.from(mock(JSONObject::class.java)).hasField(null) + } } @Test fun testHasField_returnsTheSameInstance() { val validator1 = JsonObjectValidator.from(mock(JSONObject::class.java)) val validator2 = validator1.hasField("field") - Assert.assertSame(validator1, validator2) + validator1 shouldBeSameInstanceAs validator2 } @Test fun testHasField_mustReturnWithError_whenFieldIsMissing() { val errors = JsonObjectValidator - .from(JSONObject()) - .hasField("timestamp") - .validate() - Assert.assertEquals(listOf("Missing field: 'timestamp'"), errors) + .from(JSONObject()) + .hasField("timestamp") + .validate() + errors shouldBe listOf("Missing field: 'timestamp'") } @Test fun testHasField_mustReturnWithError_whenCertainFieldAreMissing() { val errors = JsonObjectValidator.from(json) - .hasField("timestamp") - .hasField("title") - .hasField("key1") - .hasField("key2") - .validate() - - Assert.assertEquals(listOf( - "Missing field: 'timestamp'", - "Missing field: 'title'" - ), errors) + .hasField("timestamp") + .hasField("title") + .hasField("key1") + .hasField("key2") + .validate() + errors shouldBe listOf( + "Missing field: 'timestamp'", + "Missing field: 'title'" + ) } - @Test(expected = IllegalArgumentException::class) + @Test fun testHasFieldAndType_mustNotAcceptNullFieldName() { - JsonObjectValidator.from(mock(JSONObject::class.java)).hasFieldWithType(null, Any::class.java) + shouldThrow { + JsonObjectValidator.from(mock(JSONObject::class.java)) + .hasFieldWithType(null, Any::class.java) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testHasFieldAndType_mustNotAcceptNullFieldType() { - JsonObjectValidator.from(mock(JSONObject::class.java)).hasFieldWithType("field", null) + shouldThrow { + JsonObjectValidator.from(mock(JSONObject::class.java)).hasFieldWithType("field", null) + } } @Test fun testHasFieldAndType_returnsTheSameInstance() { val validator1 = JsonObjectValidator.from(mock(JSONObject::class.java)) val validator2 = validator1.hasFieldWithType("field", Any::class.java) - Assert.assertSame(validator1, validator2) + validator2 shouldBeSameInstanceAs validator1 } @Test fun testHasFieldAndType_mustReturnWithError_whenFieldIsMissing() { val type = Long::class.java val errors = JsonObjectValidator - .from(JSONObject()) - .hasFieldWithType("timestamp", type) - .validate() + .from(JSONObject()) + .hasFieldWithType("timestamp", type) + .validate() - Assert.assertEquals(listOf("Missing field: 'timestamp' with type: $type"), errors) + errors shouldBe listOf("Missing field: 'timestamp' with type: $type") } @Test fun testHasFieldAndType_mustReturnWithError_whenFieldExists_butTypeIsNotTheExpected() { val type = java.lang.String::class.java val errors = JsonObjectValidator - .from(json) - .hasFieldWithType("key2", type) - .validate() - Assert.assertEquals(1, errors.size) - Assert.assertEquals(listOf("Type mismatch for key: 'key2', expected type: $type, but was: ${java.lang.Double::class.java}"), errors) + .from(json) + .hasFieldWithType("key2", type) + .validate() + errors.size shouldBe 1 + errors shouldBe listOf("Type mismatch for key: 'key2', expected type: $type, but was: ${java.lang.Double::class.java}") } @Test fun testValidate_withMultipleValidationsX() { val errors = JsonObjectValidator - .from(json) - .hasFieldWithType("key2", java.lang.Double::class.java) - .hasField("key1") - .hasFieldWithType("key1", java.lang.Integer::class.java) - .hasField("title") - .hasFieldWithType("body", java.lang.String::class.java) - .validate() - - Assert.assertEquals(listOf( - "Type mismatch for key: 'key1', expected type: ${java.lang.Integer::class.java}, but was: ${java.lang.String::class.java}", - "Missing field: 'title'", - "Missing field: 'body' with type: ${java.lang.String::class.java}" - ), errors) + .from(json) + .hasFieldWithType("key2", java.lang.Double::class.java) + .hasField("key1") + .hasFieldWithType("key1", java.lang.Integer::class.java) + .hasField("title") + .hasFieldWithType("body", java.lang.String::class.java) + .validate() + errors shouldBe listOf( + "Type mismatch for key: 'key1', expected type: ${java.lang.Integer::class.java}, but was: ${java.lang.String::class.java}", + "Missing field: 'title'", + "Missing field: 'body' with type: ${java.lang.String::class.java}" + ) } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/worker/CoreCompletionHandlerMiddlewareTest.kt b/core/src/androidTest/java/com/emarsys/core/worker/CoreCompletionHandlerMiddlewareTest.kt index 8b507569..235716f2 100644 --- a/core/src/androidTest/java/com/emarsys/core/worker/CoreCompletionHandlerMiddlewareTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/worker/CoreCompletionHandlerMiddlewareTest.kt @@ -14,17 +14,23 @@ import com.emarsys.core.request.model.RequestMethod import com.emarsys.core.request.model.RequestModel import com.emarsys.core.request.model.specification.FilterByRequestIds import com.emarsys.core.response.ResponseModel -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.ThreadSpy -import io.kotlintest.matchers.numerics.shouldBeLessThanOrEqual -import io.kotlintest.shouldBe +import io.kotest.matchers.ints.shouldBeLessThanOrEqual +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.ArgumentCaptor -import org.mockito.kotlin.* +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.capture +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.timeout +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.verifyNoMoreInteractions +import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch class CoreCompletionHandlerMiddlewareTest { @@ -37,11 +43,8 @@ class CoreCompletionHandlerMiddlewareTest { private lateinit var uiHandler: Handler private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setup() { expectedId = "expectedId" mockWorker = mock() diff --git a/core/src/androidTest/java/com/emarsys/core/worker/DefaultWorkerTest.kt b/core/src/androidTest/java/com/emarsys/core/worker/DefaultWorkerTest.kt index c262ae10..e86b7135 100644 --- a/core/src/androidTest/java/com/emarsys/core/worker/DefaultWorkerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/worker/DefaultWorkerTest.kt @@ -14,15 +14,20 @@ import com.emarsys.core.request.model.RequestMethod import com.emarsys.core.request.model.RequestModel import com.emarsys.core.testUtil.RequestModelTestUtils.createRequestModel import com.emarsys.testUtil.DatabaseTestUtils.deleteCoreDatabase -import com.emarsys.testUtil.TimeoutUtils.timeoutRule +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.* -import java.util.* +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.doNothing +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.spy +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch class DefaultWorkerTest { @@ -42,11 +47,8 @@ class DefaultWorkerTest { private lateinit var notExpiredModel: RequestModel private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - var timeout: TestRule = timeoutRule - @Before + @BeforeEach fun setup() { deleteCoreDatabase() watchDogMock = mock() @@ -100,7 +102,7 @@ class DefaultWorkerTest { whenever(worker.requestRepository.isEmpty()).thenReturn(false) worker.unlock() worker.run() - Assert.assertTrue(worker.isLocked) + worker.isLocked shouldBe true } @Test @@ -113,7 +115,7 @@ class DefaultWorkerTest { restClient, mockProxyProvider ) - Assert.assertEquals(requestRepository, worker.requestRepository) + worker.requestRepository shouldBe requestRepository } @Test @@ -127,7 +129,7 @@ class DefaultWorkerTest { restClient, mockProxyProvider ) - Assert.assertEquals(watchDog, worker.connectionWatchDog) + worker.connectionWatchDog shouldBe watchDog } @Test @@ -158,14 +160,14 @@ class DefaultWorkerTest { fun testRun_isLockedShouldBeFalse_whenThereIsNoMoreElementInTheQueue() { whenever(requestRepository.isEmpty()).thenReturn(true) worker.run() - Assert.assertFalse(worker.isLocked) + worker.isLocked shouldBe false } @Test fun testRun_isLockedShouldBeFalse_whenNotConnectedAndIsRunning() { whenever(watchDogMock.isConnected).thenReturn(false) worker.run() - Assert.assertFalse(worker.isLocked) + worker.isLocked shouldBe false } @Test @@ -178,7 +180,7 @@ class DefaultWorkerTest { worker.run() verify(worker.restClient).execute(capture(), any()) val returnedModel = firstValue - Assert.assertEquals(expectedModel, returnedModel) + returnedModel shouldBe expectedModel } } @@ -194,7 +196,7 @@ class DefaultWorkerTest { verify(requestRepository, times(3)).query(any()) verify(requestRepository, times(2)).remove(any()) verify(worker.restClient).execute(eq(notExpiredModel), any()) - Assert.assertTrue(worker.isLocked) + worker.isLocked shouldBe true } } @@ -211,7 +213,7 @@ class DefaultWorkerTest { argumentCaptor().apply { verify(worker.coreCompletionHandler, times(2)).onError(capture(), any()) val expectedIds: List = ArrayList(listOf(expiredModel1.id, expiredModel2.id)) - Assert.assertEquals(expectedIds, allValues) + allValues shouldBe expectedIds } } @@ -226,8 +228,8 @@ class DefaultWorkerTest { verify(worker.requestRepository, times(2)).query(any()) verify(worker.requestRepository, times(2)).remove(any()) verifyNoInteractions(worker.restClient) - Assert.assertTrue(worker.requestRepository.isEmpty()) - Assert.assertFalse(worker.isLocked) + worker.requestRepository.isEmpty() shouldBe true + worker.isLocked shouldBe false } } } \ No newline at end of file diff --git a/core/src/main/java/com/emarsys/core/activity/CurrentActivityWatchdog.kt b/core/src/main/java/com/emarsys/core/activity/CurrentActivityWatchdog.kt index 85f4051f..9402890b 100644 --- a/core/src/main/java/com/emarsys/core/activity/CurrentActivityWatchdog.kt +++ b/core/src/main/java/com/emarsys/core/activity/CurrentActivityWatchdog.kt @@ -7,7 +7,8 @@ import com.emarsys.core.Mockable import com.emarsys.core.provider.Property @Mockable -class CurrentActivityWatchdog(private val currentActivityProvider: Property) : ActivityLifecycleCallbacks { +class CurrentActivityWatchdog(private val currentActivityProvider: Property) : + ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {} override fun onActivityStarted(activity: Activity) {} override fun onActivityResumed(activity: Activity) { diff --git a/core/src/main/java/com/emarsys/core/connection/ConnectionProvider.kt b/core/src/main/java/com/emarsys/core/connection/ConnectionProvider.kt index 7c2eee3f..d502cbdb 100644 --- a/core/src/main/java/com/emarsys/core/connection/ConnectionProvider.kt +++ b/core/src/main/java/com/emarsys/core/connection/ConnectionProvider.kt @@ -3,7 +3,7 @@ package com.emarsys.core.connection import android.webkit.URLUtil import com.emarsys.core.Mockable import com.emarsys.core.request.model.RequestModel -import java.util.* +import java.util.Locale import javax.net.ssl.HttpsURLConnection @Mockable @@ -11,7 +11,11 @@ class ConnectionProvider { fun provideConnection(requestModel: RequestModel): HttpsURLConnection { val url = requestModel.url - require(URLUtil.isHttpsUrl(url.toString())) { "Expected HTTPS request model, but got: " + url.protocol.uppercase(Locale.getDefault()) } + require(URLUtil.isHttpsUrl(url.toString())) { + "Expected HTTPS request model, but got: " + url.protocol.uppercase( + Locale.getDefault() + ) + } return requestModel.url.openConnection() as HttpsURLConnection } } \ No newline at end of file diff --git a/core/src/main/java/com/emarsys/core/connection/ConnectionWatchDog.kt b/core/src/main/java/com/emarsys/core/connection/ConnectionWatchDog.kt index 88cb1af0..4bbd4745 100644 --- a/core/src/main/java/com/emarsys/core/connection/ConnectionWatchDog.kt +++ b/core/src/main/java/com/emarsys/core/connection/ConnectionWatchDog.kt @@ -12,7 +12,7 @@ import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.util.AndroidVersionUtils @Mockable -class ConnectionWatchDog( +open class ConnectionWatchDog( inputContext: Context, private val concurrentHandlerHolder: ConcurrentHandlerHolder ) : ConnectivityManager.NetworkCallback() { @@ -55,7 +55,7 @@ class ConnectionWatchDog( ConnectionState.DISCONNECTED } } - val isConnected: Boolean + open val isConnected: Boolean get() { return try { val network = connectivityManager.activeNetwork ?: return false @@ -74,7 +74,7 @@ class ConnectionWatchDog( } - fun registerReceiver(connectionChangeListener: ConnectionChangeListener) { + open fun registerReceiver(connectionChangeListener: ConnectionChangeListener) { try { if (AndroidVersionUtils.isOreoOrAbove) { this.connectionChangeListener = connectionChangeListener diff --git a/core/src/main/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase.kt b/core/src/main/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase.kt index 9b013b9a..0f70dacb 100644 --- a/core/src/main/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase.kt +++ b/core/src/main/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase.kt @@ -1,13 +1,12 @@ package com.emarsys.core.database -import android.database.sqlite.SQLiteDatabase import android.content.ContentValues import android.database.Cursor +import android.database.sqlite.SQLiteDatabase import com.emarsys.core.Mockable import com.emarsys.core.database.trigger.TriggerEvent import com.emarsys.core.database.trigger.TriggerKey import com.emarsys.core.database.trigger.TriggerType -import java.util.ArrayList @Mockable class DelegatingCoreSQLiteDatabase( diff --git a/core/src/main/java/com/emarsys/core/database/repository/specification/Everything.kt b/core/src/main/java/com/emarsys/core/database/repository/specification/Everything.kt index 4755979a..7e322e72 100644 --- a/core/src/main/java/com/emarsys/core/database/repository/specification/Everything.kt +++ b/core/src/main/java/com/emarsys/core/database/repository/specification/Everything.kt @@ -1,7 +1,6 @@ package com.emarsys.core.database.repository.specification -import com.emarsys.core.Mockable import com.emarsys.core.database.repository.AbstractSqlSpecification -@Mockable + class Everything : AbstractSqlSpecification() \ No newline at end of file diff --git a/core/src/main/java/com/emarsys/core/device/DeviceInfo.kt b/core/src/main/java/com/emarsys/core/device/DeviceInfo.kt index a53712e8..6207df57 100644 --- a/core/src/main/java/com/emarsys/core/device/DeviceInfo.kt +++ b/core/src/main/java/com/emarsys/core/device/DeviceInfo.kt @@ -18,13 +18,13 @@ import java.util.Locale @Mockable data class DeviceInfo( - private val context: Context, - private val hardwareIdProvider: HardwareIdProvider, - private val versionProvider: VersionProvider, - private val languageProvider: LanguageProvider, - val notificationSettings: NotificationSettings, - val isAutomaticPushSendingEnabled: Boolean, - val isGooglePlayAvailable: Boolean + private val context: Context, + private val hardwareIdProvider: HardwareIdProvider, + private val versionProvider: VersionProvider, + private val languageProvider: LanguageProvider, + val notificationSettings: NotificationSettings, + val isAutomaticPushSendingEnabled: Boolean, + val isGooglePlayAvailable: Boolean ) { companion object { @@ -42,7 +42,8 @@ data class DeviceInfo( val model: String = Build.MODEL val osVersion: String = Build.VERSION.RELEASE val displayMetrics: DisplayMetrics = Resources.getSystem().displayMetrics - val isDebugMode: Boolean = 0 != context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE + val isDebugMode: Boolean = + 0 != context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE var sdkVersion: String = versionProvider.provideSdkVersion() val applicationVersion: String? get() { @@ -59,23 +60,23 @@ data class DeviceInfo( val deviceInfoPayload: String get() = JSONObject( - mapOf( - "notificationSettings" to mapOf( - parseChannelSettings(), - "importance" to notificationSettings.importance, - "areNotificationsEnabled" to notificationSettings.areNotificationsEnabled - ), - "hwid" to hardwareId, - "platform" to platform, - "language" to language, - "timezone" to timezone, - "manufacturer" to manufacturer, - "model" to model, - "osVersion" to osVersion, - "displayMetrics" to "${displayMetrics.widthPixels}x${displayMetrics.heightPixels}", - "sdkVersion" to sdkVersion, - "appVersion" to applicationVersion - ) + mapOf( + "notificationSettings" to mapOf( + parseChannelSettings(), + "importance" to notificationSettings.importance, + "areNotificationsEnabled" to notificationSettings.areNotificationsEnabled + ), + "hwid" to hardwareId, + "platform" to platform, + "language" to language, + "timezone" to timezone, + "manufacturer" to manufacturer, + "model" to model, + "osVersion" to osVersion, + "displayMetrics" to "${displayMetrics.widthPixels}x${displayMetrics.heightPixels}", + "sdkVersion" to sdkVersion, + "appVersion" to applicationVersion + ) ).toString() private fun parseChannelSettings(): Pair { diff --git a/core/src/main/java/com/emarsys/core/device/HardwareIdentification.kt b/core/src/main/java/com/emarsys/core/device/HardwareIdentification.kt index 56cd0b12..0c8844a9 100644 --- a/core/src/main/java/com/emarsys/core/device/HardwareIdentification.kt +++ b/core/src/main/java/com/emarsys/core/device/HardwareIdentification.kt @@ -1,3 +1,11 @@ package com.emarsys.core.device -data class HardwareIdentification(val hardwareId: String, val encryptedHardwareId: String? = null, val salt: String? = null, val iv: String? = null) \ No newline at end of file +import com.emarsys.core.Mockable + +@Mockable +data class HardwareIdentification( + val hardwareId: String, + val encryptedHardwareId: String? = null, + val salt: String? = null, + val iv: String? = null +) \ No newline at end of file diff --git a/core/src/main/java/com/emarsys/core/device/LanguageProvider.java b/core/src/main/java/com/emarsys/core/device/LanguageProvider.java index 9a24d2a0..3b4e84a0 100644 --- a/core/src/main/java/com/emarsys/core/device/LanguageProvider.java +++ b/core/src/main/java/com/emarsys/core/device/LanguageProvider.java @@ -1,9 +1,11 @@ package com.emarsys.core.device; +import com.emarsys.core.Mockable; import com.emarsys.core.util.Assert; import java.util.Locale; +@Mockable public class LanguageProvider { public String provideLanguage(Locale locale) { diff --git a/core/src/main/java/com/emarsys/core/provider/timestamp/TimestampProvider.java b/core/src/main/java/com/emarsys/core/provider/timestamp/TimestampProvider.java index db769282..3e10c4bf 100644 --- a/core/src/main/java/com/emarsys/core/provider/timestamp/TimestampProvider.java +++ b/core/src/main/java/com/emarsys/core/provider/timestamp/TimestampProvider.java @@ -1,5 +1,8 @@ package com.emarsys.core.provider.timestamp; +import com.emarsys.core.Mockable; + +@Mockable public class TimestampProvider { public long provideTimestamp() { return System.currentTimeMillis(); diff --git a/core/src/main/java/com/emarsys/core/provider/uuid/UUIDProvider.java b/core/src/main/java/com/emarsys/core/provider/uuid/UUIDProvider.java index ac9d2175..dacf78c1 100644 --- a/core/src/main/java/com/emarsys/core/provider/uuid/UUIDProvider.java +++ b/core/src/main/java/com/emarsys/core/provider/uuid/UUIDProvider.java @@ -1,7 +1,10 @@ package com.emarsys.core.provider.uuid; +import com.emarsys.core.Mockable; + import java.util.UUID; +@Mockable public class UUIDProvider { public String provideId() { diff --git a/core/src/main/java/com/emarsys/core/provider/version/VersionProvider.java b/core/src/main/java/com/emarsys/core/provider/version/VersionProvider.java index 16e1a537..b06cda08 100644 --- a/core/src/main/java/com/emarsys/core/provider/version/VersionProvider.java +++ b/core/src/main/java/com/emarsys/core/provider/version/VersionProvider.java @@ -1,7 +1,9 @@ package com.emarsys.core.provider.version; import com.emarsys.core.BuildConfig; +import com.emarsys.core.Mockable; +@Mockable public class VersionProvider { public String provideSdkVersion() { diff --git a/core/src/main/java/com/emarsys/core/request/RequestTask.kt b/core/src/main/java/com/emarsys/core/request/RequestTask.kt index 9f0261b1..05cb4131 100644 --- a/core/src/main/java/com/emarsys/core/request/RequestTask.kt +++ b/core/src/main/java/com/emarsys/core/request/RequestTask.kt @@ -20,7 +20,7 @@ import java.nio.charset.StandardCharsets import javax.net.ssl.HttpsURLConnection @Mockable -class RequestTask( +open class RequestTask( private val requestModel: RequestModel, private val connectionProvider: ConnectionProvider, private val timestampProvider: TimestampProvider @@ -30,7 +30,7 @@ class RequestTask( private const val TIMEOUT = 30000 } - fun execute(): Try { + open fun execute(): Try { var responseModel: ResponseModel? = null var exception: Exception? = null val dbEnd = timestampProvider.provideTimestamp() diff --git a/core/src/main/java/com/emarsys/core/request/model/CompositeRequestModel.kt b/core/src/main/java/com/emarsys/core/request/model/CompositeRequestModel.kt index b158d791..5c1ece51 100644 --- a/core/src/main/java/com/emarsys/core/request/model/CompositeRequestModel.kt +++ b/core/src/main/java/com/emarsys/core/request/model/CompositeRequestModel.kt @@ -1,10 +1,9 @@ package com.emarsys.core.request.model -import com.emarsys.core.Mockable import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider -@Mockable + class CompositeRequestModel( id: String, url: String, diff --git a/core/src/main/java/com/emarsys/core/request/model/RequestModel.kt b/core/src/main/java/com/emarsys/core/request/model/RequestModel.kt index 4caf75f3..e4feebb5 100644 --- a/core/src/main/java/com/emarsys/core/request/model/RequestModel.kt +++ b/core/src/main/java/com/emarsys/core/request/model/RequestModel.kt @@ -8,15 +8,18 @@ import com.emarsys.core.util.Assert import java.io.Serializable import java.net.URL + @Mockable -class RequestModel @JvmOverloads constructor(private val urlStr: String, - val method: RequestMethod, - val payload: Map?, - val headers: Map, - val timestamp: Long, - val ttl: Long, - val id: String, - val url: URL = URL(urlStr)) : Serializable { +open class RequestModel @JvmOverloads constructor( + private val urlStr: String, + val method: RequestMethod, + val payload: Map?, + val headers: Map, + val timestamp: Long, + val ttl: Long, + val id: String, + val url: URL = URL(urlStr) +) : Serializable { open class Builder { protected lateinit var url: String diff --git a/core/src/main/java/com/emarsys/core/response/ResponseModel.kt b/core/src/main/java/com/emarsys/core/response/ResponseModel.kt index 2358cddf..1aaf8217 100644 --- a/core/src/main/java/com/emarsys/core/response/ResponseModel.kt +++ b/core/src/main/java/com/emarsys/core/response/ResponseModel.kt @@ -6,7 +6,6 @@ import com.emarsys.core.request.model.RequestModel import org.json.JSONException import org.json.JSONObject import java.net.HttpCookie -import java.util.* @Mockable data class ResponseModel( @@ -31,7 +30,7 @@ data class ResponseModel( var result : JSONObject? = null if (body != null) { try { - result = JSONObject(body!!) + result = JSONObject(body) } catch (ignored: JSONException) { } } diff --git a/core/src/main/java/com/emarsys/core/shard/ShardModel.java b/core/src/main/java/com/emarsys/core/shard/ShardModel.java index 51a2bd7c..ea9b17c7 100644 --- a/core/src/main/java/com/emarsys/core/shard/ShardModel.java +++ b/core/src/main/java/com/emarsys/core/shard/ShardModel.java @@ -1,5 +1,6 @@ package com.emarsys.core.shard; +import com.emarsys.core.Mockable; import com.emarsys.core.provider.timestamp.TimestampProvider; import com.emarsys.core.provider.uuid.UUIDProvider; import com.emarsys.core.util.Assert; @@ -7,6 +8,7 @@ import java.util.HashMap; import java.util.Map; +@Mockable public class ShardModel { final private String id; final private String type; diff --git a/core/src/main/java/com/emarsys/core/util/log/entry/RequestLog.kt b/core/src/main/java/com/emarsys/core/util/log/entry/RequestLog.kt index 92c9afb0..3265ba57 100644 --- a/core/src/main/java/com/emarsys/core/util/log/entry/RequestLog.kt +++ b/core/src/main/java/com/emarsys/core/util/log/entry/RequestLog.kt @@ -3,6 +3,7 @@ package com.emarsys.core.util.log.entry import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel + class RequestLog(responseModel: ResponseModel, inDatabaseTimeEnd: Long, updatedRequestModel: RequestModel? = null) : LogEntry { override val topic: String get() = "log_request" diff --git a/emarsys-e2e-test/build.gradle.kts b/emarsys-e2e-test/build.gradle.kts index 71c2d34b..a3bde3d3 100644 --- a/emarsys-e2e-test/build.gradle.kts +++ b/emarsys-e2e-test/build.gradle.kts @@ -12,11 +12,29 @@ dependencies { implementation(project(":predict")) androidTestImplementation(project(":testUtils")) + + coreLibraryDesugaring(libs.android.tools.desugar) } android { namespace = "com.emarsys.test.e2e" defaultConfig { compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + + multiDexEnabled = true + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + testInstrumentationRunnerArgument( + "runnerBuilder", + "de.mannodermaus.junit5.AndroidJUnit5Builder" + ) + } + compileOptions { + isCoreLibraryDesugaringEnabled = true + } + packaging { + resources { + excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + } } } diff --git a/emarsys-e2e-test/src/androidTest/java/com/emarsys/EmarsysE2ETests.kt b/emarsys-e2e-test/src/androidTest/java/com/emarsys/EmarsysE2ETests.kt index e48d5664..1fa25f2e 100644 --- a/emarsys-e2e-test/src/androidTest/java/com/emarsys/EmarsysE2ETests.kt +++ b/emarsys-e2e-test/src/androidTest/java/com/emarsys/EmarsysE2ETests.kt @@ -12,22 +12,24 @@ import com.emarsys.mobileengage.api.geofence.Trigger import com.emarsys.mobileengage.api.geofence.TriggerType import com.emarsys.mobileengage.api.inbox.Message import com.emarsys.testUtil.* -import com.emarsys.testUtil.rules.ConnectionRule -import com.emarsys.testUtil.rules.DuplicatedThreadRule -import com.emarsys.testUtil.rules.RetryRule -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe +import com.emarsys.testUtil.rules.ConnectionExtension +import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe import org.json.JSONObject -import org.junit.After -import org.junit.Ignore -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Disabled + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.extension.RegisterExtension +import org.junitpioneer.jupiter.RetryingTest + import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import com.emarsys.mobileengage.api.geofence.Geofence as MEGeofence - +@ExtendWith(DuplicatedThreadExtension::class) class EmarsysE2ETests { companion object { @@ -42,28 +44,17 @@ class EmarsysE2ETests { private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.longTimeoutRule - - @Rule - @JvmField - val retryRule: RetryRule = RetryUtils.retryRule - - @Rule - @JvmField - val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") - - @Rule @JvmField - val connectionRule = ConnectionRule(application) + @RegisterExtension + var connectionExtension: ConnectionExtension = ConnectionExtension(application) - @After + @AfterEach fun tearDown() { E2ETestUtils.tearDownEmarsys(application) } @Test + @RetryingTest(3) fun testChangeApplicationCode() { setup(OLD_APPLICATION_CODE) @@ -82,6 +73,7 @@ class EmarsysE2ETests { } @Test + @RetryingTest(3) fun testChangeApplicationCodeFromNull() { setup(null) @@ -100,6 +92,7 @@ class EmarsysE2ETests { } @Test + @RetryingTest(3) fun testChangeApplicationCodeToNull() { var disabled = true setup(APPLICATION_CODE) @@ -123,6 +116,7 @@ class EmarsysE2ETests { } @Test + @RetryingTest(3) fun testInbox_addTag_removeTag() { setup(APPLICATION_CODE) @@ -166,7 +160,8 @@ class EmarsysE2ETests { } @Test - @Ignore("Test is too flaky to run on pipeline") + @Disabled("Test is too flaky to run on pipeline") + @RetryingTest(3) fun testGeofence() { setup(APPLICATION_CODE) RetryUtil.retry { diff --git a/emarsys-firebase/build.gradle.kts b/emarsys-firebase/build.gradle.kts index 7e1517ed..2ea33f05 100644 --- a/emarsys-firebase/build.gradle.kts +++ b/emarsys-firebase/build.gradle.kts @@ -11,14 +11,32 @@ dependencies { implementation(project(":mobile-engage")) implementation(project(":mobile-engage-api")) - api(libs.google.fcm, { exclude(group = "androidx") }) + api(libs.google.firebase.messaging) { exclude(group = "androidx") } androidTestImplementation(project(":testUtils")) + + coreLibraryDesugaring(libs.android.tools.desugar) } android { namespace = "com.emarsys.firebase" defaultConfig { compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + + multiDexEnabled = true + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + testInstrumentationRunnerArgument( + "runnerBuilder", + "de.mannodermaus.junit5.AndroidJUnit5Builder" + ) + } + compileOptions { + isCoreLibraryDesugaringEnabled = true + } + packaging { + resources { + excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + } } } diff --git a/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceTest.kt b/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceTest.kt index 681e2353..990f81de 100644 --- a/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceTest.kt +++ b/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceTest.kt @@ -12,20 +12,21 @@ import com.emarsys.mobileengage.push.PushInternal import com.emarsys.testUtil.FeatureTestUtils import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.ReflectionTestUtils -import com.emarsys.testUtil.TimeoutUtils -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.* +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.spy +import org.mockito.kotlin.timeout +import org.mockito.kotlin.times +import org.mockito.kotlin.verify class EmarsysFirebaseMessagingServiceTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application @@ -36,7 +37,7 @@ class EmarsysFirebaseMessagingServiceTest { private lateinit var spyCoreHandler: SdkHandler private lateinit var emarsysFirebaseMessagingService: EmarsysFirebaseMessagingService - @Before + @BeforeEach fun setUp() { emarsysFirebaseMessagingService = EmarsysFirebaseMessagingService() mockPushInternal = mock() @@ -50,7 +51,7 @@ class EmarsysFirebaseMessagingServiceTest { ) } - @After + @AfterEach fun tearDown() { tearDownMobileEngageComponent() FeatureTestUtils.resetFeatures() diff --git a/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceUtilsTest.kt b/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceUtilsTest.kt index c446f068..cbeb81ed 100644 --- a/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceUtilsTest.kt +++ b/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceUtilsTest.kt @@ -6,14 +6,14 @@ import com.emarsys.fake.FakeFirebaseDependencyContainer import com.emarsys.mobileengage.di.setupMobileEngageComponent import com.emarsys.testUtil.InstrumentationRegistry import com.google.firebase.messaging.RemoteMessage -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Test +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test class EmarsysFirebaseMessagingServiceUtilsTest { private lateinit var context: Context - @Before + @BeforeEach fun init() { context = InstrumentationRegistry.getTargetContext() setupMobileEngageComponent( @@ -25,7 +25,10 @@ class EmarsysFirebaseMessagingServiceUtilsTest { fun handleMessage_shouldReturnFalse_ifMessage_isNotEmarsysMessage() { val testRemoteMessage = RemoteMessage(Bundle.EMPTY) - EmarsysFirebaseMessagingServiceUtils.handleMessage(context, testRemoteMessage) shouldBe false + EmarsysFirebaseMessagingServiceUtils.handleMessage( + context, + testRemoteMessage + ) shouldBe false } @Test diff --git a/emarsys-firebase/src/main/java/com/emarsys/service/EmarsysFirebaseMessagingServiceUtils.kt b/emarsys-firebase/src/main/java/com/emarsys/service/EmarsysFirebaseMessagingServiceUtils.kt index 8faacbbb..cda3c641 100644 --- a/emarsys-firebase/src/main/java/com/emarsys/service/EmarsysFirebaseMessagingServiceUtils.kt +++ b/emarsys-firebase/src/main/java/com/emarsys/service/EmarsysFirebaseMessagingServiceUtils.kt @@ -1,7 +1,6 @@ package com.emarsys.service import android.content.Context -import com.emarsys.core.Mockable import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.mobileengage.di.mobileEngage import com.emarsys.mobileengage.service.MessagingServiceUtils @@ -9,7 +8,7 @@ import com.emarsys.mobileengage.service.MessagingServiceUtils.handleMessage import com.emarsys.mobileengage.service.MessagingServiceUtils.isMobileEngageNotification import com.google.firebase.messaging.RemoteMessage -@Mockable + object EmarsysFirebaseMessagingServiceUtils { var MESSAGE_FILTER = MessagingServiceUtils.MESSAGE_FILTER var V2_MESSAGE_FILTER = MessagingServiceUtils.V2_MESSAGE_FILTER diff --git a/emarsys-huawei/build.gradle.kts b/emarsys-huawei/build.gradle.kts index 350ffe3a..c6fea274 100644 --- a/emarsys-huawei/build.gradle.kts +++ b/emarsys-huawei/build.gradle.kts @@ -15,11 +15,29 @@ dependencies { api(libs.huawei.agconnect.core) api(libs.huawei.hms.push) androidTestImplementation(project(":testUtils")) + + coreLibraryDesugaring(libs.android.tools.desugar) } android { namespace = "com.emarsys.huawei" defaultConfig { compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + + multiDexEnabled = true + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + testInstrumentationRunnerArgument( + "runnerBuilder", + "de.mannodermaus.junit5.AndroidJUnit5Builder" + ) + } + compileOptions { + isCoreLibraryDesugaringEnabled = true + } + packaging { + resources { + excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + } } } diff --git a/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceTest.kt b/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceTest.kt index 7bcde86c..c0a6b68f 100644 --- a/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceTest.kt +++ b/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceTest.kt @@ -13,19 +13,20 @@ import com.emarsys.mobileengage.push.PushInternal import com.emarsys.testUtil.FeatureTestUtils import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.ReflectionTestUtils -import com.emarsys.testUtil.TimeoutUtils -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.* +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.spy +import org.mockito.kotlin.timeout +import org.mockito.kotlin.times +import org.mockito.kotlin.verify class EmarsysHuaweiMessagingServiceTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application @@ -36,7 +37,7 @@ class EmarsysHuaweiMessagingServiceTest { private lateinit var emarsysHuaweiMessagingService: EmarsysHuaweiMessagingService private lateinit var spyCoreHandler: SdkHandler - @Before + @BeforeEach fun setUp() { mockPushInternal = mock() @@ -51,7 +52,7 @@ class EmarsysHuaweiMessagingServiceTest { emarsysHuaweiMessagingService = EmarsysHuaweiMessagingService() } - @After + @AfterEach fun tearDown() { tearDownMobileEngageComponent() FeatureTestUtils.resetFeatures() diff --git a/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceUtilsTest.kt b/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceUtilsTest.kt index a4604b04..c6c32a60 100644 --- a/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceUtilsTest.kt +++ b/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceUtilsTest.kt @@ -6,14 +6,14 @@ import com.emarsys.fake.FakeHuaweiDependencyContainer import com.emarsys.mobileengage.di.setupMobileEngageComponent import com.emarsys.testUtil.InstrumentationRegistry import com.huawei.hms.push.RemoteMessage -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Test +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test class EmarsysHuaweiMessagingServiceUtilsTest { private lateinit var context: Context - @Before + @BeforeEach fun init() { context = InstrumentationRegistry.getTargetContext() setupMobileEngageComponent( diff --git a/emarsys-sdk/build.gradle.kts b/emarsys-sdk/build.gradle.kts index caac7482..cc70e838 100644 --- a/emarsys-sdk/build.gradle.kts +++ b/emarsys-sdk/build.gradle.kts @@ -17,12 +17,30 @@ dependencies { implementation(project(":emarsys")) androidTestImplementation(project(":testUtils")) + + coreLibraryDesugaring(libs.android.tools.desugar) } android { namespace = "com.emarsys" defaultConfig { compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + + multiDexEnabled = true + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + testInstrumentationRunnerArgument( + "runnerBuilder", + "de.mannodermaus.junit5.AndroidJUnit5Builder" + ) + } + compileOptions { + isCoreLibraryDesugaringEnabled = true + } + packaging { + resources { + excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + } } } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/DefaultInboxIntegrationTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/DefaultInboxIntegrationTest.kt index 283f35b2..939683c3 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/DefaultInboxIntegrationTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/DefaultInboxIntegrationTest.kt @@ -2,7 +2,6 @@ package com.emarsys import android.app.Application import com.emarsys.config.EmarsysConfig -import com.emarsys.core.api.result.Try import com.emarsys.core.device.DeviceInfo import com.emarsys.core.device.LanguageProvider import com.emarsys.core.notification.NotificationManagerHelper @@ -10,28 +9,25 @@ import com.emarsys.core.provider.hardwareid.HardwareIdProvider import com.emarsys.core.provider.version.VersionProvider import com.emarsys.di.DefaultEmarsysComponent import com.emarsys.di.DefaultEmarsysDependencies -import com.emarsys.mobileengage.api.inbox.InboxResult import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.IntegrationTestUtils -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import com.emarsys.testUtil.rules.ConnectionRule -import com.emarsys.testUtil.rules.DuplicatedThreadRule -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import com.emarsys.testUtil.rules.ConnectionExtension +import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junit.jupiter.api.extension.RegisterExtension import org.mockito.ArgumentMatchers.any import org.mockito.Mockito.mock import java.util.concurrent.CountDownLatch -import kotlin.reflect.KMutableProperty0 -import kotlin.reflect.jvm.isAccessible +@ExtendWith(DuplicatedThreadExtension::class) class DefaultInboxIntegrationTest { companion object { @@ -49,43 +45,35 @@ class DefaultInboxIntegrationTest { private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @Rule @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + @RegisterExtension + var connectionExtension: ConnectionExtension = ConnectionExtension(application) - @Rule - @JvmField - val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") - - @Rule - @JvmField - val connectionRule = ConnectionRule(application) - - @Before + @BeforeEach fun setup() { DatabaseTestUtils.deleteCoreDatabase() baseConfig = EmarsysConfig.Builder() - .application(application) - .applicationCode(APP_ID) - .build() + .application(application) + .applicationCode(APP_ID) + .build() errorCause = null latch = CountDownLatch(1) val deviceInfo = DeviceInfo( - application, - mock(HardwareIdProvider::class.java).apply { - whenever(provideHardwareId()).thenReturn("inboxv1_integration_hwid") - }, - mock(VersionProvider::class.java).apply { - whenever(provideSdkVersion()).thenReturn(SDK_VERSION) - }, - mock(LanguageProvider::class.java).apply { - whenever(provideLanguage(any())).thenReturn(LANGUAGE) - }, - mock(NotificationManagerHelper::class.java), - isAutomaticPushSendingEnabled = true, - isGooglePlayAvailable = true + application, + mock(HardwareIdProvider::class.java).apply { + whenever(provideHardwareId()).thenReturn("inboxv1_integration_hwid") + }, + mock(VersionProvider::class.java).apply { + whenever(provideSdkVersion()).thenReturn(SDK_VERSION) + }, + mock(LanguageProvider::class.java).apply { + whenever(provideLanguage(any())).thenReturn(LANGUAGE) + }, + mock(NotificationManagerHelper::class.java), + isAutomaticPushSendingEnabled = true, + isGooglePlayAvailable = true ) DefaultEmarsysDependencies(baseConfig, object : DefaultEmarsysComponent(baseConfig) { @@ -98,7 +86,7 @@ class DefaultInboxIntegrationTest { IntegrationTestUtils.doLogin(2575) } - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys(application) } @@ -106,7 +94,7 @@ class DefaultInboxIntegrationTest { @Test fun testFetchInboxMessages() { val latch = CountDownLatch(1) - Emarsys.messageInbox.fetchMessages { + Emarsys.messageInbox.fetchMessages { it.errorCause shouldBe null it.result shouldNotBe null latch.countDown() diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/EmarsysTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/EmarsysTest.kt index 852b75a0..b43de131 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/EmarsysTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/EmarsysTest.kt @@ -63,15 +63,17 @@ import com.emarsys.testUtil.CollectionTestUtils.numberOfElementsIn import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.IntegrationTestUtils import com.emarsys.testUtil.ReflectionTestUtils.getInstanceField -import com.emarsys.testUtil.TimeoutUtils -import com.emarsys.testUtil.rules.DuplicatedThreadRule -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.* -import org.junit.rules.TestRule +import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith import org.mockito.kotlin.* import java.util.concurrent.CountDownLatch +@ExtendWith(DuplicatedThreadExtension::class) class EmarsysTest { companion object { private const val APPLICATION_CODE = "EMS11-C3FD3" @@ -82,14 +84,6 @@ class EmarsysTest { private const val OPEN_ID_TOKEN = "testIdToken" } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Rule - @JvmField - val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") - private lateinit var mockActivityLifecycleWatchdog: ActivityLifecycleWatchdog private lateinit var mockCurrentActivityWatchdog: CurrentActivityWatchdog private lateinit var mockCoreSQLiteDatabase: CoreSQLiteDatabase @@ -136,132 +130,127 @@ class EmarsysTest { private lateinit var latch: CountDownLatch private lateinit var predictResultListenerCallback: (Try>) -> Unit - @Before + @BeforeEach fun setUp() { - try { - application = spy(getTargetContext().applicationContext as Application) - completionListener = mock() - mockResultListener = mock() - mockActivityLifecycleWatchdog = mock() - mockCurrentActivityWatchdog = mock() - mockCoreSQLiteDatabase = mock() - mockMobileEngageInternal = mock() - mockDeepLinkInternal = mock() - mockDeepLinkApi = mock() - mockLoggingDeepLinkApi = mock() - mockEventServiceInternal = mock() - mockEventServiceApi = mock() - mockLoggingEventServiceApi = mock() - mockClientServiceApi = mock() - mockPredictShardTrigger = mock() - mockLogShardTrigger = mock() - mockLanguageProvider = mock() - mockVersionProvider = mock() - inappEventHandler = mock() - mockDeviceInfoPayloadStorage = mock() - mockContactFieldValueStorage = mock() - mockContactTokenStorage = mock() - mockClientStateStorage = mock() - mockNotificationManagerHelper = mock() - - baseConfig = createConfig().build() - mobileEngageConfig = createConfig() - .applicationCode(APPLICATION_CODE) - .build() - predictConfig = createConfig() - .merchantId(MERCHANT_ID) - .build() - mobileEngageAndPredictConfig = createConfig() - .applicationCode(APPLICATION_CODE) - .merchantId(MERCHANT_ID) - .build() - mockRequestContext = mock() - mockHardwareIdProvider = mock() - mockMobileEngageApi = mock() - mockLoggingMobileEngageApi = mock() - mockInApp = mock() - mockLoggingInApp = mock() - mockPush = mock() - mockPredict = mock() - mockLoggingPredict = mock() - mockPredictRestricted = mock() - mockConfig = mock() - mockMessageInbox = mock() - mockLogic = mock() - mockRecommendationFilter = mock() - predictResultListenerCallback = mock() - whenever(mockNotificationManagerHelper.channelSettings).thenReturn( - listOf( - ChannelSettings(channelId = "channelId") - ) - ) - whenever(mockNotificationManagerHelper.importance).thenReturn(-1000) - whenever(mockNotificationManagerHelper.areNotificationsEnabled).thenReturn(false) - whenever(mockHardwareIdProvider.provideHardwareId()).thenReturn("hwid") - whenever(mockLanguageProvider.provideLanguage(any())).thenReturn( - "language" + application = spy(getTargetContext().applicationContext as Application) + completionListener = mock() + mockResultListener = mock() + mockActivityLifecycleWatchdog = mock() + mockCurrentActivityWatchdog = mock() + mockCoreSQLiteDatabase = mock() + mockMobileEngageInternal = mock() + mockDeepLinkInternal = mock() + mockDeepLinkApi = mock() + mockLoggingDeepLinkApi = mock() + mockEventServiceInternal = mock() + mockEventServiceApi = mock() + mockLoggingEventServiceApi = mock() + mockClientServiceApi = mock() + mockPredictShardTrigger = mock() + mockLogShardTrigger = mock() + mockLanguageProvider = mock() + mockVersionProvider = mock() + inappEventHandler = mock() + mockDeviceInfoPayloadStorage = mock() + mockContactFieldValueStorage = mock() + mockContactTokenStorage = mock() + mockClientStateStorage = mock() + mockNotificationManagerHelper = mock() + + baseConfig = createConfig().build() + mobileEngageConfig = createConfig() + .applicationCode(APPLICATION_CODE) + .build() + predictConfig = createConfig() + .merchantId(MERCHANT_ID) + .build() + mobileEngageAndPredictConfig = createConfig() + .applicationCode(APPLICATION_CODE) + .merchantId(MERCHANT_ID) + .build() + mockRequestContext = mock() + mockHardwareIdProvider = mock() + mockMobileEngageApi = mock() + mockLoggingMobileEngageApi = mock() + mockInApp = mock() + mockLoggingInApp = mock() + mockPush = mock() + mockPredict = mock() + mockLoggingPredict = mock() + mockPredictRestricted = mock() + mockConfig = mock() + mockMessageInbox = mock() + mockLogic = mock() + mockRecommendationFilter = mock() + predictResultListenerCallback = mock() + whenever(mockNotificationManagerHelper.channelSettings).thenReturn( + listOf( + ChannelSettings(channelId = "channelId") ) - whenever(mockVersionProvider.provideSdkVersion()).thenReturn("version") + ) + whenever(mockNotificationManagerHelper.importance).thenReturn(-1000) + whenever(mockNotificationManagerHelper.areNotificationsEnabled).thenReturn(false) + whenever(mockHardwareIdProvider.provideHardwareId()).thenReturn("hwid") + whenever(mockLanguageProvider.provideLanguage(any())).thenReturn( + "language" + ) + whenever(mockVersionProvider.provideSdkVersion()).thenReturn("version") - deviceInfo = DeviceInfo( - application, mockHardwareIdProvider, mockVersionProvider, - mockLanguageProvider, mockNotificationManagerHelper, - isAutomaticPushSendingEnabled = true, isGooglePlayAvailable = true - ) + deviceInfo = DeviceInfo( + application, mockHardwareIdProvider, mockVersionProvider, + mockLanguageProvider, mockNotificationManagerHelper, + isAutomaticPushSendingEnabled = true, isGooglePlayAvailable = true + ) - whenever(mockRequestContext.applicationCode).thenReturn(APPLICATION_CODE) - whenever(mockRequestContext.deviceInfo).thenReturn(deviceInfo) - whenever(mockVersionProvider.provideSdkVersion()).thenReturn(SDK_VERSION) - whenever(mockContactFieldValueStorage.get()).thenReturn("test@test.com") - whenever(mockContactTokenStorage.get()).thenReturn("contactToken") - - whenever(mockDeviceInfoPayloadStorage.get()).thenReturn("deviceInfo.deviceInfoPayload") - - setupEmarsysComponent( - FakeDependencyContainer( - activityLifecycleWatchdog = mockActivityLifecycleWatchdog, - currentActivityWatchdog = mockCurrentActivityWatchdog, - coreSQLiteDatabase = mockCoreSQLiteDatabase, - deviceInfo = deviceInfo, - logShardTrigger = mockLogShardTrigger, - mobileEngageInternal = mockMobileEngageInternal, - loggingMobileEngageInternal = mockMobileEngageInternal, - deepLinkInternal = mockDeepLinkInternal, - eventServiceInternal = mockEventServiceInternal, - loggingEventServiceInternal = mockEventServiceInternal, - clientService = mockClientServiceApi, - loggingClientService = mockClientServiceApi, - requestContext = mockRequestContext, - predictShardTrigger = mockPredictShardTrigger, - deviceInfoPayloadStorage = mockDeviceInfoPayloadStorage, - contactFieldValueStorage = mockContactFieldValueStorage, - contactTokenStorage = mockContactTokenStorage, - clientStateStorage = mockClientStateStorage, - responseHandlersProcessor = ResponseHandlersProcessor(ArrayList()), - mobileEngage = mockMobileEngageApi, - loggingMobileEngage = mockLoggingMobileEngageApi, - inApp = mockInApp, - loggingInApp = mockLoggingInApp, - push = mockPush, - predict = mockPredict, - loggingPredict = mockLoggingPredict, - predictRestricted = mockPredictRestricted, - loggingPredictRestricted = mockPredictRestricted, - config = mockConfig, - eventService = mockEventServiceApi, - loggingEventService = mockLoggingEventServiceApi, - deepLink = mockDeepLinkApi, - logger = mock() - ) + whenever(mockRequestContext.applicationCode).thenReturn(APPLICATION_CODE) + whenever(mockRequestContext.deviceInfo).thenReturn(deviceInfo) + whenever(mockVersionProvider.provideSdkVersion()).thenReturn(SDK_VERSION) + whenever(mockContactFieldValueStorage.get()).thenReturn("test@test.com") + whenever(mockContactTokenStorage.get()).thenReturn("contactToken") + + whenever(mockDeviceInfoPayloadStorage.get()).thenReturn("deviceInfo.deviceInfoPayload") + + setupEmarsysComponent( + FakeDependencyContainer( + activityLifecycleWatchdog = mockActivityLifecycleWatchdog, + currentActivityWatchdog = mockCurrentActivityWatchdog, + coreSQLiteDatabase = mockCoreSQLiteDatabase, + deviceInfo = deviceInfo, + logShardTrigger = mockLogShardTrigger, + mobileEngageInternal = mockMobileEngageInternal, + loggingMobileEngageInternal = mockMobileEngageInternal, + deepLinkInternal = mockDeepLinkInternal, + eventServiceInternal = mockEventServiceInternal, + loggingEventServiceInternal = mockEventServiceInternal, + clientService = mockClientServiceApi, + loggingClientService = mockClientServiceApi, + requestContext = mockRequestContext, + predictShardTrigger = mockPredictShardTrigger, + deviceInfoPayloadStorage = mockDeviceInfoPayloadStorage, + contactFieldValueStorage = mockContactFieldValueStorage, + contactTokenStorage = mockContactTokenStorage, + clientStateStorage = mockClientStateStorage, + responseHandlersProcessor = ResponseHandlersProcessor(ArrayList()), + mobileEngage = mockMobileEngageApi, + loggingMobileEngage = mockLoggingMobileEngageApi, + inApp = mockInApp, + loggingInApp = mockLoggingInApp, + push = mockPush, + predict = mockPredict, + loggingPredict = mockLoggingPredict, + predictRestricted = mockPredictRestricted, + loggingPredictRestricted = mockPredictRestricted, + config = mockConfig, + eventService = mockEventServiceApi, + loggingEventService = mockLoggingEventServiceApi, + deepLink = mockDeepLinkApi, + logger = mock() ) - latch = CountDownLatch(1) - } catch (e: Exception) { - e.printStackTrace() - throw e - } + ) + latch = CountDownLatch(1) } - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } @@ -269,29 +258,29 @@ class EmarsysTest { @Test fun testSetup_whenMobileEngageApplicationCodeAndMerchantIdAreNull_mobileEngageAndPredict_shouldBeDisabled() { val config = createConfig() - .applicationCode(null) - .merchantId(null) - .build() + .applicationCode(null) + .merchantId(null) + .build() setup(config) runBlockingOnCoreSdkThread() - Assert.assertEquals(false, FeatureRegistry.isFeatureEnabled(InnerFeature.MOBILE_ENGAGE)) - Assert.assertEquals(false, FeatureRegistry.isFeatureEnabled(InnerFeature.PREDICT)) + FeatureRegistry.isFeatureEnabled(InnerFeature.MOBILE_ENGAGE) shouldBe false + FeatureRegistry.isFeatureEnabled(InnerFeature.PREDICT) shouldBe false } @Test fun testSetup_whenMobileEngageApplicationCodeIsNotNull_mobileEngageFeature_shouldBeEnabled() { setup(mobileEngageConfig) - Assert.assertTrue(FeatureRegistry.isFeatureEnabled(InnerFeature.MOBILE_ENGAGE)) + FeatureRegistry.isFeatureEnabled(InnerFeature.MOBILE_ENGAGE) shouldBe true } @Test fun testSetup_whenPredictMerchantIdIsNotNull_predictFeature_shouldBeEnabled() { setup(predictConfig) - Assert.assertTrue(FeatureRegistry.isFeatureEnabled(InnerFeature.PREDICT)) + FeatureRegistry.isFeatureEnabled(InnerFeature.PREDICT) shouldBe true } @Test @@ -315,8 +304,8 @@ class EmarsysTest { setup(baseConfig) val container = emarsys() - Assert.assertEquals(DefaultEmarsysComponent::class.java, container.javaClass) - Assert.assertEquals(isEmarsysComponentSetup(), true) + container.javaClass shouldBe DefaultEmarsysComponent::class.java + isEmarsysComponentSetup() shouldBe true } @Test @@ -329,11 +318,11 @@ class EmarsysTest { runBlockingOnCoreSdkThread { val requestManager: RequestManager = emarsys().requestManager repository = getInstanceField( - requestManager, - "requestRepository" + requestManager, + "requestRepository" ) } - Assert.assertEquals(RequestRepositoryProxy::class.java, repository?.javaClass) + repository?.javaClass shouldBe RequestRepositoryProxy::class.java } @Test @@ -345,78 +334,49 @@ class EmarsysTest { runBlockingOnCoreSdkThread { val responseHandlersProcessor = emarsys().responseHandlersProcessor - Assert.assertNotNull(responseHandlersProcessor) - Assert.assertEquals(11, responseHandlersProcessor.responseHandlers.size.toLong()) - Assert.assertEquals( - 1, - numberOfElementsIn( - responseHandlersProcessor.responseHandlers, - VisitorIdResponseHandler::class.java - ).toLong() - ) - Assert.assertEquals( - 1, - numberOfElementsIn( - responseHandlersProcessor.responseHandlers, - XPResponseHandler::class.java - ).toLong() - ) - Assert.assertEquals( - 1, - numberOfElementsIn( - responseHandlersProcessor.responseHandlers, - InAppMessageResponseHandler::class.java - ).toLong() - ) - Assert.assertEquals( - 1, - numberOfElementsIn( - responseHandlersProcessor.responseHandlers, - InAppCleanUpResponseHandler::class.java - ).toLong() - ) - Assert.assertEquals( - 1, - numberOfElementsIn( - responseHandlersProcessor.responseHandlers, - InAppCleanUpResponseHandlerV4::class.java - ).toLong() - ) - Assert.assertEquals( - 2, - numberOfElementsIn( - responseHandlersProcessor.responseHandlers, - MobileEngageTokenResponseHandler::class.java - ).toLong() - ) - Assert.assertEquals( - 1, - numberOfElementsIn( - responseHandlersProcessor.responseHandlers, - MobileEngageClientStateResponseHandler::class.java - ).toLong() - ) - Assert.assertEquals( - 1, - numberOfElementsIn( - responseHandlersProcessor.responseHandlers, - ClientInfoResponseHandler::class.java - ).toLong() - ) - Assert.assertEquals( - 1, - numberOfElementsIn( - responseHandlersProcessor.responseHandlers, - OnEventActionResponseHandler::class.java - ).toLong() - ) - Assert.assertEquals( - 1, - numberOfElementsIn( - responseHandlersProcessor.responseHandlers, - DeviceEventStateResponseHandler::class.java - ).toLong() - ) + responseHandlersProcessor shouldNotBe null + responseHandlersProcessor.responseHandlers.size shouldBe 11 + numberOfElementsIn( + responseHandlersProcessor.responseHandlers, + VisitorIdResponseHandler::class.java + ).toLong() shouldBe 1 + numberOfElementsIn( + responseHandlersProcessor.responseHandlers, + XPResponseHandler::class.java + ).toLong() shouldBe 1 + numberOfElementsIn( + responseHandlersProcessor.responseHandlers, + InAppMessageResponseHandler::class.java + ).toLong() shouldBe 1 + numberOfElementsIn( + responseHandlersProcessor.responseHandlers, + InAppCleanUpResponseHandler::class.java + ).toLong() shouldBe 1 + numberOfElementsIn( + responseHandlersProcessor.responseHandlers, + InAppCleanUpResponseHandlerV4::class.java + ).toLong() shouldBe 1 + numberOfElementsIn( + responseHandlersProcessor.responseHandlers, + MobileEngageTokenResponseHandler::class.java + ).toLong() shouldBe 2 + numberOfElementsIn( + responseHandlersProcessor.responseHandlers, + MobileEngageClientStateResponseHandler::class.java + ).toLong() shouldBe 1 + numberOfElementsIn( + responseHandlersProcessor.responseHandlers, + ClientInfoResponseHandler::class.java + ).toLong() shouldBe 1 + numberOfElementsIn( + responseHandlersProcessor.responseHandlers, + OnEventActionResponseHandler::class.java + ).toLong() shouldBe 1 + numberOfElementsIn( + responseHandlersProcessor.responseHandlers, + DeviceEventStateResponseHandler::class.java + ).toLong() shouldBe 1 + } } @@ -426,10 +386,10 @@ class EmarsysTest { runBlockingOnCoreSdkThread { verify(mockCoreSQLiteDatabase).registerTrigger( - "shard", - TriggerType.AFTER, - TriggerEvent.INSERT, - mockPredictShardTrigger + "shard", + TriggerType.AFTER, + TriggerEvent.INSERT, + mockPredictShardTrigger ) } } @@ -441,12 +401,12 @@ class EmarsysTest { runBlockingOnCoreSdkThread { argumentCaptor().apply { verify(mockCoreSQLiteDatabase, times(1)).registerTrigger( - any(), - any(), - any(), - capture() + any(), + any(), + any(), + capture() ) - Assert.assertEquals(mockLogShardTrigger, firstValue) + firstValue shouldBe mockLogShardTrigger verifyNoMoreInteractions(mockCoreSQLiteDatabase) } } @@ -458,10 +418,10 @@ class EmarsysTest { runBlockingOnCoreSdkThread { verify(mockCoreSQLiteDatabase).registerTrigger( - "shard", - TriggerType.AFTER, - TriggerEvent.INSERT, - mockLogShardTrigger + "shard", + TriggerType.AFTER, + TriggerEvent.INSERT, + mockLogShardTrigger ) } } @@ -469,24 +429,37 @@ class EmarsysTest { @Test fun testSetup_registers_activityLifecycleWatchdog() { setup(mobileEngageConfig) - runBlockingOnCoreSdkThread { argumentCaptor().apply { - verify(application, times(2)).registerActivityLifecycleCallbacks(capture()) + verify( + application, + times(1), + ).registerActivityLifecycleCallbacks(capture()) + val allRegisteredWatchdogs = allValues getElementByType( - allValues, - ActivityLifecycleWatchdog::class.java + allRegisteredWatchdogs, + ActivityLifecycleWatchdog::class.java + ) shouldNotBe null + } + argumentCaptor().apply { + verify( + application, + times(1), + ).registerActivityLifecycleCallbacks(capture()) + val allRegisteredWatchdogs = allValues + getElementByType( + allRegisteredWatchdogs, + CurrentActivityWatchdog::class.java ) shouldNotBe null - getElementByType(allValues, CurrentActivityWatchdog::class.java) shouldNotBe null - } } + } @Test fun testSetup_registers_activityLifecycleWatchdogs() { IntegrationTestUtils.tearDownEmarsys() - argumentCaptor().apply { + argumentCaptor().apply { setup(mobileEngageConfig) runBlockingOnCoreSdkThread { @@ -654,9 +627,9 @@ class EmarsysTest { runBlockingOnCoreSdkThread { verifyNoInteractions(mockPredictRestricted) verify(mockMobileEngageApi).setContact( - CONTACT_FIELD_ID, - CONTACT_FIELD_VALUE, - completionListener + CONTACT_FIELD_ID, + CONTACT_FIELD_VALUE, + completionListener ) } } @@ -670,9 +643,9 @@ class EmarsysTest { runBlockingOnCoreSdkThread { verifyNoInteractions(mockPredictRestricted) verify(mockMobileEngageApi).setAuthenticatedContact( - CONTACT_FIELD_ID, - OPEN_ID_TOKEN, - completionListener + CONTACT_FIELD_ID, + OPEN_ID_TOKEN, + completionListener ) } } @@ -699,9 +672,9 @@ class EmarsysTest { runBlockingOnCoreSdkThread() verify(mockMobileEngageApi).setAuthenticatedContact( - CONTACT_FIELD_ID, - OPEN_ID_TOKEN, - completionListener + CONTACT_FIELD_ID, + OPEN_ID_TOKEN, + completionListener ) FeatureRegistry.isFeatureEnabled(InnerFeature.PREDICT) shouldBe false verifyNoInteractions(mockPredictRestricted) @@ -748,9 +721,9 @@ class EmarsysTest { runBlockingOnCoreSdkThread { verify(mockPredictRestricted).setContact(CONTACT_FIELD_ID, CONTACT_FIELD_VALUE) verify(mockMobileEngageApi).setContact( - CONTACT_FIELD_ID, - CONTACT_FIELD_VALUE, - completionListener + CONTACT_FIELD_ID, + CONTACT_FIELD_VALUE, + completionListener ) } } @@ -764,9 +737,9 @@ class EmarsysTest { runBlockingOnCoreSdkThread { verifyNoInteractions(mockPredictRestricted) verify(mockLoggingMobileEngageApi).setContact( - CONTACT_FIELD_ID, - CONTACT_FIELD_VALUE, - completionListener + CONTACT_FIELD_ID, + CONTACT_FIELD_VALUE, + completionListener ) } } @@ -860,9 +833,9 @@ class EmarsysTest { runBlockingOnCoreSdkThread { verify(mockEventServiceApi).trackCustomEventAsync( - eventName, - eventAttributes, - completionListener + eventName, + eventAttributes, + completionListener ) } } @@ -875,9 +848,9 @@ class EmarsysTest { runBlockingOnCoreSdkThread() verify(mockLoggingEventServiceApi).trackCustomEventAsync( - eventName, - eventAttributes, - completionListener + eventName, + eventAttributes, + completionListener ) } @@ -903,8 +876,8 @@ class EmarsysTest { private fun createConfig(vararg experimentalFeatures: FlipperFeature): EmarsysConfig.Builder { return EmarsysConfig.Builder() - .application(application) - .enableExperimentalFeatures(*experimentalFeatures) + .application(application) + .enableExperimentalFeatures(*experimentalFeatures) } private fun runBlockingOnCoreSdkThread(callback: (() -> Unit)? = null) { diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/InAppTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/InAppTest.kt index c5dac355..09acc3e8 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/InAppTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/InAppTest.kt @@ -12,13 +12,10 @@ import com.emarsys.mobileengage.api.event.EventHandler import com.emarsys.mobileengage.di.mobileEngage import com.emarsys.mobileengage.iam.InAppInternal import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -29,11 +26,8 @@ class InAppTest { private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockInAppInternal = mock() val dependencyContainer = FakeDependencyContainer(inAppInternal = mockInAppInternal) @@ -42,7 +36,7 @@ class InAppTest { inApp = InApp() } - @After + @AfterEach fun tearDown() { application.unregisterActivityLifecycleCallbacks( mobileEngage().activityLifecycleWatchdog) diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/InappNotificationIntegrationTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/InappNotificationIntegrationTest.kt index e5b49f2f..1c35abba 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/InappNotificationIntegrationTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/InappNotificationIntegrationTest.kt @@ -3,7 +3,6 @@ package com.emarsys import android.app.Application import android.content.Context import android.content.Intent -import androidx.test.ext.junit.rules.ActivityScenarioRule import com.emarsys.config.EmarsysConfig import com.emarsys.core.activity.ActivityLifecycleActionRegistry import com.emarsys.core.activity.ActivityLifecycleWatchdog @@ -20,14 +19,9 @@ import com.emarsys.testUtil.ConnectionTestUtils import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.IntegrationTestUtils -import com.emarsys.testUtil.TimeoutUtils -import com.emarsys.testUtil.fake.FakeActivity -import com.emarsys.testUtil.rules.DuplicatedThreadRule -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.eq import org.mockito.kotlin.mock @@ -49,20 +43,8 @@ class InappNotificationIntegrationTest { private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Rule - @JvmField - var activityScenarioRule: ActivityScenarioRule = - ActivityScenarioRule(FakeActivity::class.java) - - @Rule - @JvmField - val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") - - @Before + @BeforeEach fun setup() { completionListenerLatch = CountDownLatch(1) @@ -114,7 +96,7 @@ class InappNotificationIntegrationTest { IntegrationTestUtils.doLogin() } - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys(application) } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageIntegrationTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageIntegrationTest.kt index db7b0cc2..3210ce42 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageIntegrationTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageIntegrationTest.kt @@ -20,20 +20,22 @@ import com.emarsys.di.emarsys import com.emarsys.mobileengage.push.PushTokenProvider import com.emarsys.testUtil.* import com.emarsys.testUtil.mockito.whenever -import com.emarsys.testUtil.rules.DuplicatedThreadRule -import com.emarsys.testUtil.rules.RetryRule -import io.kotlintest.matchers.shouldBeInRange -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import io.kotest.matchers.ints.shouldBeInRange +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe + +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junitpioneer.jupiter.RetryingTest + import org.mockito.ArgumentMatchers import org.mockito.Mockito.mock import java.util.concurrent.CountDownLatch +@ExtendWith(DuplicatedThreadExtension::class) class MobileEngageIntegrationTest { private companion object { @@ -54,31 +56,19 @@ class MobileEngageIntegrationTest { private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Rule - @JvmField - val retryRule: RetryRule = RetryUtils.retryRule - - @Rule - @JvmField - val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") - - @Before + @BeforeEach fun setup() { DatabaseTestUtils.deleteCoreDatabase() application.getSharedPreferences("emarsys_secure_shared_preferences", Context.MODE_PRIVATE) - .edit() - .clear() - .commit() + .edit() + .clear() + .commit() baseConfig = EmarsysConfig.Builder() - .application(application) - .applicationCode(APP_ID) - .build() + .application(application) + .applicationCode(APP_ID) + .build() completionHandler = createDefaultCoreCompletionHandler() @@ -87,19 +77,19 @@ class MobileEngageIntegrationTest { whenever(providePushToken()).thenReturn("integration_test_push_token") } val deviceInfo = DeviceInfo( - application, - mock(HardwareIdProvider::class.java).apply { - whenever(provideHardwareId()).thenReturn("mobileengage_integration_hwid") - }, - mock(VersionProvider::class.java).apply { - whenever(provideSdkVersion()).thenReturn("0.0.0-mobileengage_integration_version") - }, - mock(LanguageProvider::class.java).apply { - whenever(provideLanguage(ArgumentMatchers.any())).thenReturn("en-US") - }, - mock(NotificationManagerHelper::class.java), - isAutomaticPushSendingEnabled = true, - isGooglePlayAvailable = true + application, + mock(HardwareIdProvider::class.java).apply { + whenever(provideHardwareId()).thenReturn("mobileengage_integration_hwid") + }, + mock(VersionProvider::class.java).apply { + whenever(provideSdkVersion()).thenReturn("0.0.0-mobileengage_integration_version") + }, + mock(LanguageProvider::class.java).apply { + whenever(provideLanguage(ArgumentMatchers.any())).thenReturn("en-US") + }, + mock(NotificationManagerHelper::class.java), + isAutomaticPushSendingEnabled = true, + isGooglePlayAvailable = true ) DefaultEmarsysDependencies(baseConfig, object : DefaultEmarsysComponent(baseConfig) { @@ -115,7 +105,10 @@ class MobileEngageIntegrationTest { ConnectionTestUtils.checkConnection(application) - sharedPreferences = application.getSharedPreferences("emarsys_secure_shared_preferences", Context.MODE_PRIVATE) + sharedPreferences = application.getSharedPreferences( + "emarsys_secure_shared_preferences", + Context.MODE_PRIVATE + ) Emarsys.setup(baseConfig) @@ -125,7 +118,7 @@ class MobileEngageIntegrationTest { completionHandlerLatch = CountDownLatch(1) } - @After + @AfterEach fun tearDown() { try { IntegrationTestUtils.tearDownEmarsys(application) @@ -136,6 +129,7 @@ class MobileEngageIntegrationTest { } @Test + @RetryingTest(3) fun testSetContact() { Emarsys.setContact( CONTACT_FIELD_ID, @@ -145,102 +139,116 @@ class MobileEngageIntegrationTest { } @Test + @RetryingTest(3) fun testClearContact() { Emarsys.clearContact( - this::eventuallyStoreResult + this::eventuallyStoreResult ).apply { eventuallyAssertSuccess() } } @Test + @RetryingTest(3) fun testTrackCustomEvent_V3_noAttributes() { Emarsys.trackCustomEvent( - "integrationTestCustomEvent", - null, - this::eventuallyStoreResult + "integrationTestCustomEvent", + null, + this::eventuallyStoreResult ).apply { eventuallyAssertSuccess() } } @Test + @RetryingTest(3) fun testTrackCustomEvent_V3_withAttributes() { Emarsys.trackCustomEvent( - "integrationTestCustomEvent", - mapOf("key1" to "value1", "key2" to "value2"), - this::eventuallyStoreResult + "integrationTestCustomEvent", + mapOf("key1" to "value1", "key2" to "value2"), + this::eventuallyStoreResult ).apply { eventuallyAssertSuccess() } } @Test + @RetryingTest(3) fun testTrackInternalCustomEvent_V3_noAttributes() { val eventServiceInternal = emarsys().eventServiceInternal eventServiceInternal.trackInternalCustomEvent( - "integrationTestInternalCustomEvent", - null, - this::eventuallyStoreResult + "integrationTestInternalCustomEvent", + null, + this::eventuallyStoreResult ).apply { eventuallyAssertSuccess() } } @Test + @RetryingTest(3) fun testTrackInternalCustomEvent_V3_withAttributes() { val eventServiceInternal = emarsys().eventServiceInternal eventServiceInternal.trackInternalCustomEvent( - "integrationTestInternalCustomEvent", - mapOf("key1" to "value1", "key2" to "value2"), - this::eventuallyStoreResult + "integrationTestInternalCustomEvent", + mapOf("key1" to "value1", "key2" to "value2"), + this::eventuallyStoreResult ).apply { eventuallyAssertSuccess() } } @Test + @RetryingTest(3) fun testSetPushToken() { - Emarsys.push.setPushToken("integration_test_push_token", - this::eventuallyStoreResult + Emarsys.push.setPushToken( + "integration_test_push_token", + this::eventuallyStoreResult ).apply { eventuallyAssertSuccess() } } @Test + @RetryingTest(3) fun testRemovePushToken() { Emarsys.push.clearPushToken( - this::eventuallyStoreResult + this::eventuallyStoreResult ).apply { eventuallyAssertSuccess() } } @Test + @RetryingTest(3) fun testDeepLinkOpen() { Thread.sleep(1000) val activity = mock(Activity::class.java) whenever(activity.intent).thenReturn(Intent()) val intent = Intent( - Intent.ACTION_VIEW, - Uri.parse("https://github.com/emartech/android-emarsys-sdk/wiki?ems_dl=210268110_ZVwwYrYUFR_1_100302293_1_2000000")) + Intent.ACTION_VIEW, + Uri.parse("https://github.com/emartech/android-emarsys-sdk/wiki?ems_dl=210268110_ZVwwYrYUFR_1_100302293_1_2000000") + ) Emarsys.trackDeepLink( - activity, - intent, - this::eventuallyStoreResult + activity, + intent, + this::eventuallyStoreResult ).apply { eventuallyAssertSuccess() } Thread.sleep(1000) } @Test + @RetryingTest(3) fun testTrackDeviceInfo() { val clientServiceInternal = emarsys().clientServiceInternal clientServiceInternal.trackDeviceInfo(this::eventuallyStoreResult) - .apply{ eventuallyAssertCompletionHandlerSuccess() } + .apply { eventuallyAssertCompletionHandlerSuccess() } } @Test + @RetryingTest(3) fun testConfig_changeApplicationCode() { val originalApplicationCode = Emarsys.config.applicationCode - Emarsys.config.changeApplicationCode(OTHER_APP_ID, this::eventuallyStoreResult).apply { eventuallyAssertSuccess() } + Emarsys.config.changeApplicationCode(OTHER_APP_ID, this::eventuallyStoreResult) + .apply { eventuallyAssertSuccess() } originalApplicationCode shouldNotBe Emarsys.config.applicationCode Emarsys.config.applicationCode shouldBe OTHER_APP_ID } @Test + @RetryingTest(3) fun testConfig_changeApplicationCode_nilToSomething() { val setupLatch = CountDownLatch(1) emarsys().concurrentHandlerHolder.coreHandler.post { @@ -251,8 +259,8 @@ class MobileEngageIntegrationTest { IntegrationTestUtils.tearDownEmarsys(application) val config = EmarsysConfig.Builder() - .application(application) - .build() + .application(application) + .build() Emarsys.setup(config) var returnedThrowable: Throwable? = Throwable("testErrorCause") diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageRefreshContactTokenIntegrationTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageRefreshContactTokenIntegrationTest.kt index 0fc4680c..8ffdb5a0 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageRefreshContactTokenIntegrationTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageRefreshContactTokenIntegrationTest.kt @@ -19,22 +19,23 @@ import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.FeatureTestUtils import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.IntegrationTestUtils -import com.emarsys.testUtil.RetryUtils -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import com.emarsys.testUtil.rules.DuplicatedThreadRule -import com.emarsys.testUtil.rules.RetryRule -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.junitpioneer.jupiter.RetryingTest + import org.mockito.ArgumentMatchers import org.mockito.Mockito import java.util.concurrent.CountDownLatch +@ExtendWith(DuplicatedThreadExtension::class) + class MobileEngageRefreshContactTokenIntegrationTest { companion object { @@ -51,43 +52,31 @@ class MobileEngageRefreshContactTokenIntegrationTest { private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Rule - @JvmField - val retryRule: RetryRule = RetryUtils.retryRule - - @Rule - @JvmField - val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") - - @Before + @BeforeEach fun setup() { DatabaseTestUtils.deleteCoreDatabase() baseConfig = EmarsysConfig.Builder() - .application(application) - .applicationCode(APP_ID) - .build() + .application(application) + .applicationCode(APP_ID) + .build() FeatureTestUtils.resetFeatures() val deviceInfo = DeviceInfo( - application, - Mockito.mock(HardwareIdProvider::class.java).apply { - whenever(provideHardwareId()).thenReturn("mobileengage_integration_hwid") - }, - Mockito.mock(VersionProvider::class.java).apply { - whenever(provideSdkVersion()).thenReturn("0.0.0-mobileengage_integration_version") - }, - Mockito.mock(LanguageProvider::class.java).apply { - whenever(provideLanguage(ArgumentMatchers.any())).thenReturn("en-US") - }, - Mockito.mock(NotificationManagerHelper::class.java), - isAutomaticPushSendingEnabled = true, - isGooglePlayAvailable = true + application, + Mockito.mock(HardwareIdProvider::class.java).apply { + whenever(provideHardwareId()).thenReturn("mobileengage_integration_hwid") + }, + Mockito.mock(VersionProvider::class.java).apply { + whenever(provideSdkVersion()).thenReturn("0.0.0-mobileengage_integration_version") + }, + Mockito.mock(LanguageProvider::class.java).apply { + whenever(provideLanguage(ArgumentMatchers.any())).thenReturn("en-US") + }, + Mockito.mock(NotificationManagerHelper::class.java), + isAutomaticPushSendingEnabled = true, + isGooglePlayAvailable = true ) DefaultEmarsysDependencies(baseConfig, object : DefaultEmarsysComponent(baseConfig) { @@ -114,12 +103,13 @@ class MobileEngageRefreshContactTokenIntegrationTest { completionListenerLatch = CountDownLatch(1) } - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys(application) } @Test + @RetryingTest(3) fun testRefreshContactToken_shouldUpdateContactToken_whenOutDated() { contactTokenStorage.remove() contactTokenStorage.set("tokenForIntegrationTest") diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/PredictIntegrationTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/PredictIntegrationTest.kt index 4a235eab..145fb282 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/PredictIntegrationTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/PredictIntegrationTest.kt @@ -26,25 +26,25 @@ import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.FeatureTestUtils import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.IntegrationTestUtils -import com.emarsys.testUtil.RetryUtils -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import com.emarsys.testUtil.rules.DuplicatedThreadRule -import com.emarsys.testUtil.rules.RetryRule -import io.kotlintest.matchers.numerics.shouldBeGreaterThan -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import io.kotest.matchers.comparables.shouldBeGreaterThan +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + import org.mockito.ArgumentMatchers import org.mockito.Mockito.mock import java.net.URLDecoder import java.util.concurrent.CountDownLatch import kotlin.reflect.KMutableProperty0 +@ExtendWith(DuplicatedThreadExtension::class) + class PredictIntegrationTest { companion object { @@ -70,31 +70,20 @@ class PredictIntegrationTest { private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Rule - @JvmField - val retryRule: RetryRule = RetryUtils.retryRule - - @Rule - @JvmField - val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") - @Before + @BeforeEach fun setup() { DatabaseTestUtils.deleteCoreDatabase() application.getSharedPreferences("emarsys_secure_shared_preferences", Context.MODE_PRIVATE) - .edit() - .clear() - .commit() + .edit() + .clear() + .commit() baseConfig = EmarsysConfig.Builder() - .application(application) - .merchantId(MERCHANT_ID) - .build() + .application(application) + .merchantId(MERCHANT_ID) + .build() latch = CountDownLatch(1) errorCause = null @@ -128,19 +117,19 @@ class PredictIntegrationTest { val deviceInfo = DeviceInfo( - application, - mock(HardwareIdProvider::class.java).apply { - whenever(provideHardwareId()).thenReturn("mobileengage_integration_hwid") - }, - mock(VersionProvider::class.java).apply { - whenever(provideSdkVersion()).thenReturn("0.0.0-mobileengage_integration_version") - }, - mock(LanguageProvider::class.java).apply { - whenever(provideLanguage(ArgumentMatchers.any())).thenReturn("en-US") - }, - mock(NotificationManagerHelper::class.java), - isAutomaticPushSendingEnabled = true, - isGooglePlayAvailable = true + application, + mock(HardwareIdProvider::class.java).apply { + whenever(provideHardwareId()).thenReturn("mobileengage_integration_hwid") + }, + mock(VersionProvider::class.java).apply { + whenever(provideSdkVersion()).thenReturn("0.0.0-mobileengage_integration_version") + }, + mock(LanguageProvider::class.java).apply { + whenever(provideLanguage(ArgumentMatchers.any())).thenReturn("en-US") + }, + mock(NotificationManagerHelper::class.java), + isAutomaticPushSendingEnabled = true, + isGooglePlayAvailable = true ) DefaultEmarsysDependencies(baseConfig, object : DefaultEmarsysComponent(baseConfig) { @@ -168,7 +157,7 @@ class PredictIntegrationTest { } } - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys(application) } @@ -299,7 +288,7 @@ class PredictIntegrationTest { latch = CountDownLatch(1) Emarsys.predict.recommendProducts(RecommendationLogic.search(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) eventuallyAssertForTriedRecommendedProducts() } @@ -312,7 +301,7 @@ class PredictIntegrationTest { PredictCartItem(ITEM3, 3.3, 30.0) ) Emarsys.predict.recommendProducts(RecommendationLogic.cart(cartItems), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) eventuallyAssertForTriedRecommendedProducts() } @@ -323,7 +312,7 @@ class PredictIntegrationTest { latch = CountDownLatch(1) Emarsys.predict.recommendProducts(RecommendationLogic.cart(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) eventuallyAssertForTriedRecommendedProducts() } @@ -344,7 +333,7 @@ class PredictIntegrationTest { latch = CountDownLatch(1) Emarsys.predict.recommendProducts(RecommendationLogic.related(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) eventuallyAssertForTriedRecommendedProducts() } @@ -352,7 +341,7 @@ class PredictIntegrationTest { @Test fun testRecommendProducts_withoutRelated() { Emarsys.predict.recommendProducts(RecommendationLogic.related(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)).eventuallyAssert { + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)).eventuallyAssert { triedRecommendedProducts.errorCause shouldBe null triedRecommendedProducts.result shouldNotBe null triedRecommendedProducts.result!!.size shouldBe 0 @@ -375,7 +364,7 @@ class PredictIntegrationTest { latch = CountDownLatch(1) Emarsys.predict.recommendProducts(RecommendationLogic.category(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) eventuallyAssertForTriedRecommendedProducts() } @@ -396,7 +385,7 @@ class PredictIntegrationTest { latch = CountDownLatch(1) Emarsys.predict.recommendProducts(RecommendationLogic.alsoBought(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) eventuallyAssertForTriedRecommendedProducts() } @@ -407,7 +396,7 @@ class PredictIntegrationTest { latch = CountDownLatch(1) Emarsys.predict.recommendProducts(RecommendationLogic.popular(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) eventuallyAssertForTriedRecommendedProducts() } @@ -418,7 +407,7 @@ class PredictIntegrationTest { latch = CountDownLatch(1) Emarsys.predict.recommendProducts(RecommendationLogic.personal(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) eventuallyAssertForTriedRecommendedProducts() } @@ -429,7 +418,7 @@ class PredictIntegrationTest { latch = CountDownLatch(1) Emarsys.predict.recommendProducts(RecommendationLogic.personal(listOf("1", "2", "3")), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) eventuallyAssertForTriedRecommendedProducts() } @@ -440,7 +429,7 @@ class PredictIntegrationTest { latch = CountDownLatch(1) Emarsys.predict.recommendProducts(RecommendationLogic.home(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) eventuallyAssertForTriedRecommendedProducts() } @@ -451,7 +440,7 @@ class PredictIntegrationTest { latch = CountDownLatch(1) Emarsys.predict.recommendProducts(RecommendationLogic.home(listOf("1", "2", "3")), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) eventuallyAssertForTriedRecommendedProducts() } @@ -462,7 +451,7 @@ class PredictIntegrationTest { latch = CountDownLatch(1) Emarsys.predict.recommendProducts(RecommendationLogic.home(listOf("1", "2", "3")), "hu", - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) eventuallyAssertForTriedRecommendedProducts() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/PredictTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/PredictTest.kt index 9fee4542..48a592c9 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/PredictTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/PredictTest.kt @@ -16,13 +16,11 @@ import com.emarsys.predict.api.model.Product import com.emarsys.predict.api.model.RecommendationFilter import com.emarsys.testUtil.RandomTestUtils.randomNumberString import com.emarsys.testUtil.RandomTestUtils.randomString -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.anyNotNull -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.assertions.throwables.shouldThrow +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.Mockito import org.mockito.kotlin.eq import org.mockito.kotlin.isNull @@ -41,11 +39,8 @@ class PredictTest { private lateinit var mockRecommendationFilters: List private lateinit var resultListenerCallback: (Try>) -> Unit - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockPredictInternal = mock() resultListenerCallback = mock() @@ -61,7 +56,7 @@ class PredictTest { mockRecommendationFilters = listOf(mockRecommendationFilter) } - @After + @AfterEach fun tearDown() { try { val handler = emarsys().concurrentHandlerHolder @@ -77,9 +72,9 @@ class PredictTest { @Test fun testPredict_trackCart_delegatesTo_Predict_Internal() { val itemList = listOf( - createItem("itemId0", 200.0, 100.0), - createItem("itemId1", 201.0, 101.0), - createItem("itemId2", 202.0, 102.0) + createItem("itemId0", 200.0, 100.0), + createItem("itemId1", 201.0, 101.0), + createItem("itemId2", 202.0, 102.0) ) predict.trackCart(itemList) Mockito.verify(mockPredictInternal).trackCart(itemList) @@ -89,9 +84,9 @@ class PredictTest { fun testPredict_trackPurchase_delegatesTo_Predict_Internal() { val orderId = "id" val itemList = listOf( - createItem("itemId0", 200.0, 100.0), - createItem("itemId1", 201.0, 101.0), - createItem("itemId2", 202.0, 102.0) + createItem("itemId0", 200.0, 100.0), + createItem("itemId1", 201.0, 101.0), + createItem("itemId2", 202.0, 102.0) ) predict.trackPurchase(orderId, itemList) Mockito.verify(mockPredictInternal).trackPurchase(orderId, itemList) @@ -126,9 +121,11 @@ class PredictTest { verify(mockPredictInternal).trackTag("testTag", HashMap()) } - @Test(expected = IllegalArgumentException::class) + @Test fun testPredict_recommendProducts_limit_mustBeAPositiveInteger() { - predict.recommendProducts(mockLogic, -5, mockResultListener) + shouldThrow { + predict.recommendProducts(mockLogic, -5, mockResultListener) + } } @Test @@ -140,7 +137,13 @@ class PredictTest { @Test fun testPredict_recommendProductWithLimitAndResultListenerCallback_delegatesTo_predictInternal() { predict.recommendProducts(mockLogic, 5, resultListenerCallback) - verify(mockPredictInternal).recommendProducts(eq(mockLogic), eq(5), isNull(), isNull(), anyNotNull()) + verify(mockPredictInternal).recommendProducts( + eq(mockLogic), + eq(5), + isNull(), + isNull(), + anyNotNull() + ) } @Test @@ -152,30 +155,48 @@ class PredictTest { @Test fun testPredict_recommendProductWithLimitAndAvailabilityZoneAndResultListenerCallback_delegatesTo_predictInternal() { predict.recommendProducts(mockLogic, 5, AVAILABILITY_ZONE, resultListenerCallback) - verify(mockPredictInternal).recommendProducts(eq(mockLogic), eq(5), isNull(), eq("HU"), anyNotNull()) + verify(mockPredictInternal).recommendProducts( + eq(mockLogic), + eq(5), + isNull(), + eq("HU"), + anyNotNull() + ) } @Test fun testPredict_recommendProductWithAvailabilityZone_delegatesTo_predictInternal() { predict.recommendProducts(mockLogic, AVAILABILITY_ZONE, mockResultListener) - verify(mockPredictInternal).recommendProducts(mockLogic, null, null, "HU", mockResultListener) + verify(mockPredictInternal).recommendProducts( + mockLogic, + null, + null, + "HU", + mockResultListener + ) } @Test fun testPredict_recommendProductWithAvailabilityZoneAndResultListenerCallback_delegatesTo_predictInternal() { predict.recommendProducts(mockLogic, AVAILABILITY_ZONE, resultListenerCallback) - verify(mockPredictInternal).recommendProducts(eq(mockLogic), isNull(), isNull(), eq("HU"), anyNotNull()) + verify(mockPredictInternal).recommendProducts( + eq(mockLogic), + isNull(), + isNull(), + eq("HU"), + anyNotNull() + ) } @Test fun testPredict_recommendProductsWithFilters_delegatesTo_predictInternal() { predict.recommendProducts(mockLogic, mockRecommendationFilters, mockResultListener) verify(mockPredictInternal).recommendProducts( - mockLogic, - null, - mockRecommendationFilters, - null, - mockResultListener + mockLogic, + null, + mockRecommendationFilters, + null, + mockResultListener ) } @@ -184,52 +205,64 @@ class PredictTest { val resultListenerCallback: (Try>) -> Unit = mock() predict.recommendProducts(mockLogic, mockRecommendationFilters, resultListenerCallback) verify(mockPredictInternal).recommendProducts( - eq(mockLogic), - isNull(), - eq(mockRecommendationFilters), - isNull(), - anyNotNull() + eq(mockLogic), + isNull(), + eq(mockRecommendationFilters), + isNull(), + anyNotNull() ) } @Test fun testPredict_recommendProductsWithFiltersAndAvailabilityZone_delegatesTo_predictInternal() { - predict.recommendProducts(mockLogic, mockRecommendationFilters, AVAILABILITY_ZONE, mockResultListener) + predict.recommendProducts( + mockLogic, + mockRecommendationFilters, + AVAILABILITY_ZONE, + mockResultListener + ) verify(mockPredictInternal).recommendProducts( - mockLogic, - null, - mockRecommendationFilters, - "HU", - mockResultListener + mockLogic, + null, + mockRecommendationFilters, + "HU", + mockResultListener ) } @Test fun testPredict_recommendProductsWithFiltersAndAvailabilityZoneAndResultListenerCallback_delegatesTo_predictInternal() { - predict.recommendProducts(mockLogic, mockRecommendationFilters, AVAILABILITY_ZONE, resultListenerCallback) + predict.recommendProducts( + mockLogic, + mockRecommendationFilters, + AVAILABILITY_ZONE, + resultListenerCallback + ) verify(mockPredictInternal).recommendProducts( - eq(mockLogic), - isNull(), - eq(mockRecommendationFilters), - eq("HU"), - anyNotNull() + eq(mockLogic), + isNull(), + eq(mockRecommendationFilters), + eq("HU"), + anyNotNull() ) } - @Test(expected = IllegalArgumentException::class) + @Test fun testPredict_recommendProductsWithFiltersAndLimit_limit_mustBeAPositiveInteger() { - predict.recommendProducts(mockLogic, mockRecommendationFilters, -5, mockResultListener) + shouldThrow { + predict.recommendProducts(mockLogic, mockRecommendationFilters, -5, mockResultListener) + } } @Test fun testPredict_recommendProductsWithFiltersAndLimit_delegatesTo_predictInternal() { predict.recommendProducts(mockLogic, mockRecommendationFilters, 123, mockResultListener) verify(mockPredictInternal).recommendProducts( - mockLogic, - 123, - mockRecommendationFilters, - null, - mockResultListener + mockLogic, + 123, + mockRecommendationFilters, + null, + mockResultListener ) } @@ -238,55 +271,85 @@ class PredictTest { val resultListenerCallback: (Try>) -> Unit = mock() predict.recommendProducts(mockLogic, mockRecommendationFilters, 123, resultListenerCallback) verify(mockPredictInternal).recommendProducts( - eq(mockLogic), - eq(123), - eq(mockRecommendationFilters), - isNull(), - anyNotNull() + eq(mockLogic), + eq(123), + eq(mockRecommendationFilters), + isNull(), + anyNotNull() ) } @Test fun testPredict_recommendProductsWithFiltersAndLimitAndAvailabilityZone_delegatesTo_predictInternal() { - predict.recommendProducts(mockLogic, mockRecommendationFilters, 123, AVAILABILITY_ZONE, mockResultListener) + predict.recommendProducts( + mockLogic, + mockRecommendationFilters, + 123, + AVAILABILITY_ZONE, + mockResultListener + ) verify(mockPredictInternal).recommendProducts( - mockLogic, - 123, - mockRecommendationFilters, - "HU", - mockResultListener + mockLogic, + 123, + mockRecommendationFilters, + "HU", + mockResultListener ) } @Test fun testPredict_recommendProducts_delegatesTo_predictInternal() { predict.recommendProducts(mockLogic, mockResultListener) - verify(mockPredictInternal).recommendProducts(mockLogic, null, null, null, mockResultListener) + verify(mockPredictInternal).recommendProducts( + mockLogic, + null, + null, + null, + mockResultListener + ) } @Test fun testPredict_recommendProductsWithResultListenerCallback_delegatesTo_predictInternal() { val resultListenerCallback: (Try>) -> Unit = mock() predict.recommendProducts(mockLogic, resultListenerCallback) - verify(mockPredictInternal).recommendProducts(eq(mockLogic), isNull(), isNull(), isNull(), anyNotNull()) + verify(mockPredictInternal).recommendProducts( + eq(mockLogic), + isNull(), + isNull(), + isNull(), + anyNotNull() + ) } @Test fun testPredict_recommendProductsWithFunction_delegatesTo_predictInternal() { val resultListenerCallback: (Try>) -> Unit = mock() - predict.recommendProducts(mockLogic, mockRecommendationFilters, 123, AVAILABILITY_ZONE, resultListenerCallback) + predict.recommendProducts( + mockLogic, + mockRecommendationFilters, + 123, + AVAILABILITY_ZONE, + resultListenerCallback + ) verify(mockPredictInternal).recommendProducts( - eq(mockLogic), - eq(123), - eq(mockRecommendationFilters), - eq("HU"), - anyNotNull() + eq(mockLogic), + eq(123), + eq(mockRecommendationFilters), + eq("HU"), + anyNotNull() ) } @Test fun testPredict_trackRecommendationClick_delegatesTo_predictInternal() { - val product = Product(randomString(), randomString(), "https://emarsys.com", randomString(), randomNumberString()) + val product = Product( + randomString(), + randomString(), + "https://emarsys.com", + randomString(), + randomNumberString() + ) predict.trackRecommendationClick(product) verify(mockPredictInternal).trackRecommendationClick(product) } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/PushTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/PushTest.kt index 30f7ab98..3721af34 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/PushTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/PushTest.kt @@ -1,6 +1,5 @@ package com.emarsys -import android.content.Intent import com.emarsys.core.api.result.CompletionListener import com.emarsys.di.FakeDependencyContainer import com.emarsys.di.setupEmarsysComponent @@ -9,12 +8,9 @@ import com.emarsys.mobileengage.api.push.NotificationInformationListener import com.emarsys.mobileengage.push.PushInternal import com.emarsys.push.Push import com.emarsys.testUtil.IntegrationTestUtils -import com.emarsys.testUtil.TimeoutUtils -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.Mockito import org.mockito.kotlin.mock @@ -25,11 +21,8 @@ class PushTest { private lateinit var mockNotificationInformationListener: NotificationInformationListener private lateinit var push: Push - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockPushInternal = mock() mockCompletionListener = mock() @@ -42,7 +35,7 @@ class PushTest { push = Push() } - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/RemoteConfigIntegrationTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/RemoteConfigIntegrationTest.kt index 1a14399a..d168421b 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/RemoteConfigIntegrationTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/RemoteConfigIntegrationTest.kt @@ -1,20 +1,20 @@ package com.emarsys + import android.app.Application import com.emarsys.config.EmarsysConfig - - import com.emarsys.di.emarsys import com.emarsys.testUtil.* -import com.emarsys.testUtil.rules.DuplicatedThreadRule -import io.kotlintest.shouldBe -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith import java.util.concurrent.CountDownLatch +@ExtendWith(DuplicatedThreadExtension::class) + class RemoteConfigIntegrationTest { private companion object { @@ -28,22 +28,14 @@ class RemoteConfigIntegrationTest { get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Rule - @JvmField - val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") - - @Before + @BeforeEach fun setup() { DatabaseTestUtils.deleteCoreDatabase() baseConfig = EmarsysConfig.Builder() - .application(application) - .applicationCode(APP_ID) - .build() + .application(application) + .applicationCode(APP_ID) + .build() ConnectionTestUtils.checkConnection(application) @@ -52,7 +44,7 @@ class RemoteConfigIntegrationTest { latch = CountDownLatch(1) } - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys(application) } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigLoaderTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigLoaderTest.kt index 007ae74a..b4464e0f 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigLoaderTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigLoaderTest.kt @@ -1,16 +1,15 @@ package com.emarsys.config -import android.app.Activity import android.app.Application import android.content.SharedPreferences -import com.emarsys.Emarsys -import io.kotlintest.matchers.types.shouldBeSameInstanceAs -import io.kotlintest.shouldBe -import org.junit.Assert.* -import org.junit.Before - -import org.junit.Test -import org.mockito.kotlin.* +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever class ConfigLoaderTest { companion object { @@ -25,7 +24,7 @@ class ConfigLoaderTest { private lateinit var mockSharedPreferences: SharedPreferences private lateinit var mockApplication : Application - @Before + @BeforeEach fun setUp() { mockSharedPreferences = mock() mockApplication = mock { diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigTest.kt index 97b6ed4a..aa64b323 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigTest.kt @@ -6,19 +6,18 @@ import com.emarsys.core.endpoint.ServiceEndpointProvider import com.emarsys.di.FakeDependencyContainer import com.emarsys.di.setupEmarsysComponent import com.emarsys.testUtil.IntegrationTestUtils -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import com.emarsys.testUtil.rules.DuplicatedThreadRule -import io.kotlintest.shouldBe -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.mockito.kotlin.doReturn +@ExtendWith(DuplicatedThreadExtension::class) class ConfigTest { @@ -28,18 +27,10 @@ class ConfigTest { private const val INBOX_HOST = "https://me-inbox.eservice.emarsys.net/v3" } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Rule - @JvmField - val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") - lateinit var config: Config lateinit var mockConfigInternal: ConfigInternal - @Before + @BeforeEach fun setUp() { mockConfigInternal = mock(ConfigInternal::class.java) val mockClientServiceProvider: ServiceEndpointProvider = org.mockito.kotlin.mock { @@ -52,10 +43,10 @@ class ConfigTest { on { provideEndpointHost() } doReturn INBOX_HOST } val dependencyContainer = FakeDependencyContainer( - configInternal = mockConfigInternal, - clientServiceEndpointProvider = mockClientServiceProvider, - eventServiceEndpointProvider = mockEventServiceProvider, - messageInboxServiceProvider = mockMessageInboxServiceProvider + configInternal = mockConfigInternal, + clientServiceEndpointProvider = mockClientServiceProvider, + eventServiceEndpointProvider = mockEventServiceProvider, + messageInboxServiceProvider = mockMessageInboxServiceProvider ) setupEmarsysComponent(dependencyContainer) @@ -63,7 +54,7 @@ class ConfigTest { } - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/config/EmarsysConfigTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/config/EmarsysConfigTest.kt index e7f930b5..c47ed96b 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/config/EmarsysConfigTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/config/EmarsysConfigTest.kt @@ -10,14 +10,11 @@ import com.emarsys.mobileengage.api.event.EventHandler import com.emarsys.testUtil.FeatureTestUtils import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.IntegrationTestUtils -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.fail -import io.kotlintest.shouldBe -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.assertions.fail +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -38,11 +35,8 @@ class EmarsysConfigTest { private lateinit var features: Array private var automaticPushTokenSending = false - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { FeatureTestUtils.resetFeatures() val mockClientServiceProvider: ServiceEndpointProvider = mock { @@ -73,7 +67,7 @@ class EmarsysConfigTest { ) } - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys(application) } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/deeplink/DeepLinkTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/deeplink/DeepLinkTest.kt index cdb36c99..812f80f4 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/deeplink/DeepLinkTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/deeplink/DeepLinkTest.kt @@ -7,9 +7,9 @@ import com.emarsys.di.FakeDependencyContainer import com.emarsys.di.setupEmarsysComponent import com.emarsys.mobileengage.deeplink.DeepLinkInternal import com.emarsys.testUtil.IntegrationTestUtils -import org.junit.After -import org.junit.Before -import org.junit.Test +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -20,7 +20,7 @@ class DeepLinkTest { private lateinit var deeplinkApi: DeepLink - @Before + @BeforeEach fun setUp() { mockActivity = mock() mockCompletionListener = mock() @@ -30,7 +30,8 @@ class DeepLinkTest { setupEmarsysComponent(FakeDependencyContainer( deepLinkInternal = mockDeepLinkInternal)) } - @After + + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/di/EmarsysDependencyInjectionTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/di/EmarsysDependencyInjectionTest.kt index 58f98c30..dcdb751a 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/di/EmarsysDependencyInjectionTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/di/EmarsysDependencyInjectionTest.kt @@ -2,14 +2,14 @@ package com.emarsys.di import com.emarsys.geofence.Geofence import com.emarsys.testUtil.IntegrationTestUtils -import io.kotlintest.shouldBe -import org.junit.After -import org.junit.Test +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock class EmarsysDependencyInjectionTest { - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/eventservice/EventServiceTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/eventservice/EventServiceTest.kt index cc01eccf..30100bd7 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/eventservice/EventServiceTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/eventservice/EventServiceTest.kt @@ -5,12 +5,9 @@ import com.emarsys.di.FakeDependencyContainer import com.emarsys.di.setupEmarsysComponent import com.emarsys.mobileengage.event.EventServiceInternal import com.emarsys.testUtil.IntegrationTestUtils -import com.emarsys.testUtil.TimeoutUtils -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -18,8 +15,8 @@ class EventServiceTest { companion object { private const val EVENT_NAME = "testEventName" private val EVENT_ATTRIBUTES = mapOf( - "key1" to "value1", - "key2" to "value2" + "key1" to "value1", + "key2" to "value2" ) } @@ -27,11 +24,8 @@ class EventServiceTest { private lateinit var mockEventServiceInternal: EventServiceInternal private lateinit var eventServiceApi: EventServiceApi - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockCompletionListener = mock() mockEventServiceInternal = mock() @@ -40,7 +34,7 @@ class EventServiceTest { setupEmarsysComponent(FakeDependencyContainer(eventServiceInternal = mockEventServiceInternal)) } - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/geofence/GeofenceTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/geofence/GeofenceTest.kt index c25ef3ff..aecf297a 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/geofence/GeofenceTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/geofence/GeofenceTest.kt @@ -6,12 +6,9 @@ import com.emarsys.di.setupEmarsysComponent import com.emarsys.mobileengage.api.event.EventHandler import com.emarsys.mobileengage.geofence.GeofenceInternal import com.emarsys.testUtil.IntegrationTestUtils -import com.emarsys.testUtil.TimeoutUtils -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -21,11 +18,8 @@ class GeofenceTest { private lateinit var geofenceProxy: GeofenceApi private lateinit var mockGeofenceInternal: GeofenceInternal - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockGeofenceInternal = mock() val dependencyContainer = FakeDependencyContainer(geofenceInternal = mockGeofenceInternal) @@ -35,7 +29,7 @@ class GeofenceTest { geofenceProxy = Geofence() } - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/inapp/ui/InlineInAppViewTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/inapp/ui/InlineInAppViewTest.kt index 0abb0199..0cc7203c 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/inapp/ui/InlineInAppViewTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/inapp/ui/InlineInAppViewTest.kt @@ -1,6 +1,6 @@ package com.emarsys.inapp.ui -import androidx.test.rule.ActivityTestRule +import androidx.test.core.app.ActivityScenario import com.emarsys.core.CoreCompletionHandler import com.emarsys.core.api.ResponseErrorException import com.emarsys.core.api.result.CompletionListener @@ -22,16 +22,13 @@ import com.emarsys.mobileengage.iam.webview.IamWebViewFactory import com.emarsys.mobileengage.request.MobileEngageRequestModelFactory import com.emarsys.testUtil.ExtensionTestUtils.runOnMain import com.emarsys.testUtil.IntegrationTestUtils -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.fake.FakeActivity -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe import org.json.JSONObject -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.Mockito.spy import org.mockito.kotlin.any import org.mockito.kotlin.doReturn @@ -59,64 +56,60 @@ class InlineInAppViewTest { private lateinit var mockJsBridge: IamJsBridge private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder private lateinit var mockJsCommandFactory: JSCommandFactory - private lateinit var inlineInAppView: InlineInAppView + private lateinit var scenario: ActivityScenario - @Rule - @JvmField - var activityTestRule = ActivityTestRule(FakeActivity::class.java) - - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { + concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() mockJsBridge = mock() mockIamJsBridgeFactory = mock { on { createJsBridge(any()) } doReturn mockJsBridge } mockJsCommandFactory = mock() + scenario = ActivityScenario.launch(FakeActivity::class.java) + scenario.onActivity { activity -> + mockIamWebView = spy(runOnMain { + IamWebView( + concurrentHandlerHolder, + mockIamJsBridgeFactory, + mockJsCommandFactory, + activity + ) + }) + + mockWebViewFactory = mock { + on { create(activity) }.thenReturn(mockIamWebView) + } + mockRequestModel = mock { + on { id } doReturn REQUEST_ID + } + mockResponseModel = mock { + on { requestModel } doReturn mockRequestModel + } + mockRequestManager = mock() + mockRequestModelFactory = mock { + on { createFetchInlineInAppMessagesRequest("testViewId") }.doReturn(mockRequestModel) + } - mockIamWebView = spy(runOnMain { - IamWebView( - concurrentHandlerHolder, - mockIamJsBridgeFactory, - mockJsCommandFactory, - activityTestRule.activity + setupEmarsysComponent( + FakeDependencyContainer( + webViewFactory = mockWebViewFactory, + concurrentHandlerHolder = concurrentHandlerHolder, + requestManager = mockRequestManager, + mobileEngageRequestModelFactory = mockRequestModelFactory, + ) ) - }) - mockWebViewFactory = mock { - on { create(activityTestRule.activity) }.thenReturn(mockIamWebView) - } - mockRequestModel = mock { - on { id } doReturn REQUEST_ID + inlineInAppView = InlineInAppView(activity) } - mockResponseModel = mock { - on { requestModel } doReturn mockRequestModel - } - mockRequestManager = mock() - mockRequestModelFactory = mock { - on { createFetchInlineInAppMessagesRequest("testViewId") }.doReturn(mockRequestModel) - } - - setupEmarsysComponent( - FakeDependencyContainer( - webViewFactory = mockWebViewFactory, - concurrentHandlerHolder = concurrentHandlerHolder, - requestManager = mockRequestManager, - mobileEngageRequestModelFactory = mockRequestModelFactory, - ) - ) - - inlineInAppView = InlineInAppView(activityTestRule.activity) - runOnMain {} } - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys() + scenario.close() } @Test diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/inbox/MessageInboxTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/inbox/MessageInboxTest.kt index 7d55643d..ebe2479a 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/inbox/MessageInboxTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/inbox/MessageInboxTest.kt @@ -8,9 +8,9 @@ import com.emarsys.di.setupEmarsysComponent import com.emarsys.mobileengage.api.inbox.InboxResult import com.emarsys.mobileengage.inbox.MessageInboxInternal import com.emarsys.testUtil.IntegrationTestUtils -import org.junit.After -import org.junit.Before -import org.junit.Test +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.eq import org.mockito.kotlin.mock @@ -25,7 +25,7 @@ class MessageInboxTest { private lateinit var inbox: MessageInboxApi private lateinit var mockInboxInternal: MessageInboxInternal - @Before + @BeforeEach fun setUp() { mockInboxInternal = mock() val dependencyContainer = FakeDependencyContainer(messageInboxInternal = mockInboxInternal) @@ -34,7 +34,7 @@ class MessageInboxTest { inbox = MessageInbox() } - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/MobileEngageTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/MobileEngageTest.kt index b9a73670..59083bc3 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/MobileEngageTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/MobileEngageTest.kt @@ -4,9 +4,9 @@ import com.emarsys.core.api.result.CompletionListener import com.emarsys.di.FakeDependencyContainer import com.emarsys.di.setupEmarsysComponent import com.emarsys.testUtil.IntegrationTestUtils -import org.junit.After -import org.junit.Before -import org.junit.Test +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -21,7 +21,7 @@ class MobileEngageTest { private lateinit var mobileEngageApi: MobileEngage - @Before + @BeforeEach fun setUp() { mockMobileEngageInternal = mock() mockCompletionListener = mock() @@ -30,7 +30,7 @@ class MobileEngageTest { setupEmarsysComponent(FakeDependencyContainer(mobileEngageInternal = mockMobileEngageInternal)) } - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/service/mapper/RemoteMessageMapperFactoryTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/service/mapper/RemoteMessageMapperFactoryTest.kt index f636d622..12b90045 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/service/mapper/RemoteMessageMapperFactoryTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/service/mapper/RemoteMessageMapperFactoryTest.kt @@ -4,9 +4,9 @@ import android.content.Context import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.resource.MetaDataReader import com.emarsys.testUtil.InstrumentationRegistry -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Test +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock @@ -16,7 +16,7 @@ class RemoteMessageMapperFactoryTest { private lateinit var mockUuidProvider: UUIDProvider private lateinit var remoteMessageMapperFactory: RemoteMessageMapperFactory - @Before + @BeforeEach fun init() { mockMetaDataReader = mock() context = InstrumentationRegistry.getTargetContext() diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/oneventaction/OnEventActionTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/oneventaction/OnEventActionTest.kt index 22ef9c45..d1e0f22a 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/oneventaction/OnEventActionTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/oneventaction/OnEventActionTest.kt @@ -6,13 +6,10 @@ import com.emarsys.di.setupEmarsysComponent import com.emarsys.mobileengage.api.event.EventHandler import com.emarsys.mobileengage.event.CacheableEventHandler import com.emarsys.testUtil.IntegrationTestUtils -import com.emarsys.testUtil.TimeoutUtils import org.json.JSONObject -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -23,21 +20,20 @@ class OnEventActionTest { private lateinit var onEventAction: OnEventAction private lateinit var mockOnEventActionCacheableEventHandler: CacheableEventHandler - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockEventHandler = mock() mockOnEventActionCacheableEventHandler = mock() - setupEmarsysComponent(FakeDependencyContainer( - onEventActionCacheableEventHandler = mockOnEventActionCacheableEventHandler) + setupEmarsysComponent( + FakeDependencyContainer( + onEventActionCacheableEventHandler = mockOnEventActionCacheableEventHandler + ) ) onEventAction = OnEventAction() } - @After + @AfterEach fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/predict/PredictRestrictedTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/predict/PredictRestrictedTest.kt index b5572090..c8a7dec1 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/predict/PredictRestrictedTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/predict/PredictRestrictedTest.kt @@ -5,12 +5,9 @@ import com.emarsys.di.FakeDependencyContainer import com.emarsys.di.emarsys import com.emarsys.di.setupEmarsysComponent import com.emarsys.di.tearDownEmarsysComponent -import com.emarsys.testUtil.TimeoutUtils -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.Mockito import org.mockito.kotlin.mock @@ -22,11 +19,8 @@ class PredictRestrictedTest { private lateinit var mockPredictInternal: PredictInternal private lateinit var predictRestricted: PredictRestricted - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockPredictInternal = mock() @@ -36,7 +30,7 @@ class PredictRestrictedTest { predictRestricted = PredictRestricted() } - @After + @AfterEach fun tearDown() { try { emarsys().concurrentHandlerHolder.coreLooper.quit() diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/provider/SharedHardwareIdentificationContentProviderTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/provider/SharedHardwareIdentificationContentProviderTest.kt index 948a2d15..fc638539 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/provider/SharedHardwareIdentificationContentProviderTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/provider/SharedHardwareIdentificationContentProviderTest.kt @@ -3,19 +3,16 @@ package com.emarsys.provider import android.content.Context import android.database.Cursor import android.net.Uri -import android.test.ProviderTestCase2 import com.emarsys.core.database.CoreSQLiteDatabase import com.emarsys.core.database.helper.CoreDbHelper import com.emarsys.testUtil.ReflectionTestUtils -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.Before -import org.junit.Test -import org.mockito.kotlin.doReturn -import org.mockito.kotlin.mock +import io.kotest.matchers.shouldBe +import io.mockk.every +import io.mockk.mockk +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test - -class SharedHardwareIdentificationContentProviderTest : ProviderTestCase2(SharedHardwareIdentificationContentProvider::class.java, "com.emarsys.test") { +class SharedHardwareIdentificationContentProviderTest { private companion object { const val ENCRYPTED_HARDWARE_ID = "encrypted_hardware_id" @@ -23,65 +20,78 @@ class SharedHardwareIdentificationContentProviderTest : ProviderTestCase2(provider, "coreDbHelper") - result shouldBe null - - provider.onCreate() - - result = ReflectionTestUtils.getInstanceField(provider, "coreDbHelper") - result shouldNotBe null + val result = provider.onCreate() + result shouldBe true } @Test fun testQuery_shouldReturnCursorWithEncryptedHardwareId_salt_iv() { - val mockContext: Context = mock { - on { packageName } doReturn "com.emarsys.test" + val mockContext: Context = mockk { + every { packageName } returns "com.emarsys.test" } - ReflectionTestUtils.setInstanceField(provider, "coreDbHelper", mockCoreDbHelper) + ReflectionTestUtils.setInstanceField(provider, "mContext", mockContext) - val cursor = provider.query(Uri.parse("content://com.emarsys.test/hardware_identification"), - null, null, null, null) + val cursor = provider.query( + Uri.parse("content://com.emarsys.test/hardware_identification"), + null, null, null, null + ) - cursor shouldNotBe null cursor shouldBe mockCursor } @Test fun testQuery_shouldReturnNull_whenInvalidRequest() { - val mockContext: Context = mock { - on { packageName } doReturn "com.emarsys.test" + val mockContext: Context = mockk { + every { packageName } returns "com.emarsys.test" } - ReflectionTestUtils.setInstanceField(provider, "coreDbHelper", mockCoreDbHelper) + ReflectionTestUtils.setInstanceField(provider, "mContext", mockContext) - val cursor = provider.query(Uri.parse("content://com.emarsys.test/hardware/other"), null, null, null, null) + val cursor = provider.query( + Uri.parse("content://com.emarsys.test/hardware/other"), + null, + null, + null, + null + ) cursor shouldBe null } } \ No newline at end of file diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/testUtil/IntegrationTestUtils.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/testUtil/IntegrationTestUtils.kt index ffbfeeea..a83eb485 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/testUtil/IntegrationTestUtils.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/testUtil/IntegrationTestUtils.kt @@ -11,7 +11,7 @@ import androidx.lifecycle.ProcessLifecycleOwner import com.emarsys.Emarsys import com.emarsys.di.emarsys import com.emarsys.di.tearDownEmarsysComponent -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import java.util.concurrent.CountDownLatch object IntegrationTestUtils { diff --git a/emarsys-sdk/src/main/java/com/emarsys/Emarsys.kt b/emarsys-sdk/src/main/java/com/emarsys/Emarsys.kt index bb6ea8bf..4a267314 100644 --- a/emarsys-sdk/src/main/java/com/emarsys/Emarsys.kt +++ b/emarsys-sdk/src/main/java/com/emarsys/Emarsys.kt @@ -81,12 +81,12 @@ object Emarsys { emarsys().concurrentHandlerHolder.postOnMain { try { registerLifecycleObservers() + registerWatchDogs(emarsysConfig) } catch (e: Throwable) { Logger.error(CrashLog(e)) } } - registerWatchDogs(emarsysConfig) emarsys().concurrentHandlerHolder.coreHandler.post { registerDatabaseTriggers() diff --git a/emarsys-sdk/src/main/java/com/emarsys/provider/SharedHardwareIdentificationContentProvider.kt b/emarsys-sdk/src/main/java/com/emarsys/provider/SharedHardwareIdentificationContentProvider.kt index 72e3733e..f19947fa 100644 --- a/emarsys-sdk/src/main/java/com/emarsys/provider/SharedHardwareIdentificationContentProvider.kt +++ b/emarsys-sdk/src/main/java/com/emarsys/provider/SharedHardwareIdentificationContentProvider.kt @@ -9,7 +9,7 @@ import com.emarsys.core.database.helper.CoreDbHelper class SharedHardwareIdentificationContentProvider : ContentProvider() { - private lateinit var coreDbHelper: CoreDbHelper + lateinit var coreDbHelper: CoreDbHelper override fun onCreate(): Boolean { this.context?.let { diff --git a/emarsys/build.gradle.kts b/emarsys/build.gradle.kts index 869078f5..9e5f2b81 100644 --- a/emarsys/build.gradle.kts +++ b/emarsys/build.gradle.kts @@ -16,11 +16,29 @@ dependencies { implementation(project(":predict")) androidTestImplementation(project(":testUtils")) + + coreLibraryDesugaring(libs.android.tools.desugar) } android { namespace = "com.emarsys.inner" defaultConfig { compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + + multiDexEnabled = true + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + testInstrumentationRunnerArgument( + "runnerBuilder", + "de.mannodermaus.junit5.AndroidJUnit5Builder" + ) + } + compileOptions { + isCoreLibraryDesugaringEnabled = true + } + packaging { + resources { + excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + } } } diff --git a/emarsys/src/androidTest/java/com/emarsys/EmarsysRequestModelFactoryTest.kt b/emarsys/src/androidTest/java/com/emarsys/EmarsysRequestModelFactoryTest.kt index 9a25c7a0..8cd34c7c 100644 --- a/emarsys/src/androidTest/java/com/emarsys/EmarsysRequestModelFactoryTest.kt +++ b/emarsys/src/androidTest/java/com/emarsys/EmarsysRequestModelFactoryTest.kt @@ -6,12 +6,11 @@ import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.request.model.RequestMethod import com.emarsys.core.request.model.RequestModel import com.emarsys.mobileengage.MobileEngageRequestContext -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -30,11 +29,8 @@ class EmarsysRequestModelFactoryTest { private lateinit var requestFactory: EmarsysRequestModelFactory private lateinit var mockMobileEngageRequestContext: MobileEngageRequestContext - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockTimeStampProvider = mock { on { provideTimestamp() } doReturn TIMESTAMP diff --git a/emarsys/src/androidTest/java/com/emarsys/config/DefaultConfigInternalTest.kt b/emarsys/src/androidTest/java/com/emarsys/config/DefaultConfigInternalTest.kt index c2d97ed1..09a0af14 100644 --- a/emarsys/src/androidTest/java/com/emarsys/config/DefaultConfigInternalTest.kt +++ b/emarsys/src/androidTest/java/com/emarsys/config/DefaultConfigInternalTest.kt @@ -35,15 +35,25 @@ import com.emarsys.predict.PredictInternal import com.emarsys.predict.request.PredictRequestContext import com.emarsys.testUtil.ExtensionTestUtils.tryCast import com.emarsys.testUtil.FeatureTestUtils -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.ThreadSpy -import io.kotlintest.shouldBe -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.* +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.eq +import org.mockito.kotlin.inOrder +import org.mockito.kotlin.mock +import org.mockito.kotlin.spy +import org.mockito.kotlin.timeout +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.verifyNoMoreInteractions +import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch class DefaultConfigInternalTest { @@ -87,11 +97,8 @@ class DefaultConfigInternalTest { private lateinit var mockCompletionListener: CompletionListener private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun setUp() { FeatureTestUtils.resetFeatures() @@ -180,7 +187,7 @@ class DefaultConfigInternalTest { ) } - @After + @AfterEach fun tearDown() { FeatureTestUtils.resetFeatures() } diff --git a/emarsys/src/androidTest/java/com/emarsys/config/FetchRemoteConfigActionTest.kt b/emarsys/src/androidTest/java/com/emarsys/config/FetchRemoteConfigActionTest.kt index c401b738..ebd3be39 100644 --- a/emarsys/src/androidTest/java/com/emarsys/config/FetchRemoteConfigActionTest.kt +++ b/emarsys/src/androidTest/java/com/emarsys/config/FetchRemoteConfigActionTest.kt @@ -4,12 +4,9 @@ import com.emarsys.core.api.result.CompletionListener import com.emarsys.fake.FakeEmarsysDependencyContainer import com.emarsys.mobileengage.di.setupMobileEngageComponent import com.emarsys.mobileengage.di.tearDownMobileEngageComponent -import com.emarsys.testUtil.TimeoutUtils -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.Mockito.verify import org.mockito.kotlin.mock import org.mockito.kotlin.timeout @@ -22,21 +19,19 @@ class FetchRemoteConfigActionTest { private lateinit var mockConfigInternal: ConfigInternal private lateinit var mockCompletionListener: CompletionListener - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setup() { mockConfigInternal = mock() mockCompletionListener = mock() setupMobileEngageComponent(FakeEmarsysDependencyContainer()) - fetchAction = FetchRemoteConfigAction(mockConfigInternal, completionListener = mockCompletionListener) + fetchAction = + FetchRemoteConfigAction(mockConfigInternal, completionListener = mockCompletionListener) } - @After + @AfterEach fun tearDown() { tearDownMobileEngageComponent() } diff --git a/emarsys/src/androidTest/java/com/emarsys/config/RemoteConfigResponseMapperTest.kt b/emarsys/src/androidTest/java/com/emarsys/config/RemoteConfigResponseMapperTest.kt index 38acc5d4..cfd3ca50 100644 --- a/emarsys/src/androidTest/java/com/emarsys/config/RemoteConfigResponseMapperTest.kt +++ b/emarsys/src/androidTest/java/com/emarsys/config/RemoteConfigResponseMapperTest.kt @@ -6,13 +6,12 @@ import com.emarsys.core.provider.hardwareid.HardwareIdProvider import com.emarsys.core.provider.random.RandomProvider import com.emarsys.core.response.ResponseModel import com.emarsys.core.util.log.LogLevel -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.mock import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -26,11 +25,7 @@ class RemoteConfigResponseMapperTest { private lateinit var remoteConfigResponseMapper: RemoteConfigResponseMapper - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Before + @BeforeEach fun setup() { mockResponseModel = mock(ResponseModel::class.java) mockRandomProvider = mock(RandomProvider::class.java) @@ -38,7 +33,8 @@ class RemoteConfigResponseMapperTest { on { provideHardwareId() } doReturn "testHardwareId" } - remoteConfigResponseMapper = RemoteConfigResponseMapper(mockRandomProvider, mockHardwareIdProvider) + remoteConfigResponseMapper = + RemoteConfigResponseMapper(mockRandomProvider, mockHardwareIdProvider) } @Test diff --git a/gradle.properties b/gradle.properties index 937cefce..c3b3768a 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,4 +4,4 @@ android.useAndroidX=true android.enableJetifier=true org.gradle.parallel=true org.gradle.vfs.watch=true -android.defaults.buildfeatures.buildconfig=true \ No newline at end of file +#android.enableBuildConfigAsBytecode=true \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index a142ea2c..a26472e0 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,49 +1,68 @@ [versions] agp = "8.2.2" +androidx-test-core = "1.4.0" kotlin = "1.9.21" kotlinxCoroutines = "1.7.3" compose = "1.6.1" +androidx-navigation-compose = "2.7.6" compose-compiler = "1.5.6" compose-plugin = "1.6.0-dev1419" android-compileSdk = "34" android-minSdk = "28" android-targetSdk = "34" +androidx-activity = "1.8.2" androidx-activityCompose = "1.8.2" androidx-annotation = "1.7.1" androidx-appcompat = "1.6.1" androidx-constraintlayout = "2.1.4" androidx-core-ktx = "1.12.0" +androidx-datastore-preferences = "1.0.0" androidx-espresso-core = "3.5.1" androidx-material = "1.11.0" androidx-test-runner = "1.5.2" +androidx-test-rules = "1.5.0" androidx-test-junit = "1.1.5" +androidx-test-fragment = "1.6.2" +androidx-test-multidex = "2.0.0" androidx-lifecycle = "2.7.0" androidx-espresso-idling-resource = "3.5.1" androidx-security-crypto = "1.1.0-alpha06" androidx-navigation-safe-args = "2.5.0" +io-coil = "2.5.0" dokka = "1.9.10" junit = "4.13.2" +playServicesAuth = "20.7.0" tink = "1.9.0" +kotpref = "2.13.0" kotest = "5.8.0" mockk = "1.13.9" fcm = "23.4.0" +firebase-common = "20.4.2" +google-gson = "2.10.1" agconnect_core = "1.9.1.300" hms_push = "6.11.0.300" googleServices = "4.4.1" -location-services = "21.1.0" +google-play-services-location = "21.1.0" +google-play-services-auth = "20.7.0" +google-accompanist-swipetorefresh = "0.34.0" webkit = "1.7.0" -mockito = "4.9.0" +mockito-android = "5.10.0" +mockito-core = "5.10.0" mockito-kotlin = "4.1.0" grGit = "5.0.0-rc.3" byte-buddy = "1.14.11" dotEnv = "4.0.0" +android-tools-desugar = "2.0.4" +benManesVersions = "0.51.0" +android-junit5 = "1.10.0.0" [libraries] +androidx-test-core = { module = "androidx.test:core", version.ref = "androidx-test-core" } kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" } kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" } kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinxCoroutines" } kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinxCoroutines" } -androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "androidx-core-ktx" } +android-tools-desugar = { module = "com.android.tools:desugar_jdk_libs_nio", version.ref = "android-tools-desugar" } androidx-runner = { module = "androidx.test:runner", version.ref = "androidx-test-runner" } androidx-test-junit = { group = "androidx.test.ext", name = "junit", version.ref = "androidx-test-junit" } androidx-espresso-idling-resource = { group = "androidx.test.espresso", name = "espresso-idling-resource", version.ref = "androidx-espresso-idling-resource" } @@ -51,36 +70,49 @@ androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-co androidx-annotation = { group = "androidx.annotation", name = "annotation", version.ref = "androidx-annotation" } androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "androidx-appcompat" } androidx-material = { group = "com.google.android.material", name = "material", version.ref = "androidx-material" } +androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidx-test-runner" } +androidx-test-rules = { module = "androidx.test:rules", version.ref = "androidx-test-rules" } +androidx-test-extensions = { module = "androidx.test.ext:junit", version.ref = "androidx-test-junit" } +androidx-test-fragment = { module = "androidx.fragment:fragment-testing", version.ref = "androidx-test-fragment" } +androidx-test-multidex = { module = "androidx.multidex:multidex-instrumentation", version.ref = "androidx-test-multidex" } androidx-constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "androidx-constraintlayout" } +androidx-activity = { module = "androidx.activity:activity", version.ref = "androidx-activity" } androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activityCompose" } +androidx-lifecycle-runtime = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "androidx-lifecycle" } androidx-lifecycle-process = { module = "androidx.lifecycle:lifecycle-process", version.ref = "androidx-lifecycle" } androidx-lifecycle-common-java8 = { module = "androidx.lifecycle:lifecycle-common-java8", version.ref = "androidx-lifecycle" } androidx-security-crypto = { module = "androidx.security:security-crypto", version.ref = "androidx-security-crypto" } androidx-webkit = { module = "androidx.webkit:webkit", version.ref = "webkit" } google-tink = { module = "com.google.crypto.tink:tink-android", version.ref = "tink" } -google-location = { module = "com.google.android.gms:play-services-location", version.ref = "location-services" } -google-fcm = { group = "com.google.firebase", name = "firebase-messaging", version.ref = "fcm" } +google-play-services-location = { module = "com.google.android.gms:play-services-location", version.ref = "google-play-services-location" } +google-play-services-auth = { module = "androidx.core:core-ktx", version.ref = "google-play-services-auth" } +google-firebase-messaging = { group = "com.google.firebase", name = "firebase-messaging", version.ref = "fcm" } +google-firebase-common = { group = "com.google.firebase", name = "firebase-common", version.ref = "firebase-common" } +google-accompanist-swipetorefresh = { module = "com.google.accompanist:accompanist-swiperefresh", version.ref = "google-accompanist-swipetorefresh" } +google-gson = { module = "com.google.code.gson:gson", version.ref = "google-gson" } huawei-hms-push = { group = "com.huawei.hms", name = "push", version.ref = "hms_push" } huawei-agconnect-core = { group = "com.huawei.agconnect", name = "agconnect-core", version.ref = "agconnect_core" } -compose-ui = { module = "androidx.compose.ui:ui", version.ref = "compose" } -compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling", version.ref = "compose" } -compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview", version.ref = "compose" } -compose-foundation = { module = "androidx.compose.foundation:foundation", version.ref = "compose" } -compose-material = { module = "androidx.compose.material:material", version.ref = "compose" } +androidx-datastore-preferences = { module = "androidx.datastore:datastore-preferences", version.ref = "androidx-datastore-preferences" } +androidx-compose-ui = { module = "androidx.compose.ui:ui", version.ref = "compose" } +androidx-compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling", version.ref = "compose" } +androidx-compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview", version.ref = "compose" } +androidx-compose-foundation = { module = "androidx.compose.foundation:foundation", version.ref = "compose" } +androidx-navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "androidx-navigation-compose" } +androidx-compose-material = { module = "androidx.compose.material:material", version.ref = "compose" } +androidx-compose-material-icons = { module = "androidx.compose.material:material-icons-extended", version.ref = "compose" } +androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "androidx-core-ktx" } +io-coil = { module = "io.coil-kt:coil-compose", version.ref = "io-coil" } +io-coil-compose = { module = "io.coil-kt:coil", version.ref = "io-coil" } junit = { group = "junit", name = "junit", version.ref = "junit" } kotest-assertions-core = { module = "io.kotest:kotest-assertions-core", version.ref = "kotest" } kotest-framework-engine = { module = "io.kotest:kotest-framework-engine", version.ref = "kotest" } mockk-android = { module = "io.mockk:mockk-android", version.ref = "mockk" } mockk-agent = { module = "io.mockk:mockk-agent-jvm", version.ref = "mockk" } -mockito-android = { module = "org.mockito:mockito-android", version.ref = "mockito" } +mockito-android = { module = "org.mockito:mockito-android", version.ref = "mockito-android" } mockito-kotlin = { module = "org.mockito.kotlin:mockito-kotlin", version.ref = "mockito-kotlin" } -mockito-core = { module = "org.mockito.kotlin:mockito-core", version.ref = "mockito" } byte-buddy = { module = "net.bytebuddy:byte-buddy", version.ref = "byte-buddy" } -androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidx-test-runner" } -androidx-test-rules = { module = "androidx.test:rules", version.ref = "androidx-test-runner" } -androidx-test-extensions = { module = "androidx.test.ext:junit", version.ref = "androidx-test-runner" } -androidx-test-fragment = { module = "androidx.fragment:fragment-testing", version.ref = "androidx-test-runner" } -androidx-test-multidex = { module = "androidx.multidex:multidex-instrumentation", version.ref = "androidx-test-runner" } +play-services-auth = { module = "com.google.android.gms:play-services-auth", version.ref = "playServicesAuth" } +kotpref = { module = "com.chibatching.kotpref:kotpref", version.ref = "kotpref" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" } @@ -95,3 +127,5 @@ huawei-agconnect = { id = "com.huawei.agconnect", version.ref = "agconnect_core" google-services = { id = "com.google.gms.google-services", version.ref = "googleServices" } grgit = { id = "org.ajoberstar.grgit", version.ref = "grGit" } dotenv = { id = "co.uzzu.dotenv.gradle", version.ref = "dotEnv" } +ben-manes-versions = { id = "com.github.ben-manes.versions", version.ref = "benManesVersions" } +android-junit5 = { id = "de.mannodermaus.android-junit5", version.ref = "android-junit5" } diff --git a/mobile-engage-api/build.gradle.kts b/mobile-engage-api/build.gradle.kts index 38cc2c3e..b42470a4 100644 --- a/mobile-engage-api/build.gradle.kts +++ b/mobile-engage-api/build.gradle.kts @@ -8,18 +8,35 @@ plugins { dependencies { implementation(project(":core-api")) - api(libs.google.location) + api(libs.google.play.services.location) androidTestImplementation(project(":testUtils")) + + coreLibraryDesugaring(libs.android.tools.desugar) } android { namespace = "com.emarsys.mobileengage.api" defaultConfig { compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + + multiDexEnabled = true + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + testInstrumentationRunnerArgument( + "runnerBuilder", + "de.mannodermaus.junit5.AndroidJUnit5Builder" + ) + } + compileOptions { + isCoreLibraryDesugaringEnabled = true + } + packaging { + resources { + excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + } } } - allOpen { annotation("com.emarsys.core.Mockable") } diff --git a/mobile-engage-api/src/androidTest/java/com/emarsys/mobileengage/api/MEApiTest.kt b/mobile-engage-api/src/androidTest/java/com/emarsys/mobileengage/api/MEApiTest.kt index a7c3ea0a..c5f18a4b 100644 --- a/mobile-engage-api/src/androidTest/java/com/emarsys/mobileengage/api/MEApiTest.kt +++ b/mobile-engage-api/src/androidTest/java/com/emarsys/mobileengage/api/MEApiTest.kt @@ -1,15 +1,11 @@ package com.emarsys.mobileengage.api -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule + +import org.junit.jupiter.api.Test + class MEApiTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun test() { diff --git a/mobile-engage/build.gradle.kts b/mobile-engage/build.gradle.kts index 5eb7ffa1..c87207db 100644 --- a/mobile-engage/build.gradle.kts +++ b/mobile-engage/build.gradle.kts @@ -15,11 +15,31 @@ dependencies { implementation(libs.androidx.webkit) androidTestImplementation(project(":testUtils")) + + coreLibraryDesugaring(libs.android.tools.desugar) } android { namespace = "com.emarsys.mobileengage" defaultConfig { compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + + multiDexEnabled = true + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + testInstrumentationRunnerArgument( + "runnerBuilder", + "de.mannodermaus.junit5.AndroidJUnit5Builder" + ) + } + compileOptions { + isCoreLibraryDesugaringEnabled = true + } + + packaging { + resources { + excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + } } } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/DefaultMobileEngageInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/DefaultMobileEngageInternalTest.kt index cafa3d08..914b156a 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/DefaultMobileEngageInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/DefaultMobileEngageInternalTest.kt @@ -12,12 +12,19 @@ import com.emarsys.mobileengage.push.PushInternal import com.emarsys.mobileengage.request.MobileEngageRequestModelFactory import com.emarsys.mobileengage.session.MobileEngageSession import com.emarsys.mobileengage.session.SessionIdHolder -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.* +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.eq +import org.mockito.kotlin.inOrder +import org.mockito.kotlin.isNull +import org.mockito.kotlin.mock +import org.mockito.kotlin.spy +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoMoreInteractions +import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit @@ -67,11 +74,8 @@ class DefaultMobileEngageInternalTest { private lateinit var mockSession: MobileEngageSession private lateinit var mockSessionIdHolder: SessionIdHolder - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun setUp() { mockEventServiceInternal = mock() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/MobileEngageRequestContextTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/MobileEngageRequestContextTest.kt index 5cb8f612..9ec37f05 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/MobileEngageRequestContextTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/MobileEngageRequestContextTest.kt @@ -1,18 +1,15 @@ package com.emarsys.mobileengage -import com.emarsys.core.storage.StringStorage -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Test -import org.mockito.kotlin.doReturn +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock -import org.mockito.kotlin.whenever class MobileEngageRequestContextTest { private lateinit var requestContext: MobileEngageRequestContext - @Before + @BeforeEach fun setUp() { requestContext = MobileEngageRequestContext( diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/client/DefaultClientServiceInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/client/DefaultClientServiceInternalTest.kt index f89b18d3..9f482178 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/client/DefaultClientServiceInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/client/DefaultClientServiceInternalTest.kt @@ -3,12 +3,11 @@ package com.emarsys.mobileengage.client import com.emarsys.core.request.RequestManager import com.emarsys.core.request.model.RequestModel import com.emarsys.mobileengage.request.MobileEngageRequestModelFactory -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito import org.mockito.Mockito.verify @@ -19,11 +18,8 @@ class DefaultClientServiceInternalTest { private lateinit var mockRequestManager: RequestManager private lateinit var clientServiceInternal: ClientServiceInternal - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun setUp() { mockRequestModel = Mockito.mock(RequestModel::class.java) @@ -32,7 +28,8 @@ class DefaultClientServiceInternalTest { mockRequestModelFactory = Mockito.mock(MobileEngageRequestModelFactory::class.java).apply { whenever(createTrackDeviceInfoRequest()).thenReturn(mockRequestModel) } - clientServiceInternal = DefaultClientServiceInternal(mockRequestManager, mockRequestModelFactory) + clientServiceInternal = + DefaultClientServiceInternal(mockRequestManager, mockRequestModelFactory) } @Test diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DeepLinkActionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DeepLinkActionTest.kt index bc1160e0..a82e9d40 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DeepLinkActionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DeepLinkActionTest.kt @@ -6,12 +6,9 @@ import com.emarsys.mobileengage.di.setupMobileEngageComponent import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.util.waitForTask -import com.emarsys.testUtil.TimeoutUtils -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.Mockito import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -29,11 +26,8 @@ class DeepLinkActionTest { private lateinit var deepLinkInternal: DeepLinkInternal private lateinit var action: DeepLinkAction - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { setupMobileEngageComponent(FakeMobileEngageDependencyContainer()) @@ -42,7 +36,7 @@ class DeepLinkActionTest { action = DeepLinkAction(deepLinkInternal) } - @After + @AfterEach fun tearDown() { tearDownMobileEngageComponent() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternalTest.kt index c1eba24b..444f78d5 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternalTest.kt @@ -1,181 +1,172 @@ -package com.emarsys.mobileengage.deeplink; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import android.app.Activity; -import android.content.Intent; -import android.net.Uri; -import android.os.Build; - -import com.emarsys.core.api.result.CompletionListener; -import com.emarsys.core.device.DeviceInfo; -import com.emarsys.core.endpoint.ServiceEndpointProvider; -import com.emarsys.core.provider.timestamp.TimestampProvider; -import com.emarsys.core.provider.uuid.UUIDProvider; -import com.emarsys.core.request.RequestManager; -import com.emarsys.core.request.model.RequestModel; -import com.emarsys.core.storage.StringStorage; -import com.emarsys.mobileengage.MobileEngageRequestContext; -import com.emarsys.mobileengage.session.SessionIdHolder; -import com.emarsys.testUtil.TimeoutUtils; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; -import org.mockito.ArgumentCaptor; -import org.mockito.Mockito; - -import java.util.HashMap; -import java.util.Map; - -public class DefaultDeepLinkInternalTest { - - private Activity mockActivity; - private DeepLinkInternal deepLinkInternal; - private RequestManager manager; - private MobileEngageRequestContext requestContext; - private TimestampProvider timestampProvider; - private UUIDProvider uuidProvider; - private DeviceInfo mockDeviceInfo; - private ServiceEndpointProvider mockDeepLinkServiceProvider; - private static final String APPLICATION_CODE = "applicationCode"; - private static final String DEEPLINK_BASE = "https://deep-link.eservice.emarsys.net"; - @Rule - public TestRule timeout = TimeoutUtils.getTimeoutRule(); - - - @Before - @SuppressWarnings("unchecked") - public void init() { - mockActivity = mock(Activity.class, Mockito.RETURNS_DEEP_STUBS); - - manager = mock(RequestManager.class); - - timestampProvider = mock(TimestampProvider.class); - uuidProvider = mock(UUIDProvider.class); - when(uuidProvider.provideId()).thenReturn("REQUEST_ID"); - mockDeviceInfo = mock(DeviceInfo.class); - when(mockDeviceInfo.getSdkVersion()).thenReturn("0.0.1"); - - requestContext = new MobileEngageRequestContext( - APPLICATION_CODE, - 1, - null, - null, mockDeviceInfo, - timestampProvider, - uuidProvider, - mock(StringStorage.class), - mock(StringStorage.class), - mock(StringStorage.class), - mock(StringStorage.class), - mock(SessionIdHolder.class) - ); - - mockDeepLinkServiceProvider = mock(ServiceEndpointProvider.class); - when(mockDeepLinkServiceProvider.provideEndpointHost()).thenReturn(DEEPLINK_BASE); - deepLinkInternal = new DefaultDeepLinkInternal(requestContext, mockDeepLinkServiceProvider, manager); +package com.emarsys.mobileengage.deeplink + +import android.app.Activity +import android.content.Intent +import android.net.Uri +import android.os.Build +import com.emarsys.core.api.result.CompletionListener +import com.emarsys.core.device.DeviceInfo +import com.emarsys.core.endpoint.ServiceEndpointProvider +import com.emarsys.core.provider.timestamp.TimestampProvider +import com.emarsys.core.provider.uuid.UUIDProvider +import com.emarsys.core.request.RequestManager +import com.emarsys.core.request.model.RequestModel +import com.emarsys.core.storage.StringStorage +import com.emarsys.mobileengage.MobileEngageRequestContext +import com.emarsys.mobileengage.session.SessionIdHolder +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.ArgumentMatchers.eq +import org.mockito.Mockito +import org.mockito.Mockito.mock +import org.mockito.Mockito.never +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.isNull +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +class DefaultDeepLinkInternalTest { + private lateinit var mockActivity: Activity + private lateinit var deepLinkInternal: DeepLinkInternal + private lateinit var mockManager: RequestManager + private lateinit var requestContext: MobileEngageRequestContext + private lateinit var mockTimestampProvider: TimestampProvider + private lateinit var mockUuidProvider: UUIDProvider + private lateinit var mockDeviceInfo: DeviceInfo + private lateinit var mockDeepLinkServiceProvider: ServiceEndpointProvider + + @BeforeEach + fun init() { + mockActivity = mock(Activity::class.java, Mockito.RETURNS_DEEP_STUBS) + mockManager = mock(RequestManager::class.java) + mockTimestampProvider = mock(TimestampProvider::class.java) + mockUuidProvider = mock(UUIDProvider::class.java) + whenever(mockUuidProvider.provideId()).thenReturn("REQUEST_ID") + mockDeviceInfo = mock(DeviceInfo::class.java) + whenever(mockDeviceInfo.sdkVersion).thenReturn("0.0.1") + requestContext = MobileEngageRequestContext( + APPLICATION_CODE, + 1, + null, + null, mockDeviceInfo, + mockTimestampProvider, + mockUuidProvider, + mock(StringStorage::class.java), + mock(StringStorage::class.java), + mock(StringStorage::class.java), + mock(StringStorage::class.java), + mock(SessionIdHolder::class.java) + ) + mockDeepLinkServiceProvider = Mockito.mock(ServiceEndpointProvider::class.java) + Mockito.`when`(mockDeepLinkServiceProvider.provideEndpointHost()).thenReturn(DEEPLINK_BASE) + deepLinkInternal = + DefaultDeepLinkInternal(requestContext, mockDeepLinkServiceProvider, mockManager) } @Test - public void testTrackDeepLink_doesNotCrashOnNonHierarchicalUris() { - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("mailto:a@b.com")); - - deepLinkInternal.trackDeepLinkOpen(mockActivity, intent, null); + fun testTrackDeepLink_doesNotCrashOnNonHierarchicalUris() { + val intent = Intent(Intent.ACTION_VIEW, Uri.parse("mailto:a@b.com")) + deepLinkInternal.trackDeepLinkOpen(mockActivity, intent, null) } @Test - public void testTrackDeepLink_requestManagerCalled_withCorrectRequestModel() { - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://demo-mobileengage.emarsys.net/something?fancy_url=1&ems_dl=1_2_3_4_5")); - - Map payload = new HashMap<>(); - payload.put("ems_dl", "1_2_3_4_5"); - - Map headers = new HashMap<>(); - headers.put("User-Agent", - String.format("Emarsys SDK %s Android %s", requestContext.getDeviceInfo().getSdkVersion(), Build.VERSION.SDK_INT)); - - RequestModel expected = new RequestModel.Builder(timestampProvider, uuidProvider) - .url(DEEPLINK_BASE + "/api/clicks") - .headers(headers) - .payload(payload) - .build(); - - ArgumentCaptor captor = ArgumentCaptor.forClass(RequestModel.class); - - deepLinkInternal.trackDeepLinkOpen(mockActivity, intent, null); - - verify(manager).submit(captor.capture(), (CompletionListener) isNull()); - - RequestModel result = captor.getValue(); - assertRequestModels(expected, result); + fun testTrackDeepLink_requestManagerCalled_withCorrectRequestModel() { + val intent = Intent( + Intent.ACTION_VIEW, + Uri.parse("https://demo-mobileengage.emarsys.net/something?fancy_url=1&ems_dl=1_2_3_4_5") + ) + val payload: MutableMap = HashMap() + payload["ems_dl"] = "1_2_3_4_5" + val headers: MutableMap = HashMap() + headers["User-Agent"] = String.format( + "Emarsys SDK %s Android %s", + requestContext.deviceInfo.sdkVersion, + Build.VERSION.SDK_INT + ) + val expected = RequestModel.Builder(mockTimestampProvider, mockUuidProvider) + .url(DEEPLINK_BASE + "/api/clicks") + .headers(headers) + .payload(payload) + .build() + argumentCaptor { + deepLinkInternal.trackDeepLinkOpen(mockActivity, intent, null) + Mockito.verify(mockManager) + .submit(this.capture(), isNull()) + val result = this.firstValue + assertRequestModels(expected, result) + + } } @Test - public void testTrackDeepLink_requestManagerCalled_withCorrectCompletionHandler() { - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://demo-mobileengage.emarsys.net/something?fancy_url=1&ems_dl=1_2_3_4_5")); - - CompletionListener completionListener = mock(CompletionListener.class); - - deepLinkInternal.trackDeepLinkOpen(mockActivity, intent, completionListener); - - verify(manager).submit(any(RequestModel.class), eq(completionListener)); + fun testTrackDeepLink_requestManagerCalled_withCorrectCompletionHandler() { + val intent = Intent( + Intent.ACTION_VIEW, + Uri.parse("https://demo-mobileengage.emarsys.net/something?fancy_url=1&ems_dl=1_2_3_4_5") + ) + val completionListener: CompletionListener = mock() + deepLinkInternal.trackDeepLinkOpen(mockActivity, intent, completionListener) + verify(mockManager).submit( + anyOrNull(), eq(completionListener) + ) } @Test - public void testTrackDeepLink_setsClickedFlag_onIntentBundle() { - Intent originalIntent = mock(Intent.class); - when(mockActivity.getIntent()).thenReturn(originalIntent); - - Intent currentIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://demo-mobileengage.emarsys.net/something?fancy_url=1&ems_dl=1_2_3_4_5")); - - deepLinkInternal.trackDeepLinkOpen(mockActivity, currentIntent, null); - - verify(originalIntent).putExtra("ems_deep_link_tracked", true); + fun testTrackDeepLink_setsClickedFlag_onIntentBundle() { + val originalIntent = mock(Intent::class.java) + Mockito.`when`(mockActivity.intent).thenReturn(originalIntent) + val currentIntent = Intent( + Intent.ACTION_VIEW, + Uri.parse("https://demo-mobileengage.emarsys.net/something?fancy_url=1&ems_dl=1_2_3_4_5") + ) + deepLinkInternal.trackDeepLinkOpen(mockActivity, currentIntent, null) + verify(originalIntent).putExtra("ems_deep_link_tracked", true) } @Test - public void testTrackDeepLink_doesNotCallRequestManager_whenTrackedFlagIsSet() { - Intent intentFromActivity = mock(Intent.class); - when(mockActivity.getIntent()).thenReturn(intentFromActivity); - when(intentFromActivity.getBooleanExtra("ems_deep_link_tracked", false)).thenReturn(true); - - Intent currentIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://demo-mobileengage.emarsys.net/something?fancy_url=1&ems_dl=1_2_3_4_5")); - - deepLinkInternal.trackDeepLinkOpen(mockActivity, currentIntent, null); - - verify(manager, times(0)).submit(any(RequestModel.class), (CompletionListener) isNull()); + fun testTrackDeepLink_doesNotCallRequestManager_whenTrackedFlagIsSet() { + val intentFromActivity = mock( + Intent::class.java + ) + Mockito.`when`(mockActivity.intent).thenReturn(intentFromActivity) + Mockito.`when`(intentFromActivity.getBooleanExtra("ems_deep_link_tracked", false)) + .thenReturn(true) + val currentIntent = Intent( + Intent.ACTION_VIEW, + Uri.parse("https://demo-mobileengage.emarsys.net/something?fancy_url=1&ems_dl=1_2_3_4_5") + ) + deepLinkInternal.trackDeepLinkOpen(mockActivity, currentIntent, null) + verify(mockManager, never()).submit(anyOrNull(), isNull()) } @Test - public void testTrackDeepLink_doesNotCallRequestManager_whenDataIsNull() { - Intent intent = new Intent(); - - deepLinkInternal.trackDeepLinkOpen(mockActivity, intent, null); - - verify(manager, times(0)).submit(any(RequestModel.class), (CompletionListener) isNull()); + fun testTrackDeepLink_doesNotCallRequestManager_whenDataIsNull() { + val intent = Intent() + deepLinkInternal.trackDeepLinkOpen(mockActivity, intent, null) + verify(mockManager, never()).submit(anyOrNull(), isNull()) } @Test - public void testTrackDeepLink_doesNotCallRequestManager_whenUriDoesNotContainEmsDlQueryParameter() { - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://demo-mobileengage.emarsys.net/something?fancy_url=1&other=1_2_3_4_5")); - - deepLinkInternal.trackDeepLinkOpen(mockActivity, intent, null); + fun testTrackDeepLink_doesNotCallRequestManager_whenUriDoesNotContainEmsDlQueryParameter() { + val intent = Intent( + Intent.ACTION_VIEW, + Uri.parse("https://demo-mobileengage.emarsys.net/something?fancy_url=1&other=1_2_3_4_5") + ) + deepLinkInternal.trackDeepLinkOpen(mockActivity, intent, null) + verify(mockManager, never()).submit(anyOrNull(), isNull()) + } - verify(manager, times(0)).submit(any(RequestModel.class), (CompletionListener) isNull()); + private fun assertRequestModels(expected: RequestModel, result: RequestModel) { + result.url shouldBe expected.url + result.method shouldBe expected.method + result.payload shouldBe expected.payload + result.headers shouldBe expected.headers } - private void assertRequestModels(RequestModel expected, RequestModel result) { - assertEquals(expected.getUrl(), result.getUrl()); - assertEquals(expected.getMethod(), result.getMethod()); - assertEquals(expected.getPayload(), result.getPayload()); - assertEquals(expected.getHeaders(), result.getHeaders()); + companion object { + private const val APPLICATION_CODE = "applicationCode" + private const val DEEPLINK_BASE = "https://deep-link.eservice.emarsys.net" } } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/device/DeviceInfoStartActionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/device/DeviceInfoStartActionTest.kt index 27b7a7d0..607d8eb4 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/device/DeviceInfoStartActionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/device/DeviceInfoStartActionTest.kt @@ -8,13 +8,10 @@ import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.util.waitForTask import com.emarsys.testUtil.SharedPrefsUtils -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions @@ -26,11 +23,8 @@ class DeviceInfoStartActionTest { private lateinit var startAction: DeviceInfoStartAction private lateinit var mockDeviceInfo: DeviceInfo - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun setUp() { deviceInfoPayloadStorage = mock() @@ -39,11 +33,15 @@ class DeviceInfoStartActionTest { setupMobileEngageComponent(FakeMobileEngageDependencyContainer()) - startAction = DeviceInfoStartAction(mockClientServiceInternal, deviceInfoPayloadStorage, mockDeviceInfo) + startAction = DeviceInfoStartAction( + mockClientServiceInternal, + deviceInfoPayloadStorage, + mockDeviceInfo + ) } - @After + @AfterEach fun tearDown() { SharedPrefsUtils.clearSharedPrefs("emarsys_secure_shared_preferences") tearDownMobileEngageComponent() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/CacheableEventHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/CacheableEventHandlerTest.kt index f2bfa43e..5916e9ab 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/CacheableEventHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/CacheableEventHandlerTest.kt @@ -3,28 +3,21 @@ package com.emarsys.mobileengage.event import android.content.Context import com.emarsys.common.feature.InnerFeature import com.emarsys.core.feature.FeatureRegistry -import com.emarsys.mobileengage.api.event.EventHandler import com.emarsys.testUtil.FeatureTestUtils import com.emarsys.testUtil.ReflectionTestUtils -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe import org.json.JSONObject -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock internal class CacheableEventHandlerTest { private lateinit var cacheableEventHandler: CacheableEventHandler - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { FeatureTestUtils.resetFeatures() cacheableEventHandler = CacheableEventHandler() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/DefaultEventServiceInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/DefaultEventServiceInternalTest.kt index 70e2719d..e985c79a 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/DefaultEventServiceInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/DefaultEventServiceInternalTest.kt @@ -4,12 +4,11 @@ import com.emarsys.core.api.result.CompletionListener import com.emarsys.core.request.RequestManager import com.emarsys.core.request.model.RequestModel import com.emarsys.mobileengage.request.MobileEngageRequestModelFactory -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.mockito.kotlin.spy @@ -31,19 +30,20 @@ class DefaultEventServiceInternalTest { private lateinit var mockRequestModel: RequestModel private lateinit var eventServiceInternal: EventServiceInternal - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockRequestModel = mock(RequestModel::class.java) mockRequestManager = mock(RequestManager::class.java) mockCompletionListener = mock(CompletionListener::class.java) mockRequestModelFactory = mock(MobileEngageRequestModelFactory::class.java).apply { - whenever(createCustomEventRequest(EVENT_NAME, EVENT_ATTRIBUTES)).thenReturn(mockRequestModel) - whenever(createInternalCustomEventRequest(EVENT_NAME, EVENT_ATTRIBUTES)).thenReturn(mockRequestModel) + whenever(createCustomEventRequest(EVENT_NAME, EVENT_ATTRIBUTES)).thenReturn( + mockRequestModel + ) + whenever(createInternalCustomEventRequest(EVENT_NAME, EVENT_ATTRIBUTES)).thenReturn( + mockRequestModel + ) } eventServiceInternal = DefaultEventServiceInternal(mockRequestModelFactory, mockRequestManager) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/fake/FakeRequestManager.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/fake/FakeRequestManager.kt index 074c826a..46ff78a1 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/fake/FakeRequestManager.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/fake/FakeRequestManager.kt @@ -1,7 +1,6 @@ package com.emarsys.mobileengage.fake import com.emarsys.core.CoreCompletionHandler -import com.emarsys.core.Mockable import com.emarsys.core.Registry import com.emarsys.core.api.result.CompletionListener import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory @@ -13,7 +12,7 @@ import com.emarsys.core.response.ResponseModel import com.emarsys.core.shard.ShardModel import org.mockito.kotlin.mock -@Mockable + class FakeRequestManager( private val responseType: ResponseType, private val response: ResponseModel diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt index 34100da4..7a018938 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt @@ -27,20 +27,22 @@ import com.emarsys.mobileengage.notification.ActionCommandFactory import com.emarsys.mobileengage.request.MobileEngageRequestModelFactory import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.ReflectionTestUtils -import com.emarsys.testUtil.TimeoutUtils import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.Geofence import com.google.android.gms.location.GeofencingClient import com.google.android.gms.location.GeofencingRequest import com.google.android.gms.tasks.OnCompleteListener import com.google.android.gms.tasks.Task -import io.kotlintest.shouldBe -import io.mockk.* +import io.kotest.matchers.shouldBe +import io.mockk.Called +import io.mockk.every +import io.mockk.mockk +import io.mockk.slot +import io.mockk.spyk +import io.mockk.verify import org.json.JSONObject -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import java.util.concurrent.CountDownLatch import com.emarsys.mobileengage.api.geofence.Geofence as MEGeofence @@ -77,9 +79,7 @@ class DefaultGeofenceInternalTest { ) } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var mockResponseModel: ResponseModel private lateinit var mockGeofenceRequestModel: RequestModel @@ -104,7 +104,7 @@ class DefaultGeofenceInternalTest { private lateinit var pendingIntent: PendingIntent private lateinit var mockTask: Task - @Before + @BeforeEach fun setUp() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() mockInitialEnterTriggerEnabledStorage = mockk(relaxed = true) { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/FetchGeofencesActionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/FetchGeofencesActionTest.kt index 43e8f6a7..c40baa0e 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/FetchGeofencesActionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/FetchGeofencesActionTest.kt @@ -5,26 +5,21 @@ import com.emarsys.mobileengage.di.setupMobileEngageComponent import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.util.waitForTask -import com.emarsys.testUtil.TimeoutUtils -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify class FetchGeofencesActionTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var mockGeofenceInternal: GeofenceInternal private lateinit var mockActivity: Activity private lateinit var fetchGeofencesAction: FetchGeofencesAction - @Before + @BeforeEach fun setUp() { mockGeofenceInternal = mock() mockActivity = mock() @@ -34,7 +29,7 @@ class FetchGeofencesActionTest { fetchGeofencesAction = FetchGeofencesAction(mockGeofenceInternal) } - @After + @AfterEach fun tearDown() { tearDownMobileEngageComponent() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceFilterTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceFilterTest.kt index 3e195060..d2614d99 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceFilterTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceFilterTest.kt @@ -7,13 +7,12 @@ import com.emarsys.mobileengage.api.geofence.Trigger import com.emarsys.mobileengage.api.geofence.TriggerType import com.emarsys.mobileengage.geofence.model.GeofenceGroup import com.emarsys.mobileengage.geofence.model.GeofenceResponse -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import org.json.JSONObject -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + class GeofenceFilterTest { @@ -32,13 +31,11 @@ class GeofenceFilterTest { ) } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var geofenceFilter: GeofenceFilter - @Before + @BeforeEach fun setUp() { geofenceFilter = GeofenceFilter(allGeofences.size) } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProviderTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProviderTest.kt index 6ed7bf2f..415b04af 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProviderTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProviderTest.kt @@ -2,9 +2,9 @@ package com.emarsys.mobileengage.geofence import android.app.PendingIntent import androidx.test.platform.app.InstrumentationRegistry -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.Test +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.Test class GeofencePendingIntentProviderTest { @Test diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapperTest.kt index 78723336..43ccbcc7 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapperTest.kt @@ -6,14 +6,13 @@ import com.emarsys.mobileengage.api.geofence.Trigger import com.emarsys.mobileengage.api.geofence.TriggerType import com.emarsys.mobileengage.geofence.model.GeofenceGroup import com.emarsys.mobileengage.geofence.model.GeofenceResponse -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import org.json.JSONArray import org.json.JSONObject -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.mock import org.mockito.kotlin.whenever @@ -22,11 +21,8 @@ class GeofenceResponseMapperTest { private lateinit var mockResponseModel: ResponseModel private lateinit var mapper: GeofenceResponseMapper - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mapper = GeofenceResponseMapper() mockResponseModel = mock() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/AppStartActionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/AppStartActionTest.kt index 543c1b99..93a62820 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/AppStartActionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/AppStartActionTest.kt @@ -7,13 +7,10 @@ import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.event.EventServiceInternal import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.util.waitForTask -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions @@ -24,11 +21,8 @@ class AppStartActionTest { private lateinit var mockContactTokenStorage: Storage private lateinit var startAction: AppStartAction - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockEventServiceInternal = mock() mockContactTokenStorage = mock() @@ -38,7 +32,7 @@ class AppStartActionTest { startAction = AppStartAction(mockEventServiceInternal, mockContactTokenStorage) } - @After + @AfterEach fun tearDown() { tearDownMobileEngageComponent() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppEventHandlerInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppEventHandlerInternalTest.kt index c76d3297..b255f986 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppEventHandlerInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppEventHandlerInternalTest.kt @@ -1,36 +1,32 @@ package com.emarsys.mobileengage.iam -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule + +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + class InAppEventHandlerInternalTest { private lateinit var inAppEventHandlerInternal: InAppEventHandlerInternal - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { inAppEventHandlerInternal = InAppEventHandlerInternal() } @Test fun testIsPaused_returnsFalse_byDefault() { - assertFalse(inAppEventHandlerInternal.isPaused) + inAppEventHandlerInternal.isPaused shouldBe false } @Test fun testPause_setsIsPaused_toTrue() { inAppEventHandlerInternal.pause() - assertTrue(inAppEventHandlerInternal.isPaused) + inAppEventHandlerInternal.isPaused shouldBe true } @Test @@ -38,6 +34,6 @@ class InAppEventHandlerInternalTest { inAppEventHandlerInternal.pause() inAppEventHandlerInternal.resume() - assertFalse(inAppEventHandlerInternal.isPaused) + inAppEventHandlerInternal.isPaused shouldBe false } } \ No newline at end of file diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppInternalTest.kt index baf7a9d5..2671388b 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppInternalTest.kt @@ -4,11 +4,10 @@ import com.emarsys.core.api.result.CompletionListener import com.emarsys.core.request.model.RequestModel import com.emarsys.mobileengage.api.event.EventHandler import com.emarsys.mobileengage.event.EventServiceInternal -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.mock import org.mockito.Mockito.verify @@ -25,11 +24,8 @@ class InAppInternalTest { private lateinit var mockCompletionListener: CompletionListener private lateinit var mockEventServiceInternal: EventServiceInternal - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun init() { mockRequestModel = mock(RequestModel::class.java) @@ -37,7 +33,8 @@ class InAppInternalTest { mockEventServiceInternal = mock(EventServiceInternal::class.java) mockInAppEventHandlerInternal = mock(InAppEventHandlerInternal::class.java) - inAppInternal = DefaultInAppInternal(mockInAppEventHandlerInternal, mockEventServiceInternal) + inAppInternal = + DefaultInAppInternal(mockInAppEventHandlerInternal, mockEventServiceInternal) } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/OverlayInAppPresenterTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/OverlayInAppPresenterTest.kt index dbc7ed7b..9801e040 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/OverlayInAppPresenterTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/OverlayInAppPresenterTest.kt @@ -3,9 +3,8 @@ package com.emarsys.mobileengage.iam import android.app.Activity import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment -import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager -import androidx.test.rule.ActivityTestRule +import androidx.test.core.app.ActivityScenario import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.provider.activity.CurrentActivityProvider @@ -13,14 +12,12 @@ import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.mobileengage.iam.dialog.IamDialog import com.emarsys.mobileengage.iam.dialog.IamDialogProvider import com.emarsys.mobileengage.iam.webview.MessageLoadedListener -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.fake.FakeActivity import com.emarsys.testUtil.mockito.anyNotNull import com.emarsys.testUtil.mockito.whenever -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -34,14 +31,6 @@ class OverlayInAppPresenterTest { private var URL = "https://www.emarsys.com" } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Rule - @JvmField - var activityRule = ActivityTestRule(FakeActivity::class.java) - private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder private lateinit var mockIamDialogProvider: IamDialogProvider private lateinit var mockTimestampProvider: TimestampProvider @@ -50,7 +39,7 @@ class OverlayInAppPresenterTest { private lateinit var inAppPresenter: OverlayInAppPresenter - @Before + @BeforeEach fun setUp() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() mockIamDialog = mock() @@ -73,94 +62,111 @@ class OverlayInAppPresenterTest { } @Test - fun testPresent_shouldShowDialog_whenFragmentActivity_isUsed() { - whenever(mockCurrentActivityProvider.get()).thenReturn(activityRule.activity as FragmentActivity) - + fun testPresent_shouldCallCallback_whenDialogIsShown() { + val scenario = ActivityScenario.launch(FakeActivity::class.java) val countDownLatch = CountDownLatch(1) + var callbackCalled = false + Thread { + scenario.onActivity { activity -> + whenever(mockCurrentActivityProvider.get()).thenReturn(activity) + + inAppPresenter.present( + "1", + SID, + URL, + "requestId", + 0L, + "

Hello

" + ) { + callbackCalled = true + countDownLatch.countDown() + } + } - inAppPresenter.present( - "1", - SID, - URL, - "requestId", - 0L, - "

Hello

" - ) { - countDownLatch.countDown() - } - + }.start() countDownLatch.await() - - verify(mockIamDialog).show(any(), any()) + scenario.close() + callbackCalled shouldBe true } @Test fun testPresent_shouldShowDialog_whenAppCompatActivity_isUsed() { - whenever(mockCurrentActivityProvider.get()).thenReturn(activityRule.activity) - + val scenario = ActivityScenario.launch(FakeActivity::class.java) val countDownLatch = CountDownLatch(1) - - inAppPresenter.present( - "1", - SID, - URL, - "requestId", - 0L, - "

Hello

", - MessageLoadedListener { - countDownLatch.countDown() + var callbackCalled = false + Thread { + scenario.onActivity { activity -> + whenever(mockCurrentActivityProvider.get()).thenReturn(activity) + + inAppPresenter.present( + "1", + SID, + URL, + "requestId", + 0L, + "

Hello

" + ) { + callbackCalled = true + countDownLatch.countDown() + } } - ) - + }.start() countDownLatch.await() - + scenario.close() verify(mockIamDialog).show(any(), any()) + callbackCalled shouldBe true } @Test fun testPresent_shouldNotShowDialog_whenActivity_isUsed() { val activity: Activity = mock() - - whenever(mockCurrentActivityProvider.get()).thenReturn(activity) - val countDownLatch = CountDownLatch(1) - - inAppPresenter.present( - "1", - SID, - URL, - "requestId", - 0L, - "

Hello

" - ) { - countDownLatch.countDown() - } - + var callbackCalled = false + Thread { + whenever(mockCurrentActivityProvider.get()).thenReturn(activity) + + inAppPresenter.present( + "1", + SID, + URL, + "requestId", + 0L, + "

Hello

" + ) { + callbackCalled = true + countDownLatch.countDown() + } + }.start() countDownLatch.await() verify(mockIamDialog, times(0)).show(any(), any()) + callbackCalled shouldBe true + } @Test fun testPresent_shouldNotShowDialog_whenActivity_isNull() { - whenever(mockCurrentActivityProvider.get()).thenReturn(null) - val countDownLatch = CountDownLatch(1) - - inAppPresenter.present( - "1", - SID, - URL, - "requestId", - 0L, - "

Hello

" - ) { - countDownLatch.countDown() - } - + var callbackCalled = false + Thread { + whenever(mockCurrentActivityProvider.get()).thenReturn(null) + + inAppPresenter.present( + "1", + SID, + URL, + "requestId", + 0L, + "

Hello

" + ) { + callbackCalled = true + countDownLatch.countDown() + } + }.start() countDownLatch.await() verify(mockIamDialog, times(0)).show(any(), any()) + callbackCalled shouldBe true } @Test @@ -168,63 +174,84 @@ class OverlayInAppPresenterTest { val activity: AppCompatActivity = mock() val fragmentManager: FragmentManager = mock() val fragment: Fragment = mock() - - whenever(mockIamDialogProvider.provideDialog(anyNotNull(), any(), any(), any())).thenReturn( - mockIamDialog - ) - whenever(mockCurrentActivityProvider.get()).thenReturn(activity) - whenever(activity.supportFragmentManager).thenReturn(fragmentManager) - whenever(fragmentManager.findFragmentByTag("MOBILE_ENGAGE_IAM_DIALOG_TAG")).thenReturn( - fragment - ) - val countDownLatch = CountDownLatch(1) - - inAppPresenter.present( - "1", - SID, - URL, - "requestId", - 0L, - "

Hello

" - ) { - countDownLatch.countDown() - } - + var callbackCalled = false + Thread { + whenever( + mockIamDialogProvider.provideDialog( + anyNotNull(), + any(), + any(), + any() + ) + ).thenReturn( + mockIamDialog + ) + whenever(mockCurrentActivityProvider.get()).thenReturn(activity) + whenever(activity.supportFragmentManager).thenReturn(fragmentManager) + whenever(fragmentManager.findFragmentByTag("MOBILE_ENGAGE_IAM_DIALOG_TAG")).thenReturn( + fragment + ) + + inAppPresenter.present( + "1", + SID, + URL, + "requestId", + 0L, + "

Hello

" + ) { + callbackCalled = true + countDownLatch.countDown() + } + }.start() countDownLatch.await() verify(mockIamDialog, times(0)).show(any(), any()) + callbackCalled shouldBe true + } @Test fun testPresent_shouldNotShowDialog_whenFragmentManager_isInSavedState() { val activity: AppCompatActivity = mock() val fragmentManager: FragmentManager = mock() - val fragment: Fragment = mock() - - whenever(mockIamDialogProvider.provideDialog(anyNotNull(), any(), any(), any())).thenReturn( - mockIamDialog - ) - whenever(mockCurrentActivityProvider.get()).thenReturn(activity) - whenever(activity.supportFragmentManager).thenReturn(fragmentManager) - whenever(fragmentManager.isStateSaved).thenReturn(true) - whenever(fragmentManager.findFragmentByTag("MOBILE_ENGAGE_IAM_DIALOG_TAG")).thenReturn(null) - val countDownLatch = CountDownLatch(1) - - inAppPresenter.present( - "1", - SID, - URL, - "requestId", - 0L, - "

Hello

" - ) { - countDownLatch.countDown() - } - + var callbackCalled = false + Thread { + whenever( + mockIamDialogProvider.provideDialog( + anyNotNull(), + any(), + any(), + any() + ) + ).thenReturn( + mockIamDialog + ) + whenever(mockCurrentActivityProvider.get()).thenReturn(activity) + whenever(activity.supportFragmentManager).thenReturn(fragmentManager) + whenever(fragmentManager.isStateSaved).thenReturn(true) + whenever(fragmentManager.findFragmentByTag("MOBILE_ENGAGE_IAM_DIALOG_TAG")).thenReturn( + null + ) + + inAppPresenter.present( + "1", + SID, + URL, + "requestId", + 0L, + "

Hello

" + ) { + callbackCalled = true + countDownLatch.countDown() + } + }.start() countDownLatch.await() verify(mockIamDialog, times(0)).show(any(), any()) + callbackCalled shouldBe true + } } \ No newline at end of file diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/PushToInAppActionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/PushToInAppActionTest.kt index 316a4d32..45e0231b 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/PushToInAppActionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/PushToInAppActionTest.kt @@ -1,13 +1,8 @@ package com.emarsys.mobileengage.iam import com.emarsys.core.provider.timestamp.TimestampProvider -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.Mockito.any -import org.mockito.Mockito.mock +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -21,25 +16,24 @@ class PushToInAppActionTest { const val SID = "sid" const val URL = "google.com" const val PRIORITY = 150 - const val TIMESTAMP : Long= 255555 + const val TIMESTAMP: Long = 255555 } - + private lateinit var pushToInAppAction: PushToInAppAction private lateinit var mockOverlayInAppPresenter: OverlayInAppPresenter private lateinit var mockTimestampProvider: TimestampProvider - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setup() { mockOverlayInAppPresenter = mock() mockTimestampProvider = mock() - pushToInAppAction = PushToInAppAction(mockOverlayInAppPresenter, CAMPAIGN_ID, HTML, SID, URL, mockTimestampProvider, - PRIORITY) + pushToInAppAction = PushToInAppAction( + mockOverlayInAppPresenter, CAMPAIGN_ID, HTML, SID, URL, mockTimestampProvider, + PRIORITY + ) } @Test diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/SaveDisplayedIamActionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/SaveDisplayedIamActionTest.kt index 14d48835..689bf205 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/SaveDisplayedIamActionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/SaveDisplayedIamActionTest.kt @@ -7,14 +7,11 @@ import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.mobileengage.iam.dialog.action.SaveDisplayedIamAction import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIam -import com.emarsys.testUtil.TimeoutUtils.timeoutRule import com.emarsys.testUtil.mockito.ThreadSpy import kotlinx.coroutines.runBlocking -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.timeout @@ -35,11 +32,8 @@ class SaveDisplayedIamActionTest { private lateinit var handler: ConcurrentHandlerHolder private lateinit var timestampProvider: TimestampProvider - @Rule - @JvmField - var timeout: TestRule = timeoutRule - @Before + @BeforeEach fun init() { runBlocking { threadSpy = ThreadSpy() @@ -55,7 +49,7 @@ class SaveDisplayedIamActionTest { } } - @After + @AfterEach fun tearDown() { handler.coreLooper.quit() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogProviderTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogProviderTest.kt index 393a5459..97b5ecb4 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogProviderTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogProviderTest.kt @@ -1,33 +1,39 @@ package com.emarsys.mobileengage.iam.dialog -import androidx.test.rule.ActivityTestRule +import androidx.test.core.app.ActivityScenario import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.testUtil.fake.FakeActivity -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import java.util.concurrent.CountDownLatch import kotlin.concurrent.thread class IamDialogProviderTest { - @Rule - @JvmField - var activityRule = ActivityTestRule(FakeActivity::class.java, false) - private lateinit var iamDialogProvider: IamDialogProvider + private lateinit var scenario: ActivityScenario - @Before + @BeforeEach fun setUp() { - iamDialogProvider = IamDialogProvider( - ConcurrentHandlerHolderFactory.create(), - mock(), - mock(), - mock(), - mock() - ) + scenario = ActivityScenario.launch(FakeActivity::class.java) + scenario.onActivity { activity -> + iamDialogProvider = IamDialogProvider( + ConcurrentHandlerHolderFactory.create(), + mock(), + mock(), + mock(), + mock() + ) + } + } + + @AfterEach + fun tearDown() { + scenario.close() } @Test @@ -41,6 +47,7 @@ class IamDialogProviderTest { } latch.await() } + @Test fun testProvideDialog_shouldSetCorrectArguments() { val testSid = "test sid" @@ -48,7 +55,8 @@ class IamDialogProviderTest { val testUrl = "test url" val testRequestId = "test request id" - val resultDialog = iamDialogProvider.provideDialog(testCampaignId, testSid, testUrl, testRequestId) + val resultDialog = + iamDialogProvider.provideDialog(testCampaignId, testSid, testUrl, testRequestId) val resultArguments = resultDialog.arguments!! diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogTest.kt index c2bf3904..62a3e296 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogTest.kt @@ -7,7 +7,7 @@ import android.widget.LinearLayout import androidx.fragment.app.testing.FragmentScenario import androidx.fragment.app.testing.launchFragment import androidx.lifecycle.Lifecycle -import androidx.test.rule.ActivityTestRule +import androidx.test.core.app.ActivityScenario import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.provider.activity.CurrentActivityProvider import com.emarsys.core.provider.timestamp.TimestampProvider @@ -29,15 +29,12 @@ import com.emarsys.mobileengage.iam.webview.MessageLoadedListener import com.emarsys.testUtil.ExtensionTestUtils.runOnMain import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.ReflectionTestUtils -import com.emarsys.testUtil.TimeoutUtils.timeoutRule import com.emarsys.testUtil.fake.FakeActivity -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -66,59 +63,59 @@ class IamDialogTest { private lateinit var mockCurrentActivityProvider: CurrentActivityProvider private lateinit var iamDialog: IamDialog + private lateinit var scenario: ActivityScenario - @Rule - @JvmField - var timeout: TestRule = timeoutRule - - @Rule - @JvmField - var activityTestRule = ActivityTestRule(FakeActivity::class.java) - - @Before + @BeforeEach fun setUp() { - mockTimestampProvider = mock() - val mockUuidProvider: UUIDProvider = mock { - on { provideId() } doReturn "uuid" - } + scenario = ActivityScenario.launch(FakeActivity::class.java) + val countDownLatch = CountDownLatch(1) + scenario.onActivity { activity -> + mockTimestampProvider = mock() + val mockUuidProvider: UUIDProvider = mock { + on { provideId() } doReturn "uuid" + } - mockJsBridge = mock() - mockJsBridgeFactory = mock { - on { createJsBridge(any()) } doReturn mockJsBridge - } + mockJsBridge = mock() + mockJsBridgeFactory = mock { + on { createJsBridge(any()) } doReturn mockJsBridge + } - mockJSCommandFactory = mock() - mockJSCommandFactoryProvider = mock { - on { provide() } doReturn mockJSCommandFactory - } + mockJSCommandFactory = mock() + mockJSCommandFactoryProvider = mock { + on { provide() } doReturn mockJSCommandFactory + } - mockConcurrentHandlerHolder = mock() - mockCurrentActivityProvider = mock { - on { get() } doReturn activityTestRule.activity - } + mockConcurrentHandlerHolder = mock() + mockCurrentActivityProvider = mock { + on { get() } doReturn activity + } - val iamWebView = createWebView() - mockWebViewFactory = mock { - on { create(null) } doReturn iamWebView - } + val iamWebView = createWebView() + mockWebViewFactory = mock { + on { create(null) } doReturn iamWebView + } - setupMobileEngageComponent( - FakeMobileEngageDependencyContainer( - timestampProvider = mockTimestampProvider, - uuidProvider = mockUuidProvider, - webViewFactory = mockWebViewFactory, - jsCommandFactoryProvider = mockJSCommandFactoryProvider, - iamJsBridgeFactory = mockJsBridgeFactory, - concurrentHandlerHolder = mockConcurrentHandlerHolder, - currentActivityProvider = mockCurrentActivityProvider + setupMobileEngageComponent( + FakeMobileEngageDependencyContainer( + timestampProvider = mockTimestampProvider, + uuidProvider = mockUuidProvider, + webViewFactory = mockWebViewFactory, + jsCommandFactoryProvider = mockJSCommandFactoryProvider, + iamJsBridgeFactory = mockJsBridgeFactory, + concurrentHandlerHolder = mockConcurrentHandlerHolder, + currentActivityProvider = mockCurrentActivityProvider + ) ) - ) - iamDialog = IamDialog(mockTimestampProvider, mockWebViewFactory) + iamDialog = IamDialog(mockTimestampProvider, mockWebViewFactory) + countDownLatch.countDown() + } + countDownLatch.await() } - @After + @AfterEach fun tearDown() { tearDownMobileEngageComponent() + scenario.close() } @Test diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamActionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamActionTest.kt index 5ad66b83..9e333558 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamActionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamActionTest.kt @@ -1,115 +1,76 @@ -package com.emarsys.mobileengage.iam.dialog.action; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.isNull; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import com.emarsys.core.api.result.CompletionListener; -import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory; -import com.emarsys.core.handler.ConcurrentHandlerHolder; -import com.emarsys.mobileengage.iam.InAppInternal; -import com.emarsys.testUtil.TimeoutUtils; -import com.emarsys.testUtil.mockito.ThreadSpy; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; -import org.mockito.Mockito; - -import java.util.HashMap; -import java.util.Map; - -public class SendDisplayedIamActionTest { - - private static final String CAMPAIGN_ID = "123445"; - private static final String SID = "testSid"; - private static final String URL = "https://www.emarsys.com"; - - private SendDisplayedIamAction action; - - private ConcurrentHandlerHolder handler; - private InAppInternal inAppInternal; - - @Rule - public TestRule timeout = TimeoutUtils.getTimeoutRule(); - - @Before - public void init() { - handler = ConcurrentHandlerHolderFactory.INSTANCE.create(); - inAppInternal = mock(InAppInternal.class); - action = new SendDisplayedIamAction(handler, inAppInternal); - } - - @After - public void tearDown() { - handler.getCoreLooper().quit(); +package com.emarsys.mobileengage.iam.dialog.action + +import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory.create +import com.emarsys.core.handler.ConcurrentHandlerHolder +import com.emarsys.mobileengage.iam.InAppInternal +import com.emarsys.testUtil.mockito.ThreadSpy +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.Mockito +import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.isNull +import org.mockito.kotlin.whenever + +class SendDisplayedIamActionTest { + private lateinit var action: SendDisplayedIamAction + private lateinit var handler: ConcurrentHandlerHolder + private lateinit var inAppInternal: InAppInternal + + @BeforeEach + fun init() { + handler = create() + inAppInternal = Mockito.mock(InAppInternal::class.java) + action = SendDisplayedIamAction(handler, inAppInternal) } - @Test(expected = IllegalArgumentException.class) - public void testConstructor_handler_mustNotBeNull() { - new SendDisplayedIamAction( - null, - mock(InAppInternal.class) - ); - } - - @Test(expected = IllegalArgumentException.class) - public void testConstructor_inAppInternal_mustNotBeNull() { - new SendDisplayedIamAction( - mock(ConcurrentHandlerHolder.class), - null - ); - } - - @Test(expected = IllegalArgumentException.class) - public void testExecute_campaignIdMustNotBeNull() { - action.execute(null, SID, URL); + @AfterEach + fun tearDown() { + handler.coreLooper.quit() } @Test - public void testExecute_callsRequestManager_withProperAttributes() { - action.execute(CAMPAIGN_ID, SID, URL); - - String eventName = "inapp:viewed"; - Map attributes = new HashMap<>(); - attributes.put("campaignId", CAMPAIGN_ID); - attributes.put("sid", SID); - attributes.put("url", URL); - - verify(inAppInternal, Mockito.timeout(500)).trackInternalCustomEventAsync( - eventName, - attributes, - null); + fun testExecute_callsRequestManager_withProperAttributes() { + action!!.execute(CAMPAIGN_ID, SID, URL) + val eventName = "inapp:viewed" + val attributes: MutableMap = HashMap() + attributes["campaignId"] = CAMPAIGN_ID + attributes["sid"] = SID + attributes["url"] = URL + Mockito.verify(inAppInternal, Mockito.timeout(500)).trackInternalCustomEventAsync( + eventName, + attributes, + null + ) } @Test - public void testExecute_callsRequestManager_withoutSidAndUrl_when_theyAreNull() throws Exception { - action.execute(CAMPAIGN_ID, null, null); - - String eventName = "inapp:viewed"; - Map attributes = new HashMap<>(); - attributes.put("campaignId", CAMPAIGN_ID); - - verify(inAppInternal, Mockito.timeout(500)).trackInternalCustomEventAsync(eventName, attributes, null); + @Throws(Exception::class) + fun testExecute_callsRequestManager_withoutSidAndUrl_when_theyAreNull() { + action.execute(CAMPAIGN_ID, null, null) + val eventName = "inapp:viewed" + val attributes: MutableMap = HashMap() + attributes["campaignId"] = CAMPAIGN_ID + Mockito.verify(inAppInternal, Mockito.timeout(500)) + .trackInternalCustomEventAsync(eventName, attributes, null) } @Test - @SuppressWarnings("unchecked") - public void testExecute_callsRequestManager_onCoreSdkThread() { - ThreadSpy threadSpy = new ThreadSpy(); - doAnswer(threadSpy).when(inAppInternal).trackInternalCustomEventAsync( - any(String.class), - any(Map.class), - (CompletionListener) isNull()); - - action.execute(CAMPAIGN_ID, SID, URL); - - threadSpy.verifyCalledOnCoreSdkThread(); + fun testExecute_callsRequestManager_onCoreSdkThread() { + val threadSpy: ThreadSpy = ThreadSpy() + whenever(inAppInternal.trackInternalCustomEventAsync(any(), any(), isNull())) doAnswer { + threadSpy.call() + null + } + + action.execute(CAMPAIGN_ID, SID, URL) + threadSpy.verifyCalledOnCoreSdkThread() } - + companion object { + private const val CAMPAIGN_ID = "123445" + private const val SID = "testSid" + private const val URL = "https://www.emarsys.com" + } } \ No newline at end of file diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeFactoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeFactoryTest.kt index c53e01cf..e418cc7e 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeFactoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeFactoryTest.kt @@ -1,8 +1,8 @@ package com.emarsys.mobileengage.iam.jsbridge import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory -import io.kotlintest.shouldBe -import org.junit.Test +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock class IamJsBridgeFactoryTest { @@ -14,6 +14,6 @@ class IamJsBridgeFactoryTest { val result = jsBridgeFactory.createJsBridge(jsCommandFactory) - result::class shouldBe IamJsBridge::class + (result is IamJsBridge) shouldBe true } } \ No newline at end of file diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeTest.kt index 91413cea..545d15b7 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeTest.kt @@ -1,21 +1,29 @@ package com.emarsys.mobileengage.iam.jsbridge -import androidx.test.rule.ActivityTestRule +import androidx.test.core.app.ActivityScenario import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.mobileengage.api.event.EventHandler import com.emarsys.mobileengage.iam.model.InAppMetaData import com.emarsys.mobileengage.iam.webview.IamWebView -import com.emarsys.testUtil.TimeoutUtils.timeoutRule import com.emarsys.testUtil.fake.FakeActivity -import io.kotlintest.shouldBe +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe import org.json.JSONObject -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.ArgumentCaptor -import org.mockito.kotlin.* +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.capture +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.isNull +import org.mockito.kotlin.mock +import org.mockito.kotlin.timeout +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.verifyNoMoreInteractions class IamJsBridgeTest { @@ -41,46 +49,46 @@ class IamJsBridgeTest { private lateinit var mockCopyToClipboardListener: JSCommand private lateinit var mockOnMEEventListener: JSCommand private lateinit var captor: ArgumentCaptor + private lateinit var scenario: ActivityScenario - - @Rule - @JvmField - var timeout: TestRule = timeoutRule - - @Rule - @JvmField - var activityRule = ActivityTestRule(FakeActivity::class.java) - - @Before + @BeforeEach fun setUp() { - inAppMetaData = InAppMetaData("campaignId", "sid", "url") - concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() - mockIamWebView = mock() - mockOnCloseListener = mock() - mockOnAppEventListener = mock() - mockOnButtonClickedListener = mock() - mockOnOpenExternalUrlListener = mock() - mockOnMEEventListener = mock() - mockCopyToClipboardListener = mock() - mockJsCommandFactory = mock { - on { create(JSCommandFactory.CommandType.ON_CLOSE) } doReturn (mockOnCloseListener) - on { create(JSCommandFactory.CommandType.ON_ME_EVENT) } doReturn (mockOnMEEventListener) - on { create(JSCommandFactory.CommandType.ON_OPEN_EXTERNAL_URL) } doReturn (mockOnOpenExternalUrlListener) - on { create(JSCommandFactory.CommandType.ON_APP_EVENT) } doReturn (mockOnAppEventListener) - on { - create( - JSCommandFactory.CommandType.ON_BUTTON_CLICKED - ) - } doReturn (mockOnButtonClickedListener) - on {create(JSCommandFactory.CommandType.ON_COPY_TO_CLIPBOARD)} doReturn mockCopyToClipboardListener + scenario = ActivityScenario.launch(FakeActivity::class.java) + scenario.onActivity { activity -> + inAppMetaData = InAppMetaData("campaignId", "sid", "url") + concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() + mockIamWebView = mock() + mockOnCloseListener = mock() + mockOnAppEventListener = mock() + mockOnButtonClickedListener = mock() + mockOnOpenExternalUrlListener = mock() + mockOnMEEventListener = mock() + mockCopyToClipboardListener = mock() + mockJsCommandFactory = mock { + on { create(JSCommandFactory.CommandType.ON_CLOSE) } doReturn (mockOnCloseListener) + on { create(JSCommandFactory.CommandType.ON_ME_EVENT) } doReturn (mockOnMEEventListener) + on { create(JSCommandFactory.CommandType.ON_OPEN_EXTERNAL_URL) } doReturn (mockOnOpenExternalUrlListener) + on { create(JSCommandFactory.CommandType.ON_APP_EVENT) } doReturn (mockOnAppEventListener) + on { + create( + JSCommandFactory.CommandType.ON_BUTTON_CLICKED + ) + } doReturn (mockOnButtonClickedListener) + on { create(JSCommandFactory.CommandType.ON_COPY_TO_CLIPBOARD) } doReturn mockCopyToClipboardListener + } + mockEventHandler = mock() + jsBridge = IamJsBridge( + concurrentHandlerHolder, + mockJsCommandFactory + ) + jsBridge.iamWebView = mockIamWebView + captor = ArgumentCaptor.forClass(JSONObject::class.java) } - mockEventHandler = mock() - jsBridge = IamJsBridge( - concurrentHandlerHolder, - mockJsCommandFactory - ) - jsBridge.iamWebView = mockIamWebView - captor = ArgumentCaptor.forClass(JSONObject::class.java) + } + + @AfterEach + fun tearDown() { + scenario.close() } @Test @@ -333,9 +341,11 @@ class IamJsBridgeTest { captor.value["success"] shouldBe false } - @Test(expected = IllegalArgumentException::class) + @Test fun testSendResult_whenPayloadDoesNotContainId() { - jsBridge.sendResult(JSONObject()) + shouldThrow { + jsBridge.sendResult(JSONObject()) + } } @Test diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryProviderTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryProviderTest.kt index 1cabd134..e77ec59a 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryProviderTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryProviderTest.kt @@ -8,8 +8,8 @@ import com.emarsys.core.provider.activity.CurrentActivityProvider import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.mobileengage.iam.InAppInternal import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked -import io.kotlintest.shouldBe -import org.junit.Test +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock class JSCommandFactoryProviderTest { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryTest.kt index 8572e657..c1e69043 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryTest.kt @@ -2,7 +2,7 @@ package com.emarsys.mobileengage.iam.jsbridge import android.app.Activity import android.content.ClipboardManager -import androidx.test.rule.ActivityTestRule +import androidx.test.core.app.ActivityScenario import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.database.repository.Repository import com.emarsys.core.database.repository.SqlSpecification @@ -14,14 +14,24 @@ import com.emarsys.mobileengage.iam.model.InAppMetaData import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked import com.emarsys.testUtil.fake.FakeActivity import com.emarsys.testUtil.mockito.ThreadSpy -import io.kotlintest.shouldBe -import io.kotlintest.shouldThrow +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking import org.json.JSONObject -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.mockito.kotlin.* +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.eq +import org.mockito.kotlin.isNull +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch class JSCommandFactoryTest { @@ -43,38 +53,47 @@ class JSCommandFactoryTest { private lateinit var mockOnCloseListener: OnCloseListener private lateinit var mockOnAppEventListener: OnAppEventListener private lateinit var mockTimestampProvider: TimestampProvider - private lateinit var mockActivity: Activity + private lateinit var fakeActivity: Activity private lateinit var mockClipboardManager: ClipboardManager + private lateinit var scenario: ActivityScenario - @Rule - @JvmField - var activityRule = ActivityTestRule(FakeActivity::class.java) - - @Before + @BeforeEach fun setUp() { - mockActivity = mock() - mockCurrentActivityProvider = mock { - on { get() } doReturn mockActivity - } - mockClipboardManager = mock() - concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() - mockInAppInternal = mock() - mockButtonClickedRepository = mock() - mockOnCloseListener = mock() - mockOnAppEventListener = mock() - mockTimestampProvider = mock { - on { provideTimestamp() } doReturn TIMESTAMP + scenario = ActivityScenario.launch(FakeActivity::class.java) + val countDownLatch = CountDownLatch(1) + scenario.onActivity { activity -> + fakeActivity = activity + mockCurrentActivityProvider = mock() + whenever(mockCurrentActivityProvider.get()).thenReturn(fakeActivity) + + mockClipboardManager = mock() + concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() + mockInAppInternal = mock() + mockButtonClickedRepository = mock() + mockOnCloseListener = mock() + mockOnAppEventListener = mock() + mockTimestampProvider = mock() + + whenever(mockTimestampProvider.provideTimestamp()).thenReturn(TIMESTAMP) + + jsCommandFactory = JSCommandFactory( + mockCurrentActivityProvider, + concurrentHandlerHolder, + mockInAppInternal, + mockButtonClickedRepository, + mockOnCloseListener, + mockOnAppEventListener, + mockTimestampProvider, + mockClipboardManager + ) + countDownLatch.countDown() } - jsCommandFactory = JSCommandFactory( - mockCurrentActivityProvider, - concurrentHandlerHolder, - mockInAppInternal, - mockButtonClickedRepository, - mockOnCloseListener, - mockOnAppEventListener, - mockTimestampProvider, - mockClipboardManager - ) + countDownLatch.await() + } + + @AfterEach + fun tearDown() { + scenario.close() } @Test @@ -167,14 +186,17 @@ class JSCommandFactoryTest { fun testCreate_OpenExternalUrl_shouldTriggerStartActivityOnMainThread_whenActivityIsNotNullAndActivityCanBeResolved() { val property = TEST_URL val threadSpy = ThreadSpy() - - whenever(mockActivity.startActivity(any())).doAnswer(threadSpy) + val mockActivity: Activity = mock() + whenever(mockCurrentActivityProvider.get()).thenReturn(mockActivity) + whenever(mockActivity.startActivity(any())).doAnswer { + threadSpy.call() + Unit + } jsCommandFactory.create(JSCommandFactory.CommandType.ON_OPEN_EXTERNAL_URL) .invoke(property, JSONObject()) verify(mockCurrentActivityProvider).get() - verify(mockActivity).startActivity(any()) threadSpy.verifyCalledOnMainThread() } @@ -182,6 +204,8 @@ class JSCommandFactoryTest { @Test fun testCreate_OpenExternalUrl_shouldThrowException_whenActivityIsNotNullAndActivityCanNotBeResolved() { val property = TEST_URL + val mockActivity: Activity = mock() + whenever(mockCurrentActivityProvider.get()).thenReturn(mockActivity) whenever(mockActivity.startActivity(any())).thenAnswer { throw Exception() @@ -218,9 +242,10 @@ class JSCommandFactoryTest { concurrentHandlerHolder.coreHandler.post { latch1.await() } val meEventListener = jsCommandFactory.create(JSCommandFactory.CommandType.ON_ME_EVENT) val property = "testProperty" + val payload = mapOf("payloadKey" to "payloadValue") meEventListener.invoke( property, - JSONObject(mapOf("key" to "value", "payload" to mapOf("payloadKey" to "payloadValue"))) + JSONObject(mapOf("key" to "value", "payload" to payload)) ) verifyNoInteractions(mockInAppInternal) @@ -229,9 +254,9 @@ class JSCommandFactoryTest { latch2.await() verify(mockInAppInternal).trackCustomEventAsync( - property, - mapOf("payloadKey" to "payloadValue"), - null + eq(property), + eq(payload), + isNull() ) } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/IamConversionUtilsTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/IamConversionUtilsTest.kt index c93643d2..9d80c62d 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/IamConversionUtilsTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/IamConversionUtilsTest.kt @@ -1,118 +1,95 @@ -package com.emarsys.mobileengage.iam.model; - -import static org.junit.Assert.assertEquals; - -import com.emarsys.core.util.TimestampUtils; -import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked; -import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIam; -import com.emarsys.testUtil.TimeoutUtils; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class IamConversionUtilsTest { - - private ButtonClicked buttonClicked1; - private ButtonClicked buttonClicked2; - private ButtonClicked buttonClicked3; - - private DisplayedIam displayedIam1; - private DisplayedIam displayedIam2; - private DisplayedIam displayedIam3; - - @Rule - public TestRule timeout = TimeoutUtils.getTimeoutRule(); - - @Before - public void init() { - buttonClicked1 = new ButtonClicked("campaign1", "button1", 200); - buttonClicked2 = new ButtonClicked("campaign1", "button2", 400); - buttonClicked3 = new ButtonClicked("campaign2", "button1", 2000); - - displayedIam1 = new DisplayedIam("campaign10", 500); - displayedIam2 = new DisplayedIam("campaign20", 1000); - displayedIam3 = new DisplayedIam("campaign30", 1500); +package com.emarsys.mobileengage.iam.model + +import com.emarsys.core.util.TimestampUtils +import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked +import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIam +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import java.util.Arrays + +class IamConversionUtilsTest { + private var buttonClicked1: ButtonClicked? = null + private var buttonClicked2: ButtonClicked? = null + private var buttonClicked3: ButtonClicked? = null + private var displayedIam1: DisplayedIam? = null + private var displayedIam2: DisplayedIam? = null + private var displayedIam3: DisplayedIam? = null + + @BeforeEach + fun init() { + buttonClicked1 = ButtonClicked("campaign1", "button1", 200) + buttonClicked2 = ButtonClicked("campaign1", "button2", 400) + buttonClicked3 = ButtonClicked("campaign2", "button1", 2000) + displayedIam1 = DisplayedIam("campaign10", 500) + displayedIam2 = DisplayedIam("campaign20", 1000) + displayedIam3 = DisplayedIam("campaign30", 1500) } @Test - public void testConvert_buttonClick() { - Map json = IamConversionUtils.buttonClickToJson(buttonClicked1); - - Map expected = new HashMap<>(); - expected.put("campaignId", buttonClicked1.getCampaignId()); - expected.put("buttonId", buttonClicked1.getButtonId()); - expected.put("timestamp", TimestampUtils.formatTimestampWithUTC(buttonClicked1.getTimestamp())); - - assertEquals(expected, json); + fun testConvert_buttonClick() { + val json = IamConversionUtils.buttonClickToJson(buttonClicked1) + val expected: MutableMap = HashMap() + expected["campaignId"] = buttonClicked1!!.campaignId + expected["buttonId"] = buttonClicked1!!.buttonId + expected["timestamp"] = TimestampUtils.formatTimestampWithUTC(buttonClicked1!!.timestamp) + json shouldBe expected } @Test - public void testConvert_buttonClickList() { - List> result = IamConversionUtils.buttonClicksToArray(Arrays.asList( + fun testConvert_buttonClickList() { + val result = IamConversionUtils.buttonClicksToArray( + Arrays.asList( buttonClicked1, buttonClicked2, buttonClicked3 - )); - - Map click1 = new HashMap<>(); - click1.put("campaignId", buttonClicked1.getCampaignId()); - click1.put("buttonId", buttonClicked1.getButtonId()); - click1.put("timestamp", TimestampUtils.formatTimestampWithUTC(buttonClicked1.getTimestamp())); - - Map click2 = new HashMap<>(); - click2.put("campaignId", buttonClicked2.getCampaignId()); - click2.put("buttonId", buttonClicked2.getButtonId()); - click2.put("timestamp", TimestampUtils.formatTimestampWithUTC(buttonClicked2.getTimestamp())); - - Map click3 = new HashMap<>(); - click3.put("campaignId", buttonClicked3.getCampaignId()); - click3.put("buttonId", buttonClicked3.getButtonId()); - click3.put("timestamp", TimestampUtils.formatTimestampWithUTC(buttonClicked3.getTimestamp())); - - List> expected = Arrays.asList(click1, click2, click3); - assertEquals(expected, result); + ) + ) + val click1: MutableMap = HashMap() + click1["campaignId"] = buttonClicked1!!.campaignId + click1["buttonId"] = buttonClicked1!!.buttonId + click1["timestamp"] = TimestampUtils.formatTimestampWithUTC(buttonClicked1!!.timestamp) + val click2: MutableMap = HashMap() + click2["campaignId"] = buttonClicked2!!.campaignId + click2["buttonId"] = buttonClicked2!!.buttonId + click2["timestamp"] = TimestampUtils.formatTimestampWithUTC(buttonClicked2!!.timestamp) + val click3: MutableMap = HashMap() + click3["campaignId"] = buttonClicked3!!.campaignId + click3["buttonId"] = buttonClicked3!!.buttonId + click3["timestamp"] = TimestampUtils.formatTimestampWithUTC(buttonClicked3!!.timestamp) + val expected = Arrays.asList>(click1, click2, click3) + result shouldBe expected } @Test - public void testConvert_displayedIam() { - Map json = IamConversionUtils.displayedIamToJson(displayedIam1); - - Map expected = new HashMap<>(); - expected.put("campaignId", displayedIam1.getCampaignId()); - expected.put("timestamp", TimestampUtils.formatTimestampWithUTC(displayedIam1.getTimestamp())); - - assertEquals(expected, json); + fun testConvert_displayedIam() { + val json = IamConversionUtils.displayedIamToJson(displayedIam1) + val expected: MutableMap = HashMap() + expected["campaignId"] = displayedIam1!!.campaignId + expected["timestamp"] = TimestampUtils.formatTimestampWithUTC(displayedIam1!!.timestamp) + json shouldBe expected } @Test - public void testConvert_displayedIamList() { - List> result = IamConversionUtils.displayedIamsToArray(Arrays.asList( + fun testConvert_displayedIamList() { + val result = IamConversionUtils.displayedIamsToArray( + Arrays.asList( displayedIam1, displayedIam2, displayedIam3 - )); - - Map iam1 = new HashMap<>(); - iam1.put("campaignId", displayedIam1.getCampaignId()); - iam1.put("timestamp", TimestampUtils.formatTimestampWithUTC(displayedIam1.getTimestamp())); - - Map iam2 = new HashMap<>(); - iam2.put("campaignId", displayedIam2.getCampaignId()); - iam2.put("timestamp", TimestampUtils.formatTimestampWithUTC(displayedIam2.getTimestamp())); - - Map iam3 = new HashMap<>(); - iam3.put("campaignId", displayedIam3.getCampaignId()); - iam3.put("timestamp", TimestampUtils.formatTimestampWithUTC(displayedIam3.getTimestamp())); - - List> expected = Arrays.asList(iam1, iam2, iam3); - - assertEquals(expected, result); + ) + ) + val iam1: MutableMap = HashMap() + iam1["campaignId"] = displayedIam1!!.campaignId + iam1["timestamp"] = TimestampUtils.formatTimestampWithUTC(displayedIam1!!.timestamp) + val iam2: MutableMap = HashMap() + iam2["campaignId"] = displayedIam2!!.campaignId + iam2["timestamp"] = TimestampUtils.formatTimestampWithUTC(displayedIam2!!.timestamp) + val iam3: MutableMap = HashMap() + iam3["campaignId"] = displayedIam3!!.campaignId + iam3["timestamp"] = TimestampUtils.formatTimestampWithUTC(displayedIam3!!.timestamp) + val expected = Arrays.asList>(iam1, iam2, iam3) + + result shouldBe expected } } \ No newline at end of file diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/buttonclicked/ButtonClickedRepositoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/buttonclicked/ButtonClickedRepositoryTest.kt index 5d826372..9c8405c8 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/buttonclicked/ButtonClickedRepositoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/buttonclicked/ButtonClickedRepositoryTest.kt @@ -9,32 +9,20 @@ import com.emarsys.core.database.helper.DbHelper import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.testUtil.DatabaseTestUtils.deleteCoreDatabase import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.Mockito -import java.util.* +import com.emarsys.testUtil.mockito.whenever +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.Mockito.mock +import java.util.Date class ButtonClickedRepositoryTest { - companion object { - init { - Mockito.mock(Cursor::class.java) - } - } - private lateinit var repository: ButtonClickedRepository private lateinit var buttonClicked1: ButtonClicked private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Before - fun init() { + @BeforeEach + fun setUp() { deleteCoreDatabase() val context = getTargetContext() val dbHelper: DbHelper = CoreDbHelper(context, HashMap()) @@ -46,9 +34,15 @@ class ButtonClickedRepositoryTest { @Test fun testContentValuesFromItem() { val expected = ContentValues() - expected.put(DatabaseContract.BUTTON_CLICKED_COLUMN_NAME_CAMPAIGN_ID, buttonClicked1.campaignId) + expected.put( + DatabaseContract.BUTTON_CLICKED_COLUMN_NAME_CAMPAIGN_ID, + buttonClicked1.campaignId + ) expected.put(DatabaseContract.BUTTON_CLICKED_COLUMN_NAME_BUTTON_ID, buttonClicked1.buttonId) - expected.put(DatabaseContract.BUTTON_CLICKED_COLUMN_NAME_TIMESTAMP, buttonClicked1.timestamp) + expected.put( + DatabaseContract.BUTTON_CLICKED_COLUMN_NAME_TIMESTAMP, + buttonClicked1.timestamp + ) val result = repository.contentValuesFromItem(buttonClicked1) result shouldBe expected @@ -56,13 +50,20 @@ class ButtonClickedRepositoryTest { @Test fun testItemFromCursor() { - val cursor = Mockito.mock(Cursor::class.java) - Mockito.`when`(cursor.getColumnIndexOrThrow(DatabaseContract.BUTTON_CLICKED_COLUMN_NAME_CAMPAIGN_ID)).thenReturn(0) - Mockito.`when`(cursor.getString(0)).thenReturn(buttonClicked1.campaignId) - Mockito.`when`(cursor.getColumnIndexOrThrow(DatabaseContract.BUTTON_CLICKED_COLUMN_NAME_BUTTON_ID)).thenReturn(1) - Mockito.`when`(cursor.getString(1)).thenReturn(buttonClicked1.buttonId) - Mockito.`when`(cursor.getColumnIndexOrThrow(DatabaseContract.BUTTON_CLICKED_COLUMN_NAME_TIMESTAMP)).thenReturn(2) - Mockito.`when`(cursor.getLong(2)).thenReturn(buttonClicked1.timestamp) + val cursor: Cursor = mock() + whenever(cursor.getColumnIndexOrThrow(DatabaseContract.BUTTON_CLICKED_COLUMN_NAME_CAMPAIGN_ID)).thenReturn( + 0 + ) + whenever(cursor.getString(0)).thenReturn(buttonClicked1.campaignId) + whenever(cursor.getColumnIndexOrThrow(DatabaseContract.BUTTON_CLICKED_COLUMN_NAME_BUTTON_ID)).thenReturn( + 1 + ) + whenever(cursor.getString(1)).thenReturn(buttonClicked1.buttonId) + whenever(cursor.getColumnIndexOrThrow(DatabaseContract.BUTTON_CLICKED_COLUMN_NAME_TIMESTAMP)).thenReturn( + 2 + ) + whenever(cursor.getLong(2)).thenReturn(buttonClicked1.timestamp) + val result = repository.itemFromCursor(cursor) val expected = buttonClicked1 diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/displayediam/DisplayedIamRepositoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/displayediam/DisplayedIamRepositoryTest.kt index 0a6292a6..f4a21ef7 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/displayediam/DisplayedIamRepositoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/displayediam/DisplayedIamRepositoryTest.kt @@ -10,16 +10,12 @@ import com.emarsys.core.database.helper.DbHelper import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.testUtil.DatabaseTestUtils.deleteCoreDatabase import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext -import com.emarsys.testUtil.TimeoutUtils.timeoutRule -import io.kotlintest.shouldBe -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.whenever -import java.util.* +import java.util.Date class DisplayedIamRepositoryTest { @@ -27,11 +23,8 @@ class DisplayedIamRepositoryTest { private lateinit var displayedIam1: DisplayedIam private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - var timeout: TestRule = timeoutRule - @Before + @BeforeEach fun setUp() { deleteCoreDatabase() val context = getTargetContext() @@ -63,6 +56,6 @@ class DisplayedIamRepositoryTest { whenever(mockCursor.getLong(1)).thenReturn(displayedIam1.timestamp) val result = iamRepository.itemFromCursor(mockCursor) val expected = displayedIam1 - Assert.assertEquals(expected, result) + result shouldBe expected } } \ No newline at end of file diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/requestRepositoryProxy/RequestRepositoryProxyTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/requestRepositoryProxy/RequestRepositoryProxyTest.kt index a8a7fdbf..a4e0d4d6 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/requestRepositoryProxy/RequestRepositoryProxyTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/requestRepositoryProxy/RequestRepositoryProxyTest.kt @@ -29,11 +29,11 @@ import com.emarsys.mobileengage.util.RequestPayloadUtils.createCompositeRequestM import com.emarsys.testUtil.DatabaseTestUtils.deleteCoreDatabase import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.RandomTestUtils.randomString -import com.emarsys.testUtil.TimeoutUtils.timeoutRule -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.* -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.* class RequestRepositoryProxyTest { @@ -52,11 +52,8 @@ class RequestRepositoryProxyTest { private lateinit var mockRequestModelHelper: RequestModelHelper private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - val timeout: TestRule = timeoutRule - @Before + @BeforeEach fun setUp() { deleteCoreDatabase() val context = getTargetContext() @@ -94,7 +91,7 @@ class RequestRepositoryProxyTest { ) } - @After + @AfterEach @Throws(Exception::class) fun tearDown() { FeatureRegistry.disableFeature(InnerFeature.EVENT_SERVICE_V4) @@ -130,14 +127,14 @@ class RequestRepositoryProxyTest { @Test fun testIsEmpty_whenEmpty_shouldDelegate_toRequestModelRepository() { whenever(mockRequestModelRepository.isEmpty()).thenReturn(true) - Assert.assertTrue(compositeRepository.isEmpty()) + compositeRepository.isEmpty() shouldBe true verify(mockRequestModelRepository).isEmpty() } @Test fun testIsEmpty_whenNotEmpty_shouldDelegate_toRequestModelRepository() { whenever(mockRequestModelRepository.isEmpty()).thenReturn(false) - Assert.assertFalse(compositeRepository.isEmpty()) + compositeRepository.isEmpty() shouldBe false verify(mockRequestModelRepository).isEmpty() } @@ -152,7 +149,7 @@ class RequestRepositoryProxyTest { requestModelRepository.add(requestModel()) } val expected = listOf(firstRequestModel) - Assert.assertEquals(expected, compositeRepository.query(QueryLatestRequestModel())) + compositeRepository.query(QueryLatestRequestModel()) shouldBe expected } @Test @@ -160,13 +157,20 @@ class RequestRepositoryProxyTest { val customEvent = customEvent(123, "testEventName") val requestModel = requestModel() - whenever(mockRequestModelRepository.query(any())).doReturnConsecutively(listOf(listOf(customEvent, requestModel), listOf())) + whenever(mockRequestModelRepository.query(any())).doReturnConsecutively( + listOf( + listOf( + customEvent, + requestModel + ), listOf() + ) + ) val expected = listOf(customEvent, requestModel) val result = compositeRepository.query(Everything()) - Assert.assertEquals(expected, result) + result shouldBe expected } @Test @@ -232,7 +236,7 @@ class RequestRepositoryProxyTest { expectedComposite, request3 ) - Assert.assertEquals(expected, compositeRepository.query(Everything())) + compositeRepository.query(Everything()) shouldBe expected } } @@ -288,7 +292,7 @@ class RequestRepositoryProxyTest { TIMESTAMP, Long.MAX_VALUE, arrayOf(customEvent1.id) ) val expected = listOf(expectedComposite) - Assert.assertEquals(expected, compositeRepository.query(Everything())) + compositeRepository.query(Everything()) shouldBe expected } } @@ -377,7 +381,7 @@ class RequestRepositoryProxyTest { expectedComposite, request3 ) - Assert.assertEquals(expected, compositeRepository.query(Everything())) + compositeRepository.query(Everything()) shouldBe expected } } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/specification/FilterByCampaignIdTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/specification/FilterByCampaignIdTest.kt index 1498c79c..9e51bbc1 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/specification/FilterByCampaignIdTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/specification/FilterByCampaignIdTest.kt @@ -10,26 +10,20 @@ import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIam import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIamRepository import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import java.util.* +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test class FilterByCampaignIdTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var displayedIamRepository: DisplayedIamRepository private lateinit var buttonClickedRepository: ButtonClickedRepository private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Before + @BeforeEach fun init() { DatabaseTestUtils.deleteCoreDatabase() concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewClientTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewClientTest.kt index 80b5c644..65621a51 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewClientTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewClientTest.kt @@ -5,23 +5,17 @@ import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.mobileengage.fake.FakeMessageLoadedListener import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext -import com.emarsys.testUtil.TimeoutUtils.timeoutRule -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import java.util.concurrent.CountDownLatch class IamWebViewClientTest { private lateinit var latch: CountDownLatch private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - var timeout: TestRule = timeoutRule - @Before + @BeforeEach fun setUp() { latch = CountDownLatch(1) concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() @@ -39,7 +33,8 @@ class IamWebViewClientTest { ) } latch.await() - Assert.assertEquals(1, listener.invocationCount.toLong()) + + listener.invocationCount.toLong() shouldBe 1 } @Test @@ -52,6 +47,6 @@ class IamWebViewClientTest { Thread { client.onPageFinished(webView, "") }.start() } latch.await() - Assert.assertEquals(1, listener.invocationCount.toLong()) + listener.invocationCount.toLong() shouldBe 1 } } \ No newline at end of file diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewFactoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewFactoryTest.kt index 9faa809f..2bddd5d1 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewFactoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewFactoryTest.kt @@ -1,6 +1,6 @@ package com.emarsys.mobileengage.iam.webview -import androidx.test.rule.ActivityTestRule +import androidx.test.core.app.ActivityScenario import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.provider.activity.CurrentActivityProvider @@ -9,16 +9,17 @@ import com.emarsys.mobileengage.iam.jsbridge.IamJsBridgeFactory import com.emarsys.mobileengage.iam.jsbridge.JSCommandFactory import com.emarsys.mobileengage.iam.jsbridge.JSCommandFactoryProvider import com.emarsys.testUtil.ExtensionTestUtils.runOnMain -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.fake.FakeActivity -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock +import java.util.concurrent.CountDownLatch class IamWebViewFactoryTest { @@ -30,16 +31,9 @@ class IamWebViewFactoryTest { private lateinit var mockCurrentActivityProvider: CurrentActivityProvider private lateinit var webViewFactory: IamWebViewFactory + private lateinit var scenario: ActivityScenario - @Rule - @JvmField - var timeout: TestRule = TimeoutUtils.timeoutRule - - @Rule - @JvmField - var activityTestRule = ActivityTestRule(FakeActivity::class.java) - - @Before + @BeforeEach fun setUp() { mockJsBridge = mock() mockJsBridgeFactory = mock { @@ -52,16 +46,24 @@ class IamWebViewFactoryTest { } concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() - mockCurrentActivityProvider = mock { - on { get() } doReturn activityTestRule.activity + + scenario = ActivityScenario.launch(FakeActivity::class.java) + scenario.onActivity { activity -> + mockCurrentActivityProvider = mock { + on { get() } doReturn activity + } + webViewFactory = IamWebViewFactory( + mockJsBridgeFactory, + mockJSCommandFactoryProvider, + concurrentHandlerHolder, + mockCurrentActivityProvider + ) } + } - webViewFactory = IamWebViewFactory( - mockJsBridgeFactory, - mockJSCommandFactoryProvider, - concurrentHandlerHolder, - mockCurrentActivityProvider - ) + @AfterEach + fun tearDown() { + scenario.close() } @Test @@ -74,9 +76,16 @@ class IamWebViewFactoryTest { @Test fun testCreateWithActivity() { - val iamWebView = runOnMain { - webViewFactory.create(activityTestRule.activity) + val scenario = ActivityScenario.launch(FakeActivity::class.java) + val countDownLatch = CountDownLatch(1) + scenario.onActivity { activity -> + val iamWebView = runOnMain { + webViewFactory.create(activity) + } + iamWebView::class.java shouldBe IamWebView::class.java + countDownLatch.countDown() } - iamWebView::class.java shouldBe IamWebView::class.java + countDownLatch.await() + scenario.close() } } \ No newline at end of file diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewTest.kt index fbc3f021..6510460d 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewTest.kt @@ -1,7 +1,7 @@ package com.emarsys.mobileengage.iam.webview import android.app.Activity -import androidx.test.rule.ActivityTestRule +import androidx.test.core.app.ActivityScenario import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.provider.activity.CurrentActivityProvider @@ -13,12 +13,12 @@ import com.emarsys.mobileengage.iam.jsbridge.OnCloseListener import com.emarsys.mobileengage.iam.model.InAppMetaData import com.emarsys.testUtil.ExtensionTestUtils.runOnMain import com.emarsys.testUtil.fake.FakeActivity -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.mockito.kotlin.doReturn +import com.emarsys.testUtil.mockito.whenever +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -31,36 +31,43 @@ class IamWebViewTest { private lateinit var mockCurrentActivityProvider: CurrentActivityProvider private lateinit var mockJsBridge: IamJsBridge private lateinit var mockActivity: Activity + private lateinit var scenario: ActivityScenario - @Rule - @JvmField - var activityRule = ActivityTestRule(FakeActivity::class.java) - - @Before + @BeforeEach fun setUp() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() mockActivity = mock() mockJsBridge = mock() + val inAppMetaData = InAppMetaData("campaignId", "sid", "url") + mockCommandFactory = mock { - on { inAppMetaData } doReturn mock() + whenever(it.inAppMetaData).thenReturn(inAppMetaData) } mockJSBridgeFactory = mock { - on { createJsBridge(mockCommandFactory) } doReturn mockJsBridge + whenever(it.createJsBridge(mockCommandFactory)).thenReturn(mockJsBridge) } - mockCurrentActivityProvider = mock { - on { get() } doReturn activityRule.activity - } - iamWebView = runOnMain { - IamWebView( - concurrentHandlerHolder, - mockJSBridgeFactory, - mockCommandFactory, - mockCurrentActivityProvider.get() - ) + scenario = ActivityScenario.launch(FakeActivity::class.java) + scenario.onActivity { activity -> + mockCurrentActivityProvider = mock { + whenever(it.get()).thenReturn(activity) + } + iamWebView = runOnMain { + IamWebView( + concurrentHandlerHolder, + mockJSBridgeFactory, + mockCommandFactory, + mockCurrentActivityProvider.get() + ) + } } } + @AfterEach + fun tearDown() { + scenario.close() + } + @Test fun testInit_shouldSetWebView() { iamWebView.webView shouldNotBe null diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/DefaultMessageInboxInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/DefaultMessageInboxInternalTest.kt index d48cddf4..96cca0eb 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/DefaultMessageInboxInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/DefaultMessageInboxInternalTest.kt @@ -18,14 +18,19 @@ import com.emarsys.mobileengage.api.inbox.Message import com.emarsys.mobileengage.fake.FakeRestClient import com.emarsys.mobileengage.fake.FakeResultListener import com.emarsys.mobileengage.request.MobileEngageRequestModelFactory -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import kotlinx.coroutines.CoroutineScope -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.* +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.eq +import org.mockito.kotlin.isNull +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch class DefaultMessageInboxInternalTest { @@ -48,11 +53,8 @@ class DefaultMessageInboxInternalTest { private lateinit var messages: List private lateinit var message: Message - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { message = Message( "testMessageId", diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/MessageInboxResponseMapperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/MessageInboxResponseMapperTest.kt index de9efef1..dc62ba59 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/MessageInboxResponseMapperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/MessageInboxResponseMapperTest.kt @@ -7,9 +7,9 @@ import com.emarsys.mobileengage.api.action.DismissActionModel import com.emarsys.mobileengage.api.action.OpenExternalUrlActionModel import com.emarsys.mobileengage.api.inbox.InboxResult import com.emarsys.mobileengage.api.inbox.Message -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Test +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import java.net.URL @@ -17,7 +17,7 @@ class MessageInboxResponseMapperTest { private lateinit var messageInboxResponseMapper: MessageInboxResponseMapper - @Before + @BeforeEach fun setUp() { messageInboxResponseMapper = MessageInboxResponseMapper() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/ActionCommandFactoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/ActionCommandFactoryTest.kt index e318a192..a62208b2 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/ActionCommandFactoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/ActionCommandFactoryTest.kt @@ -8,22 +8,19 @@ import com.emarsys.mobileengage.notification.command.AppEventCommand import com.emarsys.mobileengage.notification.command.CustomEventCommand import com.emarsys.mobileengage.notification.command.OpenExternalUrlCommand import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe import org.json.JSONArray import org.json.JSONObject -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.mock class ActionCommandFactoryTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var factory: ActionCommandFactory private lateinit var context: Context @@ -31,7 +28,7 @@ class ActionCommandFactoryTest { private lateinit var mockEventServiceInternal: EventServiceInternal private lateinit var mockNotificationCacheableEventHandler: CacheableEventHandler - @Before + @BeforeEach fun setUp() { context = InstrumentationRegistry.getTargetContext().applicationContext diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksFactoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksFactoryTest.kt index 296ec252..fb9a948c 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksFactoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksFactoryTest.kt @@ -1,7 +1,7 @@ package com.emarsys.mobileengage.notification -import io.kotlintest.shouldBe -import org.junit.Test +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.Test import java.util.concurrent.CountDownLatch class LaunchActivityCommandLifecycleCallbacksFactoryTest { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksTest.kt index 77f4d0d9..7b04e9dd 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksTest.kt @@ -5,9 +5,9 @@ import android.content.Intent import android.content.pm.PackageManager import androidx.test.platform.app.InstrumentationRegistry import com.emarsys.testUtil.fake.FakeActivity -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Test +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -19,7 +19,7 @@ class LaunchActivityCommandLifecycleCallbacksTest { private lateinit var launchIntent: Intent private lateinit var mockPackageManager: PackageManager - @Before + @BeforeEach fun setUp() { latch = CountDownLatch(1) launchIntent = Intent(InstrumentationRegistry.getInstrumentation().targetContext, FakeActivity::class.java) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/NotificationCommandFactoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/NotificationCommandFactoryTest.kt index c1b6bcbb..99b00597 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/NotificationCommandFactoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/NotificationCommandFactoryTest.kt @@ -28,19 +28,17 @@ import com.emarsys.mobileengage.service.NotificationData import com.emarsys.mobileengage.service.NotificationMethod import com.emarsys.mobileengage.service.NotificationOperation import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.data.forall -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import io.kotlintest.tables.row +import io.kotest.data.forAll +import io.kotest.data.row +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import kotlinx.coroutines.runBlocking import org.json.JSONArray import org.json.JSONObject -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.Mockito.mock import org.mockito.kotlin.mock @@ -81,9 +79,7 @@ class NotificationCommandFactoryTest { ) } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var factory: NotificationCommandFactory private lateinit var context: Context @@ -96,7 +92,7 @@ class NotificationCommandFactoryTest { private lateinit var mockCurrentActivityProvider: CurrentActivityProvider private lateinit var mockActivity: Activity - @Before + @BeforeEach fun setUp() { context = InstrumentationRegistry.getTargetContext().applicationContext mockConcurrentHandlerHolder = mock() @@ -130,7 +126,7 @@ class NotificationCommandFactoryTest { factory = NotificationCommandFactory(context) } - @After + @AfterEach fun tearDown() { tearDownMobileEngageComponent() } @@ -372,8 +368,8 @@ class NotificationCommandFactoryTest { } @Test - fun testCreateNotificationCommand_trackActionCommand_withSids() { - forall( + fun testCreateNotificationCommand_trackActionCommand_withSids() = runBlocking { + forAll( row( SID, extractCommandFromComposite(createAppEventIntent()).sid diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/AppEventCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/AppEventCommandTest.kt index 7f676bf7..96267f47 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/AppEventCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/AppEventCommandTest.kt @@ -5,28 +5,23 @@ import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.mobileengage.event.CacheableEventHandler import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext -import com.emarsys.testUtil.TimeoutUtils.timeoutRule import com.emarsys.testUtil.mockito.ThreadSpy import org.json.JSONException import org.json.JSONObject -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.fail import org.mockito.kotlin.* import java.util.concurrent.CountDownLatch class AppEventCommandTest { - @Rule - @JvmField - val timeout: TestRule = timeoutRule + private lateinit var applicationContext: Context private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder private lateinit var mockEventHandler: CacheableEventHandler - @Before + @BeforeEach fun setUp() { applicationContext = getTargetContext().applicationContext mockEventHandler = mock() @@ -95,7 +90,7 @@ class AppEventCommandTest { null ).run() } catch (e: Exception) { - Assert.fail(e.message) + fail(e.message) } } } \ No newline at end of file diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CompositeCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CompositeCommandTest.kt index 40629cb5..65719ae9 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CompositeCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CompositeCommandTest.kt @@ -1,18 +1,14 @@ package com.emarsys.mobileengage.notification.command -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.verify class CompositeCommandTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun testRun_shouldInvokeAllCommands() { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CustomEventCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CustomEventCommandTest.kt index 22e19ca6..57880973 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CustomEventCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CustomEventCommandTest.kt @@ -1,59 +1,53 @@ -package com.emarsys.mobileengage.notification.command; +package com.emarsys.mobileengage.notification.command -import com.emarsys.mobileengage.event.EventServiceInternal; -import com.emarsys.testUtil.TimeoutUtils; +import com.emarsys.mobileengage.event.EventServiceInternal +import io.kotest.assertions.throwables.shouldThrow +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.Mockito -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; +class CustomEventCommandTest { + private lateinit var mockEventServiceInternal: EventServiceInternal -import java.util.HashMap; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class CustomEventCommandTest { - - private static final String EVENT_NAME = "eventName"; - - private EventServiceInternal mockEventServiceInternal; - - @Rule - public TestRule timeout = TimeoutUtils.getTimeoutRule(); - - @Before - public void setUp() { - mockEventServiceInternal = mock(EventServiceInternal.class); + @BeforeEach + fun setUp() { + mockEventServiceInternal = Mockito.mock(EventServiceInternal::class.java) } - @Test(expected = IllegalArgumentException.class) - public void testConstructor_mockEventServiceInternal_mustNotBeNull() { - new CustomEventCommand(null, "", new HashMap()); + @Test + fun testConstructor_mockEventServiceInternal_mustNotBeNull() { + shouldThrow { + CustomEventCommand(null, "", HashMap()) + } } - @Test(expected = IllegalArgumentException.class) - public void testConstructor_eventName_mustNotBeNull() { - new CustomEventCommand(mockEventServiceInternal, null, new HashMap()); + @Test + fun testConstructor_eventName_mustNotBeNull() { + shouldThrow { + CustomEventCommand(mockEventServiceInternal, null, HashMap()) + } } @Test - public void testRun_withEventAttributes() { - HashMap eventAttributes = new HashMap<>(); - eventAttributes.put("key", "value"); - - Runnable customEventCommand = new CustomEventCommand(mockEventServiceInternal, EVENT_NAME, eventAttributes); - customEventCommand.run(); - - verify(mockEventServiceInternal).trackCustomEventAsync(EVENT_NAME, eventAttributes, null); + fun testRun_withEventAttributes() { + val eventAttributes = HashMap() + eventAttributes["key"] = "value" + val customEventCommand: Runnable = + CustomEventCommand(mockEventServiceInternal, EVENT_NAME, eventAttributes) + customEventCommand.run() + Mockito.verify(mockEventServiceInternal) + .trackCustomEventAsync(EVENT_NAME, eventAttributes, null) } @Test - public void testRun_withoutEventAttributes() { - Runnable customEventCommand = new CustomEventCommand(mockEventServiceInternal, EVENT_NAME, null); - customEventCommand.run(); - - verify(mockEventServiceInternal).trackCustomEventAsync(EVENT_NAME, null, null); + fun testRun_withoutEventAttributes() { + val customEventCommand: Runnable = + CustomEventCommand(mockEventServiceInternal, EVENT_NAME, null) + customEventCommand.run() + Mockito.verify(mockEventServiceInternal).trackCustomEventAsync(EVENT_NAME, null, null) } + companion object { + private const val EVENT_NAME = "eventName" + } } \ No newline at end of file diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/DismissNotificationCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/DismissNotificationCommandTest.kt index 3723b255..390a815d 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/DismissNotificationCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/DismissNotificationCommandTest.kt @@ -5,10 +5,9 @@ import android.content.Context import android.content.Intent import com.emarsys.mobileengage.service.NotificationData import com.emarsys.mobileengage.service.NotificationOperation -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -43,9 +42,6 @@ class DismissNotificationCommandTest { ) } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun testDismissNotification_callsNotificationManager() { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/LaunchApplicationCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/LaunchApplicationCommandTest.kt index b3dc3ec8..74bad010 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/LaunchApplicationCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/LaunchApplicationCommandTest.kt @@ -6,17 +6,16 @@ import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import androidx.lifecycle.Lifecycle -import androidx.test.rule.ActivityTestRule +import androidx.test.core.app.ActivityScenario import com.emarsys.mobileengage.fake.FakeActivityLifecycleCallbacks import com.emarsys.mobileengage.notification.LaunchActivityCommandLifecycleCallbacksFactory import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext -import com.emarsys.testUtil.TimeoutUtils.timeoutRule import com.emarsys.testUtil.fake.FakeActivity -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.ArgumentCaptor import org.mockito.ArgumentMatchers import org.mockito.Mockito @@ -28,34 +27,47 @@ import java.util.concurrent.CountDownLatch class LaunchApplicationCommandTest { - @Rule - @JvmField - var activityRule = ActivityTestRule(FakeActivity::class.java) - lateinit var mockProviderLaunchActivityCommand: LaunchActivityCommandLifecycleCallbacksFactory + private lateinit var scenario: ActivityScenario + private lateinit var mockProviderLaunchActivityCommand: LaunchActivityCommandLifecycleCallbacksFactory - @Before + @BeforeEach fun setUp() { - mockProviderLaunchActivityCommand = Mockito.mock(LaunchActivityCommandLifecycleCallbacksFactory::class.java) + scenario = ActivityScenario.launch(FakeActivity::class.java) + scenario.onActivity { activity -> + mockProviderLaunchActivityCommand = + Mockito.mock(LaunchActivityCommandLifecycleCallbacksFactory::class.java) + } } - @Rule - @JvmField - var timeout: TestRule = timeoutRule + @AfterEach + fun tearDown() { + scenario.close() + } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_intentMustNotBeNull() { - LaunchApplicationCommand(null, getTargetContext().applicationContext, mockProviderLaunchActivityCommand) + shouldThrow { + LaunchApplicationCommand( + null, + getTargetContext().applicationContext, + mockProviderLaunchActivityCommand + ) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_contextMustNotBeNull() { - LaunchApplicationCommand(Intent(), null, mockProviderLaunchActivityCommand) + shouldThrow { + LaunchApplicationCommand(Intent(), null, mockProviderLaunchActivityCommand) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_providerMustNotBeNull() { - LaunchApplicationCommand(Intent(), getTargetContext().applicationContext, null) + shouldThrow { + LaunchApplicationCommand(Intent(), getTargetContext().applicationContext, null) + } } @Test @@ -63,7 +75,9 @@ class LaunchApplicationCommandTest { val captor = ArgumentCaptor.forClass(Intent::class.java) val launchIntentForPackage = Intent() val pm: PackageManager = mock() - whenever(pm.getLaunchIntentForPackage(ArgumentMatchers.anyString())).thenReturn(launchIntentForPackage) + whenever(pm.getLaunchIntentForPackage(ArgumentMatchers.anyString())).thenReturn( + launchIntentForPackage + ) val mockActivity: Activity = mock() whenever(mockActivity.applicationContext).thenReturn(mock()) whenever(mockActivity.packageManager).thenReturn(pm) @@ -73,7 +87,12 @@ class LaunchApplicationCommandTest { extras.putString("key2", "value") val remoteIntent = Intent() remoteIntent.putExtras(extras) - val command: Runnable = LaunchApplicationCommand(remoteIntent, mockActivity, mockProviderLaunchActivityCommand) + val command: Runnable = + LaunchApplicationCommand( + remoteIntent, + mockActivity, + mockProviderLaunchActivityCommand + ) command.run() verify(mockActivity).startActivity(captor.capture()) val expectedBundle = launchIntentForPackage.extras @@ -98,7 +117,12 @@ class LaunchApplicationCommandTest { extras.putString("key2", "value") val remoteIntent = Intent() remoteIntent.putExtras(extras) - val command: Runnable = LaunchApplicationCommand(remoteIntent, mockActivity, mockProviderLaunchActivityCommand) + val command: Runnable = + LaunchApplicationCommand( + remoteIntent, + mockActivity, + mockProviderLaunchActivityCommand + ) command.run() } @@ -108,11 +132,14 @@ class LaunchApplicationCommandTest { FakeActivityLifecycleCallbacks(onResume = { (invocation.getArgument(0) as CountDownLatch).countDown() }) } - val fakeActivity = activityRule.activity - val command: Runnable = LaunchApplicationCommand(Intent(), fakeActivity, mockProviderLaunchActivityCommand) - - command.run() + scenario.onActivity { activity -> + val command: Runnable = + LaunchApplicationCommand(Intent(), activity, mockProviderLaunchActivityCommand) + command.run() + } - fakeActivity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED) shouldBe true + scenario.onActivity { activity -> + activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED) shouldBe true + } } } \ No newline at end of file diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/NotificationInformationCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/NotificationInformationCommandTest.kt index f22a25ef..e02cca2a 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/NotificationInformationCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/NotificationInformationCommandTest.kt @@ -3,7 +3,7 @@ package com.emarsys.mobileengage.notification.command import com.emarsys.mobileengage.api.push.NotificationInformation import com.emarsys.mobileengage.api.push.NotificationInformationListener import com.emarsys.mobileengage.push.NotificationInformationListenerProvider -import org.junit.Test +import org.junit.jupiter.api.Test import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/OpenExternalUrlCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/OpenExternalUrlCommandTest.kt index 77fd5f25..cd72640b 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/OpenExternalUrlCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/OpenExternalUrlCommandTest.kt @@ -2,10 +2,9 @@ package com.emarsys.mobileengage.notification.command import android.content.Context import android.content.Intent -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule + +import org.junit.jupiter.api.Test + import org.mockito.Mockito import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -17,9 +16,6 @@ class OpenExternalUrlCommandTest { } } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun testRun_startsActivity_withCorrectIntent() { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/PreloadedInappHandlerCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/PreloadedInappHandlerCommandTest.kt index 1d1bdbcb..5a7561d6 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/PreloadedInappHandlerCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/PreloadedInappHandlerCommandTest.kt @@ -12,14 +12,11 @@ import com.emarsys.mobileengage.service.NotificationData import com.emarsys.mobileengage.service.NotificationOperation import com.emarsys.testUtil.FileTestUtils import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import org.json.JSONObject -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -63,11 +60,8 @@ class PreloadedInappHandlerCommandTest { private lateinit var mockLifecycleActionRegistry: ActivityLifecycleActionRegistry private lateinit var fileUrl: String - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { fileUrl = InstrumentationRegistry.getTargetContext().applicationContext.cacheDir.absolutePath + "/test.file" @@ -89,7 +83,7 @@ class PreloadedInappHandlerCommandTest { } - @After + @AfterEach fun tearDown() { concurrentHandlerHolder.coreLooper.quitSafely() tearDownMobileEngageComponent() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/SilentNotificationInformationCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/SilentNotificationInformationCommandTest.kt index e856e859..ddc0c5db 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/SilentNotificationInformationCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/SilentNotificationInformationCommandTest.kt @@ -3,19 +3,15 @@ package com.emarsys.mobileengage.notification.command import com.emarsys.mobileengage.api.push.NotificationInformation import com.emarsys.mobileengage.api.push.NotificationInformationListener import com.emarsys.mobileengage.push.SilentNotificationInformationListenerProvider -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify class SilentNotificationInformationCommandTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun testRun() { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackActionClickCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackActionClickCommandTest.kt index afadb9ab..0ebadec7 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackActionClickCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackActionClickCommandTest.kt @@ -1,51 +1,44 @@ -package com.emarsys.mobileengage.notification.command; +package com.emarsys.mobileengage.notification.command -import com.emarsys.mobileengage.event.EventServiceInternal; -import com.emarsys.testUtil.TimeoutUtils; +import com.emarsys.mobileengage.event.EventServiceInternal +import io.kotest.assertions.throwables.shouldThrow +import org.junit.jupiter.api.Test +import org.mockito.Mockito -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestRule; - -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class TrackActionClickCommandTest { - - @Rule - public TestRule timeout = TimeoutUtils.getTimeoutRule(); - - @Test(expected = IllegalArgumentException.class) - public void testConstructor_eventServiceInternal_mustNotBeNull() { - new TrackActionClickCommand(null, "", ""); +class TrackActionClickCommandTest { + @Test + fun testConstructor_eventServiceInternal_mustNotBeNull() { + shouldThrow { + TrackActionClickCommand(null, "", "") + } } - @Test(expected = IllegalArgumentException.class) - public void testConstructor_buttonId_mustNotBeNull() { - new TrackActionClickCommand(mock(EventServiceInternal.class), null, ""); + @Test + fun testConstructor_buttonId_mustNotBeNull() { + shouldThrow { + TrackActionClickCommand(Mockito.mock(EventServiceInternal::class.java), null, "") + } } - @Test(expected = IllegalArgumentException.class) - public void testConstructor_sid_mustNotBeNull() { - new TrackActionClickCommand(mock(EventServiceInternal.class), "", null); + @Test + fun testConstructor_sid_mustNotBeNull() { + shouldThrow { + TrackActionClickCommand(Mockito.mock(EventServiceInternal::class.java), "", null) + } } @Test - public void testRun_sendsInternalCustomEvent() { - EventServiceInternal internalMock = mock(EventServiceInternal.class); - String buttonId = "buttonId"; - String sid = "sid1234"; - - new TrackActionClickCommand(internalMock, buttonId, sid).run(); - - Map payload = new HashMap<>(); - payload.put("button_id", buttonId); - payload.put("origin", "button"); - payload.put("sid", sid); - verify(internalMock).trackInternalCustomEventAsync("push:click", payload, null); + fun testRun_sendsInternalCustomEvent() { + val internalMock = Mockito.mock( + EventServiceInternal::class.java + ) + val buttonId = "buttonId" + val sid = "sid1234" + TrackActionClickCommand(internalMock, buttonId, sid).run() + val payload: MutableMap = HashMap() + payload["button_id"] = buttonId + payload["origin"] = "button" + payload["sid"] = sid + Mockito.verify(internalMock).trackInternalCustomEventAsync("push:click", payload, null) } - } \ No newline at end of file diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackMessageOpenCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackMessageOpenCommandTest.kt index dcc3b6b7..1af30f9d 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackMessageOpenCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackMessageOpenCommandTest.kt @@ -1,18 +1,14 @@ package com.emarsys.mobileengage.notification.command import com.emarsys.mobileengage.push.PushInternal -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.mock import org.mockito.Mockito.verify class TrackMessageOpenCommandTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun testRun_callsMobileEngageInternal() { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushInternalTest.kt index 5f5298ef..d9b8367f 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushInternalTest.kt @@ -15,16 +15,22 @@ import com.emarsys.mobileengage.event.CacheableEventHandler import com.emarsys.mobileengage.event.EventServiceInternal import com.emarsys.mobileengage.fake.FakeCompletionListener import com.emarsys.mobileengage.request.MobileEngageRequestModelFactory -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.ThreadSpy import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.matchers.types.shouldBeTypeOf -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.* +import io.kotest.matchers.shouldBe +import io.kotest.matchers.types.shouldBeTypeOf +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.verifyNoMoreInteractions import java.util.concurrent.CountDownLatch class DefaultPushInternalTest { @@ -62,11 +68,8 @@ class DefaultPushInternalTest { private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun setUp() { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushTokenProviderTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushTokenProviderTest.kt index 639f16c1..5e54b2dc 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushTokenProviderTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushTokenProviderTest.kt @@ -2,12 +2,11 @@ package com.emarsys.mobileengage.push import com.emarsys.core.storage.Storage import com.emarsys.core.storage.StringStorage -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.mock class DefaultPushTokenProviderTest { @@ -15,9 +14,6 @@ class DefaultPushTokenProviderTest { const val PUSH_TOKEN = "pushToken" } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun testProvidePushToken() { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyProviderTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyProviderTest.kt index 03ab83a4..8d53bf0c 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyProviderTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyProviderTest.kt @@ -9,13 +9,12 @@ import com.emarsys.core.worker.CoreCompletionHandlerMiddleware import com.emarsys.core.worker.Worker import com.emarsys.mobileengage.responsehandler.MobileEngageTokenResponseHandler import com.emarsys.mobileengage.util.RequestModelHelper -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.mock import org.mockito.kotlin.mock @@ -36,11 +35,8 @@ class CoreCompletionHandlerRefreshTokenProxyProviderTest { private lateinit var mockTokenResponseHandler: MobileEngageTokenResponseHandler private lateinit var mockRequestModelFactory: MobileEngageRequestModelFactory - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun setUp() { mockCoreCompletionHandlerMiddlewareProvider = mock() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyTest.kt index 8ecf4187..e9415173 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyTest.kt @@ -8,12 +8,11 @@ import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.Storage import com.emarsys.mobileengage.responsehandler.MobileEngageTokenResponseHandler import com.emarsys.mobileengage.util.RequestModelHelper -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.eq @@ -24,9 +23,7 @@ import java.net.URL class CoreCompletionHandlerRefreshTokenProxyTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + companion object { const val REQUEST_ID = "testRequestId" @@ -44,7 +41,7 @@ class CoreCompletionHandlerRefreshTokenProxyTest { private lateinit var mockRequestModelHelper: RequestModelHelper private lateinit var mockRequestModelFactory: MobileEngageRequestModelFactory - @Before + @BeforeEach fun setUp() { mockRequestModel = mock { on { url } doReturn URL(CLIENT_HOST) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/MobileEngageRequestModelFactoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/MobileEngageRequestModelFactoryTest.kt index 22ec33c4..34013684 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/MobileEngageRequestModelFactoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/MobileEngageRequestModelFactoryTest.kt @@ -14,12 +14,11 @@ import com.emarsys.mobileengage.MobileEngageRequestContext import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClickedRepository import com.emarsys.mobileengage.util.RequestPayloadUtils -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -59,11 +58,8 @@ class MobileEngageRequestModelFactoryTest { lateinit var mockClientServiceProvider: ServiceEndpointProvider lateinit var mockButtonClickedRepository: ButtonClickedRepository - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockEventServiceProvider = mock { on { provideEndpointHost() } doReturn EVENT_HOST diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/ContactTokenHeaderMapperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/ContactTokenHeaderMapperTest.kt index 89b8d28f..b4628f68 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/ContactTokenHeaderMapperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/ContactTokenHeaderMapperTest.kt @@ -10,14 +10,13 @@ import com.emarsys.core.storage.StringStorage import com.emarsys.mobileengage.MobileEngageRequestContext import com.emarsys.mobileengage.util.RequestModelHelper import com.emarsys.mobileengage.util.RequestPayloadUtils -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -42,11 +41,7 @@ class ContactTokenHeaderMapperTest { private lateinit var mockRequestModelHelper: RequestModelHelper - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun setUp() { mockContactTokenStorage = mock { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DefaultRequestHeaderMapperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DefaultRequestHeaderMapperTest.kt index 08efb181..7c7a359b 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DefaultRequestHeaderMapperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DefaultRequestHeaderMapperTest.kt @@ -4,13 +4,12 @@ import com.emarsys.core.device.DeviceInfo import com.emarsys.core.request.model.RequestMethod import com.emarsys.core.request.model.RequestModel import com.emarsys.mobileengage.MobileEngageRequestContext -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.whenever @@ -30,11 +29,7 @@ class DefaultRequestHeaderMapperTest { private lateinit var mockDeviceInfo: DeviceInfo - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun setUp() { mockDeviceInfo = mock { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DeviceEventStateRequestMapperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DeviceEventStateRequestMapperTest.kt index 7606e11a..799470ca 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DeviceEventStateRequestMapperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DeviceEventStateRequestMapperTest.kt @@ -8,10 +8,10 @@ import com.emarsys.core.request.model.RequestModel import com.emarsys.core.storage.Storage import com.emarsys.mobileengage.MobileEngageRequestContext import com.emarsys.mobileengage.util.RequestModelHelper -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import org.json.JSONObject -import org.junit.Before -import org.junit.Test +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -32,7 +32,7 @@ class DeviceEventStateRequestMapperTest { private lateinit var mockDeviceEventStateStorage: Storage private lateinit var mockRequestModelHelper: RequestModelHelper - @Before + @BeforeEach fun setUp() { FeatureRegistry.enableFeature(InnerFeature.EVENT_SERVICE_V4) val mockDeviceInfo: DeviceInfo = mock { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/MobileEngageHeaderMapperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/MobileEngageHeaderMapperTest.kt index c2dbb211..5639db0e 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/MobileEngageHeaderMapperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/MobileEngageHeaderMapperTest.kt @@ -9,14 +9,13 @@ import com.emarsys.core.request.model.RequestModel import com.emarsys.core.storage.StringStorage import com.emarsys.mobileengage.MobileEngageRequestContext import com.emarsys.mobileengage.util.RequestModelHelper -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -40,11 +39,7 @@ MobileEngageHeaderMapperTest { private lateinit var mockRequestModelHelper: RequestModelHelper - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun setUp() { mockClientStateStorage = mock { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/OpenIdTokenRequestMapperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/OpenIdTokenRequestMapperTest.kt index 70a56d01..65b368e6 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/OpenIdTokenRequestMapperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/OpenIdTokenRequestMapperTest.kt @@ -8,13 +8,12 @@ import com.emarsys.core.request.model.RequestMethod import com.emarsys.core.request.model.RequestModel import com.emarsys.mobileengage.MobileEngageRequestContext import com.emarsys.mobileengage.util.RequestModelHelper -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -36,11 +35,7 @@ class OpenIdTokenRequestMapperTest { private lateinit var mockRequestModelHelper: RequestModelHelper - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Before + @BeforeEach fun setUp() { mockDeviceInfo = mock { on { hardwareId } doReturn HARDWARE_ID diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/ClientInfoResponseHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/ClientInfoResponseHandlerTest.kt index 6afa748c..355bb19d 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/ClientInfoResponseHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/ClientInfoResponseHandlerTest.kt @@ -4,13 +4,12 @@ import com.emarsys.core.device.DeviceInfo import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.StringStorage -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.mock import org.mockito.Mockito.verify import java.net.URL @@ -21,9 +20,7 @@ class ClientInfoResponseHandlerTest { val URL: URL = URL("https://me-client.eservice.emarsys.net/v3/apps/12341/client") } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var clientInfoResponseHandler: ClientInfoResponseHandler @@ -32,7 +29,7 @@ class ClientInfoResponseHandlerTest { private lateinit var mockResponseModel: ResponseModel private lateinit var mockRequestModel: RequestModel - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun setUp() { mockDeviceInfo = mock(DeviceInfo::class.java) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/DeviceEventStateResponseHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/DeviceEventStateResponseHandlerTest.kt index e435d7a6..43f9fe87 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/DeviceEventStateResponseHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/DeviceEventStateResponseHandlerTest.kt @@ -6,10 +6,14 @@ import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.StringStorage import com.emarsys.mobileengage.util.RequestModelHelper -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Test -import org.mockito.kotlin.* +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever import java.net.URL class DeviceEventStateResponseHandlerTest { @@ -24,7 +28,7 @@ class DeviceEventStateResponseHandlerTest { private lateinit var handler: DeviceEventStateResponseHandler private lateinit var mockRequestModelHelper: RequestModelHelper - @Before + @BeforeEach fun setup() { mockRequestModel = mock { on { url } doReturn URL(EVENT_BASE) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerTest.kt index 7b66c520..91f72c7a 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerTest.kt @@ -10,14 +10,13 @@ import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIam import com.emarsys.mobileengage.iam.model.specification.FilterByCampaignId import com.emarsys.mobileengage.util.RequestModelHelper -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -36,11 +35,8 @@ class InAppCleanUpResponseHandlerTest { private lateinit var mockRequestModel: RequestModel private lateinit var mockRequestModelHelper: RequestModelHelper - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockRequestModel = mock { on { url } doReturn URL(EVENT_BASE) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerV4Test.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerV4Test.kt index 25471294..d15883bc 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerV4Test.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerV4Test.kt @@ -10,16 +10,18 @@ import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIam import com.emarsys.mobileengage.iam.model.specification.FilterByCampaignId import com.emarsys.mobileengage.util.RequestModelHelper -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.data.forall -import io.kotlintest.shouldBe -import io.kotlintest.tables.row +import io.kotest.data.forAll +import io.kotest.data.row +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.* +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.whenever import java.net.URL class InAppCleanUpResponseHandlerV4Test { @@ -34,11 +36,8 @@ class InAppCleanUpResponseHandlerV4Test { private lateinit var mockRequestModel: RequestModel private lateinit var mockRequestModelHelper: RequestModelHelper - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockRequestModel = mock { on { url } doReturn URL(EVENT_BASE) @@ -94,8 +93,8 @@ class InAppCleanUpResponseHandlerV4Test { } @Test - fun testShouldHandleResponse_whenResponseWasSuccessful() { - forall( + fun testShouldHandleResponse_whenResponseWasSuccessful() = runBlocking { + forAll( row(buildResponseModel(mockRequestModel, statusCode = 200), true), row(buildResponseModel(mockRequestModel, statusCode = 299), true), row(buildResponseModel(mockRequestModel, statusCode = 400), false) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppMessageResponseHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppMessageResponseHandlerTest.kt index b642862b..1b83cf03 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppMessageResponseHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppMessageResponseHandlerTest.kt @@ -1,7 +1,7 @@ package com.emarsys.mobileengage.responsehandler import android.content.ClipboardManager -import androidx.test.rule.ActivityTestRule +import androidx.test.core.app.ActivityScenario import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.provider.activity.CurrentActivityProvider @@ -14,14 +14,17 @@ import com.emarsys.mobileengage.iam.dialog.IamDialog import com.emarsys.mobileengage.iam.dialog.IamDialogProvider import com.emarsys.mobileengage.iam.jsbridge.IamJsBridge import com.emarsys.mobileengage.iam.jsbridge.IamJsBridgeFactory -import com.emarsys.testUtil.TimeoutUtils.timeoutRule import com.emarsys.testUtil.fake.FakeActivity -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.* +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.spy +import org.mockito.kotlin.verify class InAppMessageResponseHandlerTest { @@ -33,71 +36,72 @@ class InAppMessageResponseHandlerTest { private lateinit var mockClipboardManager: ClipboardManager private lateinit var mockJsBridge: IamJsBridge private lateinit var mockCurrentActivityProvider: CurrentActivityProvider + private lateinit var scenario: ActivityScenario - @Rule - @JvmField - var timeout: TestRule = timeoutRule - - @Rule - @JvmField - var activityRule = ActivityTestRule(FakeActivity::class.java) - - @Before + @BeforeEach fun init() { - concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() - mockCurrentActivityProvider = mock { - on { get() } doReturn activityRule.activity - } - mockJsBridge = mock() - mockClipboardManager = mock() - mockJsBridgeFactory = mock { - on { createJsBridge(any()) } doReturn mockJsBridge - } - mockDialog = mock() - val dialogProvider = mock { - on { - provideDialog( - any(), - anyOrNull(), - anyOrNull(), - any() + scenario = ActivityScenario.launch(FakeActivity::class.java) + scenario.onActivity { activity -> + concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() + mockCurrentActivityProvider = mock { + on { get() } doReturn activity + } + mockJsBridge = mock() + mockClipboardManager = mock() + mockJsBridgeFactory = mock { + on { createJsBridge(any()) } doReturn mockJsBridge + } + mockDialog = mock() + val dialogProvider = mock { + on { + provideDialog( + any(), + anyOrNull(), + anyOrNull(), + any() + ) + } doReturn mockDialog + } + + presenter = spy( + OverlayInAppPresenter( + concurrentHandlerHolder, + dialogProvider, + mock(), + mockCurrentActivityProvider, ) - } doReturn mockDialog + ) + handler = InAppMessageResponseHandler(presenter) } + } - presenter = spy( - OverlayInAppPresenter( - concurrentHandlerHolder, - dialogProvider, - mock(), - mockCurrentActivityProvider, - ) - ) - handler = InAppMessageResponseHandler(presenter) + @AfterEach + fun tearDown() { + scenario.close() } @Test fun testShouldHandleResponse_shouldReturnTrueWhenTheResponseHasHtmlAttribute() { val response = buildResponseModel("{'message': {'html':'some html'}}") - Assert.assertTrue(handler.shouldHandleResponse(response)) + handler.shouldHandleResponse(response) shouldBe true } @Test fun testShouldHandleResponse_shouldReturnFalseWhenTheResponseHasANonJsonBody() { val response = buildResponseModel("Created") - Assert.assertFalse(handler.shouldHandleResponse(response)) + handler.shouldHandleResponse(response) shouldBe false } @Test fun testShouldHandleResponse_shouldReturnFalseWhenTheResponseHasNoMessageAttribute() { val response = buildResponseModel("{'not_a_message': {'html':'some html'}}") - Assert.assertFalse(handler.shouldHandleResponse(response)) + handler.shouldHandleResponse(response) shouldBe false } @Test fun testShouldHandleResponse_shouldReturnFalseWhenTheResponseHasNoHtmlAttribute() { val response = buildResponseModel("{'message': {'not_html':'some html'}}") - Assert.assertFalse(handler.shouldHandleResponse(response)) + handler.shouldHandleResponse(response) shouldBe false } @Test @@ -106,7 +110,15 @@ class InAppMessageResponseHandlerTest { val responseBody = String.format("{'message': {'html':'%s', 'campaignId': '123'} }", html) val response = buildResponseModel(responseBody) handler.handleResponse(response) - verify(presenter).present("123", null, null, response.requestModel.id, response.timestamp, html, null) + verify(presenter).present( + "123", + null, + null, + response.requestModel.id, + response.timestamp, + html, + null + ) } private fun buildResponseModel(responseBody: String): ResponseModel { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageClientStateResponseHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageClientStateResponseHandlerTest.kt index eadb5e14..4fffeade 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageClientStateResponseHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageClientStateResponseHandlerTest.kt @@ -5,13 +5,12 @@ import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.StringStorage import com.emarsys.mobileengage.endpoint.Endpoint import com.emarsys.mobileengage.util.RequestModelHelper -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -30,11 +29,8 @@ class MobileEngageClientStateResponseHandlerTest { private lateinit var clientStateResponseHandler: MobileEngageClientStateResponseHandler private lateinit var mockRequestModelHelper: RequestModelHelper - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockStorage = mock() requestModelMock = mock { @@ -44,7 +40,8 @@ class MobileEngageClientStateResponseHandlerTest { on { isMobileEngageRequest(any()) } doReturn true } - clientStateResponseHandler = MobileEngageClientStateResponseHandler(mockStorage, mockRequestModelHelper) + clientStateResponseHandler = + MobileEngageClientStateResponseHandler(mockStorage, mockRequestModelHelper) } @Test diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageTokenResponseHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageTokenResponseHandlerTest.kt index d9c861c7..d994abd3 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageTokenResponseHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageTokenResponseHandlerTest.kt @@ -4,13 +4,12 @@ import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.StringStorage import com.emarsys.mobileengage.util.RequestModelHelper -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -30,13 +29,11 @@ class MobileEngageTokenResponseHandlerTest { private lateinit var requestModelMock: RequestModel private lateinit var mockRequestModelHelper: RequestModelHelper - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { - token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ4IjoieSJ9.bKXKVZCwf8J55WzWagrg2S0o2k_xZQ-HYfHIIj_2Z_U" + token = + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ4IjoieSJ9.bKXKVZCwf8J55WzWagrg2S0o2k_xZQ-HYfHIIj_2Z_U" tokenKey = "refreshToken" mockStorage = mock() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/OnEventActionResponseHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/OnEventActionResponseHandlerTest.kt index 6b29e619..d983f9e0 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/OnEventActionResponseHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/OnEventActionResponseHandlerTest.kt @@ -13,18 +13,21 @@ import com.emarsys.mobileengage.event.EventServiceInternal import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIam import com.emarsys.mobileengage.notification.ActionCommandFactory import com.emarsys.mobileengage.notification.command.AppEventCommand -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.anyNotNull import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking import org.json.JSONObject -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.* +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.timeout +import org.mockito.kotlin.verify class OnEventActionResponseHandlerTest { @@ -36,11 +39,8 @@ class OnEventActionResponseHandlerTest { private lateinit var mockTimestampProvider: TimestampProvider private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockAppEventCommand = mock() mockActionCommandFactory = mock() @@ -59,7 +59,7 @@ class OnEventActionResponseHandlerTest { ) } - @After + @AfterEach fun tearDown() { try { val looper: Looper? = concurrentHandlerHolder.coreLooper diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/IntentUtilsTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/IntentUtilsTest.kt index 273dc8fd..6a277b9c 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/IntentUtilsTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/IntentUtilsTest.kt @@ -10,12 +10,9 @@ import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.service.IntentUtils.createLaunchIntent import com.emarsys.mobileengage.service.IntentUtils.createNotificationHandlerServiceIntent import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext -import com.emarsys.testUtil.TimeoutUtils.timeoutRule -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -47,13 +44,10 @@ class IntentUtilsTest { inapp = null ) } - private lateinit var context: Context - @Rule - @JvmField - val timeout: TestRule = timeoutRule + private lateinit var context: Context - @Before + @BeforeEach fun init() { setupMobileEngageComponent(FakeMobileEngageDependencyContainer()) context = getTargetContext() @@ -99,7 +93,7 @@ class IntentUtilsTest { @Test fun testCreateLaunchIntent_whenIntentIsNull() { - val pm : PackageManager = mock() + val pm: PackageManager = mock() val mockActivity: Activity = mock { on { packageManager } doReturn pm on { packageName } doReturn "packageName" diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/MessagingServiceUtilsTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/MessagingServiceUtilsTest.kt index ef1741da..70d49a49 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/MessagingServiceUtilsTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/MessagingServiceUtilsTest.kt @@ -28,18 +28,16 @@ import com.emarsys.mobileengage.service.MessagingServiceUtils.styleNotification import com.emarsys.mobileengage.service.mapper.RemoteMessageMapperFactory import com.emarsys.mobileengage.service.mapper.RemoteMessageMapperV1 import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext -import com.emarsys.testUtil.RetryUtils.retryRule -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.copyInputStreamToFile -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe import org.json.JSONArray import org.json.JSONObject -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.ArgumentMatchers import org.mockito.kotlin.any import org.mockito.kotlin.doReturn @@ -94,15 +92,8 @@ class MessagingServiceUtilsTest { private lateinit var mockSilentNotificationInformationListenerProvider: SilentNotificationInformationListenerProvider private lateinit var mockRemoteMessageMapperV1: RemoteMessageMapperV1 - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - - @Rule - @JvmField - var retry: TestRule = retryRule - @Before + @BeforeEach fun init() { context = getTargetContext() val mockNotificationSettings: NotificationSettings = mock() @@ -159,7 +150,7 @@ class MessagingServiceUtilsTest { ) } - @After + @AfterEach fun tearDown() { mobileEngage().concurrentHandlerHolder.coreLooper.quitSafely() tearDownMobileEngageComponent() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/NotificationActionUtilsTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/NotificationActionUtilsTest.kt index 102499a9..b25ad141 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/NotificationActionUtilsTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/NotificationActionUtilsTest.kt @@ -9,14 +9,15 @@ import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.notification.NotificationCommandFactory import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.ThreadSpy -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import org.json.JSONArray import org.json.JSONException import org.json.JSONObject -import org.junit.* -import org.junit.rules.TestRule +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + import org.mockito.Mockito import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch @@ -43,17 +44,13 @@ class NotificationActionUtilsTest { private lateinit var context: Context - @Rule - @JvmField - var timeout: TestRule = TimeoutUtils.timeoutRule - - @Before + @BeforeEach fun init() { context = getTargetContext().applicationContext setupMobileEngageComponent(FakeMobileEngageDependencyContainer()) } - @After + @AfterEach fun tearDown() { mobileEngage().concurrentHandlerHolder.coreLooper.quitSafely() tearDownMobileEngageComponent() @@ -90,7 +87,7 @@ class NotificationActionUtilsTest { testActions, testNotificationData ) - Assert.assertTrue(result.isEmpty()) + result.isEmpty() shouldBe true } @Test @@ -106,7 +103,7 @@ class NotificationActionUtilsTest { testActions, testNotificationData ) - Assert.assertTrue(result.isEmpty()) + result.isEmpty() shouldBe true } @Test @@ -122,7 +119,7 @@ class NotificationActionUtilsTest { testActions, testNotificationData ) - Assert.assertTrue(result.isEmpty()) + result.isEmpty() shouldBe true } @Test @@ -139,7 +136,7 @@ class NotificationActionUtilsTest { testActions, testNotificationData ) - Assert.assertTrue(result.isEmpty()) + result.isEmpty() shouldBe true } @Test diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV1Test.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV1Test.kt index 2936c8c2..5e8ab839 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV1Test.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV1Test.kt @@ -10,17 +10,12 @@ import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.service.mapper.RemoteMessageMapperV1 import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.RetryUtils -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe import org.json.JSONObject -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.eq +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.whenever @@ -44,16 +39,9 @@ class RemoteMessageMapperV1Test { private lateinit var mockMetaDataReader: MetaDataReader private lateinit var remoteMessageMapperV1: RemoteMessageMapperV1 - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Rule - @JvmField - var retry: TestRule = RetryUtils.retryRule - - @Before - fun init() { + @BeforeEach + fun setUp() { context = InstrumentationRegistry.getTargetContext() setupMobileEngageComponent(FakeMobileEngageDependencyContainer()) @@ -70,7 +58,7 @@ class RemoteMessageMapperV1Test { ) } - @After + @AfterEach fun tearDown() { mobileEngage().concurrentHandlerHolder.coreLooper.quitSafely() tearDownMobileEngageComponent() @@ -123,7 +111,7 @@ class RemoteMessageMapperV1Test { val notificationData = remoteMessageMapperV1.map(input) - notificationData shouldNotBe eq(null) + notificationData shouldNotBe null } @Test diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV2Test.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV2Test.kt index 66c5e4f1..0aa61d33 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV2Test.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV2Test.kt @@ -10,18 +10,13 @@ import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.service.mapper.RemoteMessageMapperV2 import com.emarsys.testUtil.InstrumentationRegistry -import com.emarsys.testUtil.RetryUtils -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe import org.json.JSONArray import org.json.JSONObject -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.eq +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.whenever @@ -45,15 +40,8 @@ class RemoteMessageMapperV2Test { private lateinit var mockMetaDataReader: MetaDataReader private lateinit var remoteMessageMapperV2: RemoteMessageMapperV2 - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Rule - @JvmField - var retry: TestRule = RetryUtils.retryRule - - @Before + @BeforeEach fun init() { context = InstrumentationRegistry.getTargetContext() @@ -72,7 +60,7 @@ class RemoteMessageMapperV2Test { ) } - @After + @AfterEach fun tearDown() { mobileEngage().concurrentHandlerHolder.coreLooper.quitSafely() tearDownMobileEngageComponent() @@ -128,7 +116,7 @@ class RemoteMessageMapperV2Test { val notificationData = remoteMessageMapperV2.map(input) - notificationData shouldNotBe eq(null) + notificationData shouldNotBe null } @Test diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/session/MobileEngageSessionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/session/MobileEngageSessionTest.kt index 181202bf..90205641 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/session/MobileEngageSessionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/session/MobileEngageSessionTest.kt @@ -5,8 +5,8 @@ import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.storage.Storage import com.emarsys.mobileengage.MobileEngageRequestContext import com.emarsys.mobileengage.event.EventServiceInternal -import org.junit.Before -import org.junit.Test +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doReturn import org.mockito.kotlin.eq @@ -30,7 +30,7 @@ class MobileEngageSessionTest { private lateinit var mockContactTokenStorage: Storage private lateinit var mockMobileEngageRequestContext: MobileEngageRequestContext - @Before + @BeforeEach fun setUp() { mockMobileEngageRequestContext = mock { on { applicationCode } doReturn "testApplicationCode" diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/storage/MobileEngageStorageKeyTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/storage/MobileEngageStorageKeyTest.kt index e0533eb1..0d96fd99 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/storage/MobileEngageStorageKeyTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/storage/MobileEngageStorageKeyTest.kt @@ -1,27 +1,23 @@ package com.emarsys.mobileengage.storage -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.data.forall -import io.kotlintest.shouldBe -import io.kotlintest.tables.row -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.data.forAll +import io.kotest.data.row +import io.kotest.matchers.shouldBe +import kotlinx.coroutines.runBlocking +import org.junit.jupiter.api.Test + class MobileEngageStorageKeyTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test - fun testGetKey() { + fun testGetKey() = runBlocking { MobileEngageStorageKey.values().map { "mobile_engage_${it.name.lowercase()}" }.zip(MobileEngageStorageKey.values()) { stringValue, enum -> row(enum, stringValue) }.let { - forall(*it.toTypedArray()) { input, expected -> + forAll(*it.toTypedArray()) { input, expected -> input.key shouldBe expected } } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestModelHelperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestModelHelperTest.kt index cad208fc..6cf1b32f 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestModelHelperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestModelHelperTest.kt @@ -2,13 +2,12 @@ package com.emarsys.mobileengage.util import com.emarsys.core.endpoint.ServiceEndpointProvider import com.emarsys.core.request.model.RequestModel -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.mock import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -35,7 +34,7 @@ class RequestModelHelperTest { private lateinit var mockRequestModel: RequestModel private lateinit var requestModelHelper: RequestModelHelper - @Before + @BeforeEach fun setUp() { mockRequestModel = mock() @@ -52,9 +51,6 @@ class RequestModelHelperTest { requestModelHelper = RequestModelHelper(mockClientServiceProvider, mockEventServiceProvider, mockMessageInboxServiceProvider) } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test fun testIsMobileEngageRequest_true_whenItIsMobileEngageClient() { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestPayloadUtilsTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestPayloadUtilsTest.kt index 4c061532..20f4dbce 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestPayloadUtilsTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestPayloadUtilsTest.kt @@ -7,6 +7,7 @@ import com.emarsys.core.api.notification.NotificationSettings import com.emarsys.core.device.DeviceInfo import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.storage.StringStorage +import com.emarsys.core.util.AndroidVersionUtils import com.emarsys.core.util.TimestampUtils import com.emarsys.mobileengage.MobileEngageRequestContext import com.emarsys.mobileengage.iam.model.IamConversionUtils @@ -14,12 +15,11 @@ import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked import com.emarsys.mobileengage.session.SessionIdHolder import com.emarsys.mobileengage.testUtil.RandomMETestUtils import com.emarsys.testUtil.RandomTestUtils -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.whenever @@ -40,7 +40,8 @@ class RequestPayloadUtilsTest { const val CONTACT_FIELD_ID = 3 const val EVENT_NAME = "testEventName" const val TIMESTAMP = 123456789L - const val REFRESH_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ4IjoieSJ9.bKXKVZCwf8J55WzWagrg2S0o2k_xZQ-HYfHIIj_2Z_U" + const val REFRESH_TOKEN = + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ4IjoieSJ9.bKXKVZCwf8J55WzWagrg2S0o2k_xZQ-HYfHIIj_2Z_U" const val ARE_NOTIFICATIONS_ENABLED = true const val IMPORTANCE = 0 const val CHANNEL_ID_1 = "channelId1" @@ -56,22 +57,24 @@ class RequestPayloadUtilsTest { private lateinit var mockChannelSettings: List private lateinit var mockSessionIdHolder: SessionIdHolder - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun setUp() { mockChannelSettings = listOf( - ChannelSettings(channelId = CHANNEL_ID_1, - importance = IMPORTANCE, - isCanBypassDnd = true, - isCanShowBadge = true, - isShouldShowLights = true, - isShouldVibrate = true), - ChannelSettings(channelId = CHANNEL_ID_2, - importance = IMPORTANCE)) + ChannelSettings( + channelId = CHANNEL_ID_1, + importance = IMPORTANCE, + isCanBypassDnd = true, + isCanShowBadge = true, + isShouldShowLights = true, + isShouldVibrate = true + ), + ChannelSettings( + channelId = CHANNEL_ID_2, + importance = IMPORTANCE + ) + ) mockNotificationSettings = mock { on { areNotificationsEnabled } doReturn ARE_NOTIFICATIONS_ENABLED on { importance } doReturn IMPORTANCE @@ -117,7 +120,7 @@ class RequestPayloadUtilsTest { fun testCreateSetPushTokenPayload() { val payload = RequestPayloadUtils.createSetPushTokenPayload(PUSH_TOKEN) payload shouldBe mapOf( - "pushToken" to PUSH_TOKEN + "pushToken" to PUSH_TOKEN ) } @@ -126,41 +129,44 @@ class RequestPayloadUtilsTest { fun testCreateTrackDeviceInfoPayload() { val payload = RequestPayloadUtils.createTrackDeviceInfoPayload(mockRequestContext) payload shouldBe mapOf( - "platform" to PLATFORM, - "applicationVersion" to APPLICATION_VERSION, - "deviceModel" to DEVICE_MODEL, - "osVersion" to OS_VERSION, - "sdkVersion" to SDK_VERSION, - "language" to LANGUAGE, - "timezone" to TIMEZONE, - "pushSettings" to mapOf( - "areNotificationsEnabled" to ARE_NOTIFICATIONS_ENABLED, + "platform" to PLATFORM, + "applicationVersion" to APPLICATION_VERSION, + "deviceModel" to DEVICE_MODEL, + "osVersion" to OS_VERSION, + "sdkVersion" to SDK_VERSION, + "language" to LANGUAGE, + "timezone" to TIMEZONE, + "pushSettings" to mapOf( + "areNotificationsEnabled" to ARE_NOTIFICATIONS_ENABLED, + "importance" to IMPORTANCE, + "channelSettings" to listOf( + mapOf( + "channelId" to CHANNEL_ID_1, "importance" to IMPORTANCE, - "channelSettings" to listOf( - mapOf("channelId" to CHANNEL_ID_1, - "importance" to IMPORTANCE, - "canShowBadge" to true, - "canBypassDnd" to true, - "shouldVibrate" to true, - "shouldShowLights" to true - ), - mapOf("channelId" to CHANNEL_ID_2, - "importance" to IMPORTANCE, - "canShowBadge" to false, - "canBypassDnd" to false, - "shouldVibrate" to false, - "shouldShowLights" to false - ) - ) + "canShowBadge" to true, + "canBypassDnd" to true, + "shouldVibrate" to true, + "shouldShowLights" to true + ), + mapOf( + "channelId" to CHANNEL_ID_2, + "importance" to IMPORTANCE, + "canShowBadge" to false, + "canBypassDnd" to false, + "shouldVibrate" to false, + "shouldShowLights" to false + ) ) + ) ) } @Test @SdkSuppress(maxSdkVersion = android.os.Build.VERSION_CODES.N) fun testCreateTrackDeviceInfoPayload_belowOreo() { - val payload = RequestPayloadUtils.createTrackDeviceInfoPayload(mockRequestContext) - payload shouldBe mapOf( + if (AndroidVersionUtils.isBelowOreo) { + val payload = RequestPayloadUtils.createTrackDeviceInfoPayload(mockRequestContext) + payload shouldBe mapOf( "platform" to PLATFORM, "applicationVersion" to APPLICATION_VERSION, "deviceModel" to DEVICE_MODEL, @@ -169,29 +175,30 @@ class RequestPayloadUtilsTest { "language" to LANGUAGE, "timezone" to TIMEZONE, "pushSettings" to mapOf( - "areNotificationsEnabled" to ARE_NOTIFICATIONS_ENABLED, - "importance" to IMPORTANCE + "areNotificationsEnabled" to ARE_NOTIFICATIONS_ENABLED, + "importance" to IMPORTANCE ) - ) - + ) + } } @Test fun testCreateCustomEventPayload_whenEventAttributesIsNull() { val event = mapOf( - "type" to "custom", - "name" to EVENT_NAME, - "timestamp" to TimestampUtils.formatTimestampWithUTC(TIMESTAMP), - "sessionId" to SESSION_ID + "type" to "custom", + "name" to EVENT_NAME, + "timestamp" to TimestampUtils.formatTimestampWithUTC(TIMESTAMP), + "sessionId" to SESSION_ID ) val expectedPayload = mapOf( - "clicks" to emptyList(), - "viewedMessages" to emptyList(), - "events" to listOf(event) + "clicks" to emptyList(), + "viewedMessages" to emptyList(), + "events" to listOf(event) ) - val actualPayload = RequestPayloadUtils.createCustomEventPayload(EVENT_NAME, null, mockRequestContext) + val actualPayload = + RequestPayloadUtils.createCustomEventPayload(EVENT_NAME, null, mockRequestContext) actualPayload shouldBe expectedPayload } @@ -201,20 +208,21 @@ class RequestPayloadUtilsTest { val attribute = mapOf("attributeKey" to "attributeValue") val event = mapOf( - "type" to "custom", - "name" to EVENT_NAME, - "timestamp" to TimestampUtils.formatTimestampWithUTC(TIMESTAMP), - "attributes" to attribute, - "sessionId" to SESSION_ID + "type" to "custom", + "name" to EVENT_NAME, + "timestamp" to TimestampUtils.formatTimestampWithUTC(TIMESTAMP), + "attributes" to attribute, + "sessionId" to SESSION_ID ) val expectedPayload = mapOf( - "clicks" to emptyList(), - "viewedMessages" to emptyList(), - "events" to listOf(event) + "clicks" to emptyList(), + "viewedMessages" to emptyList(), + "events" to listOf(event) ) - val actualPayload = RequestPayloadUtils.createCustomEventPayload(EVENT_NAME, attribute, mockRequestContext) + val actualPayload = + RequestPayloadUtils.createCustomEventPayload(EVENT_NAME, attribute, mockRequestContext) actualPayload shouldBe expectedPayload } @@ -222,19 +230,20 @@ class RequestPayloadUtilsTest { @Test fun testCreateCustomEventPayload_whenEventAttributesIsEmpty() { val event = mapOf( - "type" to "custom", - "name" to EVENT_NAME, - "timestamp" to TimestampUtils.formatTimestampWithUTC(TIMESTAMP), - "sessionId" to SESSION_ID + "type" to "custom", + "name" to EVENT_NAME, + "timestamp" to TimestampUtils.formatTimestampWithUTC(TIMESTAMP), + "sessionId" to SESSION_ID ) val expectedPayload = mapOf( - "clicks" to emptyList(), - "viewedMessages" to emptyList(), - "events" to listOf(event) + "clicks" to emptyList(), + "viewedMessages" to emptyList(), + "events" to listOf(event) ) - val actualPayload = RequestPayloadUtils.createCustomEventPayload(EVENT_NAME, emptyMap(), mockRequestContext) + val actualPayload = + RequestPayloadUtils.createCustomEventPayload(EVENT_NAME, emptyMap(), mockRequestContext) actualPayload shouldBe expectedPayload } @@ -242,19 +251,23 @@ class RequestPayloadUtilsTest { @Test fun testCreateInternalCustomEventPayload_whenEventAttributesIsNull() { val event = mapOf( - "type" to "internal", - "name" to EVENT_NAME, - "timestamp" to TimestampUtils.formatTimestampWithUTC(TIMESTAMP), - "sessionId" to SESSION_ID + "type" to "internal", + "name" to EVENT_NAME, + "timestamp" to TimestampUtils.formatTimestampWithUTC(TIMESTAMP), + "sessionId" to SESSION_ID ) val expectedPayload = mapOf( - "clicks" to emptyList(), - "viewedMessages" to emptyList(), - "events" to listOf(event) + "clicks" to emptyList(), + "viewedMessages" to emptyList(), + "events" to listOf(event) ) - val actualPayload = RequestPayloadUtils.createInternalCustomEventPayload(EVENT_NAME, null, mockRequestContext) + val actualPayload = RequestPayloadUtils.createInternalCustomEventPayload( + EVENT_NAME, + null, + mockRequestContext + ) actualPayload shouldBe expectedPayload } @@ -264,18 +277,22 @@ class RequestPayloadUtilsTest { whenever(mockSessionIdHolder.sessionId).thenReturn(null) val event = mapOf( - "type" to "internal", - "name" to EVENT_NAME, - "timestamp" to TimestampUtils.formatTimestampWithUTC(TIMESTAMP) + "type" to "internal", + "name" to EVENT_NAME, + "timestamp" to TimestampUtils.formatTimestampWithUTC(TIMESTAMP) ) val expectedPayload = mapOf( - "clicks" to emptyList(), - "viewedMessages" to emptyList(), - "events" to listOf(event) + "clicks" to emptyList(), + "viewedMessages" to emptyList(), + "events" to listOf(event) ) - val actualPayload = RequestPayloadUtils.createInternalCustomEventPayload(EVENT_NAME, null, mockRequestContext) + val actualPayload = RequestPayloadUtils.createInternalCustomEventPayload( + EVENT_NAME, + null, + mockRequestContext + ) actualPayload shouldBe expectedPayload } @@ -285,20 +302,24 @@ class RequestPayloadUtilsTest { val attribute = mapOf("attributeKey" to "attributeValue") val event = mapOf( - "type" to "internal", - "name" to EVENT_NAME, - "timestamp" to TimestampUtils.formatTimestampWithUTC(TIMESTAMP), - "attributes" to attribute, - "sessionId" to SESSION_ID + "type" to "internal", + "name" to EVENT_NAME, + "timestamp" to TimestampUtils.formatTimestampWithUTC(TIMESTAMP), + "attributes" to attribute, + "sessionId" to SESSION_ID ) val expectedPayload = mapOf( - "clicks" to emptyList(), - "viewedMessages" to emptyList(), - "events" to listOf(event) + "clicks" to emptyList(), + "viewedMessages" to emptyList(), + "events" to listOf(event) ) - val actualPayload = RequestPayloadUtils.createInternalCustomEventPayload(EVENT_NAME, attribute, mockRequestContext) + val actualPayload = RequestPayloadUtils.createInternalCustomEventPayload( + EVENT_NAME, + attribute, + mockRequestContext + ) actualPayload shouldBe expectedPayload } @@ -306,19 +327,23 @@ class RequestPayloadUtilsTest { @Test fun testCreateInternalCustomEventPayload_whenEventAttributesIsEmpty() { val event = mapOf( - "type" to "internal", - "name" to EVENT_NAME, - "timestamp" to TimestampUtils.formatTimestampWithUTC(TIMESTAMP), - "sessionId" to SESSION_ID + "type" to "internal", + "name" to EVENT_NAME, + "timestamp" to TimestampUtils.formatTimestampWithUTC(TIMESTAMP), + "sessionId" to SESSION_ID ) val expectedPayload = mapOf( - "clicks" to emptyList(), - "viewedMessages" to emptyList(), - "events" to listOf(event) + "clicks" to emptyList(), + "viewedMessages" to emptyList(), + "events" to listOf(event) ) - val actualPayload = RequestPayloadUtils.createInternalCustomEventPayload(EVENT_NAME, emptyMap(), mockRequestContext) + val actualPayload = RequestPayloadUtils.createInternalCustomEventPayload( + EVENT_NAME, + emptyMap(), + mockRequestContext + ) actualPayload shouldBe expectedPayload } @@ -326,10 +351,10 @@ class RequestPayloadUtilsTest { @Test fun testCreateCompositeRequestModelPayload_payloadContainsDoNotDisturb_whenDoNotDisturbIsTrue() { val payload = RequestPayloadUtils.createCompositeRequestModelPayload( - emptyList(), - emptyList(), - emptyList(), - true + emptyList(), + emptyList(), + emptyList(), + true ) (payload["dnd"] as Boolean) shouldBe true @@ -338,30 +363,30 @@ class RequestPayloadUtilsTest { @Test fun testCreateCompositeRequestModelPayload() { val events = listOf( - RandomTestUtils.randomMap(), - RandomTestUtils.randomMap(), - RandomTestUtils.randomMap() + RandomTestUtils.randomMap(), + RandomTestUtils.randomMap(), + RandomTestUtils.randomMap() ) val displayedIams = listOf( - RandomMETestUtils.randomDisplayedIam(), - RandomMETestUtils.randomDisplayedIam() + RandomMETestUtils.randomDisplayedIam(), + RandomMETestUtils.randomDisplayedIam() ) val buttonClicks = listOf( - RandomMETestUtils.randomButtonClick(), - RandomMETestUtils.randomButtonClick(), - RandomMETestUtils.randomButtonClick() + RandomMETestUtils.randomButtonClick(), + RandomMETestUtils.randomButtonClick(), + RandomMETestUtils.randomButtonClick() ) val expectedPayload = mapOf( - "events" to events, - "viewedMessages" to IamConversionUtils.displayedIamsToArray(displayedIams), - "clicks" to IamConversionUtils.buttonClicksToArray(buttonClicks) + "events" to events, + "viewedMessages" to IamConversionUtils.displayedIamsToArray(displayedIams), + "clicks" to IamConversionUtils.buttonClicksToArray(buttonClicks) ) val resultPayload = RequestPayloadUtils.createCompositeRequestModelPayload( - events, - displayedIams, - buttonClicks, - false + events, + displayedIams, + buttonClicks, + false ) resultPayload shouldBe expectedPayload @@ -370,7 +395,7 @@ class RequestPayloadUtilsTest { @Test fun testCreateRefreshContactTokenPayload() { val expectedPayload = mapOf( - "refreshToken" to REFRESH_TOKEN + "refreshToken" to REFRESH_TOKEN ) val resultPayload = RequestPayloadUtils.createRefreshContactTokenPayload(mockRequestContext) @@ -382,9 +407,9 @@ class RequestPayloadUtilsTest { fun testCreateInlineInAppPayload() { val viewId = "testViewId" val clicks = listOf( - ButtonClicked("campaignId1", "buttonId1", 1L), - ButtonClicked("campaignId2", "buttonId2", 2L), - ButtonClicked("campaignId3", "buttonId3", 3L) + ButtonClicked("campaignId1", "buttonId1", 1L), + ButtonClicked("campaignId2", "buttonId2", 2L), + ButtonClicked("campaignId3", "buttonId3", 3L) ) val expectedPayload = mapOf( "viewIds" to listOf(viewId), diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternal.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternal.kt index 73c3b0f9..f1509ce7 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternal.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternal.kt @@ -4,7 +4,6 @@ import android.app.Activity import android.content.Intent import android.os.Build import android.util.Log -import com.emarsys.core.Mockable import com.emarsys.core.api.result.CompletionListener import com.emarsys.core.endpoint.ServiceEndpointProvider import com.emarsys.core.request.RequestManager @@ -12,7 +11,7 @@ import com.emarsys.core.request.model.RequestModel import com.emarsys.mobileengage.MobileEngageRequestContext import com.emarsys.mobileengage.endpoint.Endpoint -@Mockable + class DefaultDeepLinkInternal( private val requestContext: MobileEngageRequestContext, private val deepLinkServiceProvider: ServiceEndpointProvider, diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternal.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternal.kt index c00bfee9..c96b961e 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternal.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternal.kt @@ -8,7 +8,6 @@ import android.content.pm.PackageManager import android.location.Location import androidx.annotation.RequiresPermission import com.emarsys.core.CoreCompletionHandler -import com.emarsys.core.Mockable import com.emarsys.core.api.MissingPermissionException import com.emarsys.core.api.result.CompletionListener import com.emarsys.core.handler.ConcurrentHandlerHolder @@ -34,7 +33,7 @@ import org.json.JSONObject import kotlin.math.abs import com.emarsys.mobileengage.api.geofence.Geofence as MEGeofence -@Mockable + class DefaultGeofenceInternal( private val requestModelFactory: MobileEngageRequestModelFactory, private val requestManager: RequestManager, diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceBroadcastReceiver.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceBroadcastReceiver.kt index 07dfb905..2dcfafaa 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceBroadcastReceiver.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceBroadcastReceiver.kt @@ -3,7 +3,6 @@ package com.emarsys.mobileengage.geofence import android.content.BroadcastReceiver import android.content.Context import android.content.Intent -import com.emarsys.core.Mockable import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.util.SystemUtils import com.emarsys.core.util.log.Logger @@ -13,7 +12,7 @@ import com.emarsys.mobileengage.di.mobileEngage import com.emarsys.mobileengage.geofence.model.TriggeringEmarsysGeofence import com.google.android.gms.location.GeofencingEvent -@Mockable + class GeofenceBroadcastReceiver(val concurrentHandlerHolder: ConcurrentHandlerHolder) : BroadcastReceiver() { diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceFilter.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceFilter.kt index 900d54f1..0b9ed6f8 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceFilter.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceFilter.kt @@ -2,11 +2,10 @@ package com.emarsys.mobileengage.geofence import android.location.Location import android.location.LocationManager -import com.emarsys.core.Mockable import com.emarsys.mobileengage.api.geofence.Geofence import com.emarsys.mobileengage.geofence.model.GeofenceResponse -@Mockable + class GeofenceFilter(private val limit: Int) { fun findNearestGeofences(currentLocation: Location, geofenceResponse: GeofenceResponse): List { val geofences = geofenceResponse.geofenceGroups diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProvider.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProvider.kt index dc70d19b..47c8cb3c 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProvider.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProvider.kt @@ -3,10 +3,9 @@ package com.emarsys.mobileengage.geofence import android.app.PendingIntent import android.content.Context import android.content.Intent -import com.emarsys.core.Mockable import com.emarsys.core.util.AndroidVersionUtils -@Mockable + class GeofencePendingIntentProvider(private val context: Context) { fun providePendingIntent(): PendingIntent { val intent = Intent("com.emarsys.sdk.GEOFENCE_ACTION") diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapper.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapper.kt index 45492567..b1dce214 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapper.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapper.kt @@ -1,7 +1,6 @@ package com.emarsys.mobileengage.geofence import com.emarsys.core.Mapper -import com.emarsys.core.Mockable import com.emarsys.core.response.ResponseModel import com.emarsys.core.util.log.Logger import com.emarsys.core.util.log.entry.CrashLog @@ -15,7 +14,7 @@ import org.json.JSONException import org.json.JSONObject @Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") -@Mockable + class GeofenceResponseMapper : Mapper { override fun map(responseModel: ResponseModel): GeofenceResponse { diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamAction.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamAction.kt index e6e53e87..d57d8479 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamAction.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamAction.kt @@ -1,44 +1,27 @@ -package com.emarsys.mobileengage.iam.dialog.action; +package com.emarsys.mobileengage.iam.dialog.action -import com.emarsys.core.handler.ConcurrentHandlerHolder; -import com.emarsys.core.util.Assert; -import com.emarsys.mobileengage.event.EventServiceInternal; +import com.emarsys.core.handler.ConcurrentHandlerHolder +import com.emarsys.core.util.Assert +import com.emarsys.mobileengage.event.EventServiceInternal -import java.util.HashMap; -import java.util.Map; +class SendDisplayedIamAction( + private val concurrentHandlerHolder: ConcurrentHandlerHolder, + private val eventServiceInternal: EventServiceInternal +) : OnDialogShownAction { -public class SendDisplayedIamAction implements OnDialogShownAction { - - private final ConcurrentHandlerHolder concurrentHandlerHolder; - private final EventServiceInternal eventServiceInternal; - - public SendDisplayedIamAction( - ConcurrentHandlerHolder handler, - EventServiceInternal eventServiceInternal) { - Assert.notNull(handler, "Handler must not be null!"); - Assert.notNull(eventServiceInternal, "EventServiceInternal must not be null!"); - this.concurrentHandlerHolder = handler; - this.eventServiceInternal = eventServiceInternal; - } - - @Override - public void execute(final String campaignId, final String sid, final String url) { - Assert.notNull(campaignId, "CampaignId must not be null!"); - concurrentHandlerHolder.getCoreHandler().post(new Runnable() { - @Override - public void run() { - Map attributes = new HashMap<>(); - attributes.put("campaignId", campaignId); - if (sid != null) { - attributes.put("sid", sid); - } - if (url != null) { - attributes.put("url", url); - } - - String eventName = "inapp:viewed"; - eventServiceInternal.trackInternalCustomEventAsync(eventName, attributes, null); + override fun execute(campaignId: String, sid: String?, url: String?) { + Assert.notNull(campaignId, "CampaignId must not be null!") + concurrentHandlerHolder.coreHandler.post { + val attributes: MutableMap = HashMap() + attributes["campaignId"] = campaignId + if (sid != null) { + attributes["sid"] = sid + } + if (url != null) { + attributes["url"] = url } - }); + val eventName = "inapp:viewed" + eventServiceInternal.trackInternalCustomEventAsync(eventName, attributes, null) + } } } diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryProvider.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryProvider.kt index a13e0529..56cbd32e 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryProvider.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryProvider.kt @@ -20,7 +20,8 @@ class JSCommandFactoryProvider( private val onCloseTriggered: OnCloseListener?, private val onAppEventTriggered: OnAppEventListener?, private val timestampProvider: TimestampProvider, - private val clipboardManager: ClipboardManager): Provider { + private val clipboardManager: ClipboardManager +) : Provider { override fun provide(): JSCommandFactory { return JSCommandFactory( diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/iam/model/InAppMetaData.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/iam/model/InAppMetaData.kt index 866ad621..939a6411 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/iam/model/InAppMetaData.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/iam/model/InAppMetaData.kt @@ -1,6 +1,4 @@ package com.emarsys.mobileengage.iam.model -import com.emarsys.core.Mockable -@Mockable data class InAppMetaData(val campaignId: String, val sid: String?, val url: String?) \ No newline at end of file diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/notification/NotificationCommandFactory.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/notification/NotificationCommandFactory.kt index 80406cb2..e7ef75b8 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/notification/NotificationCommandFactory.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/notification/NotificationCommandFactory.kt @@ -32,7 +32,10 @@ class NotificationCommandFactory(private val context: Context) { fun createNotificationCommand(intent: Intent): Runnable { val actionId = intent.action - val notificationData = if (AndroidVersionUtils.isBelowUpsideDownCake) intent.getParcelableExtra("payload") else extractPayload(intent) + val notificationData = + if (AndroidVersionUtils.isBelowUpsideDownCake) intent.getParcelableExtra("payload") else extractPayload( + intent + ) val action = getAction(notificationData, actionId) val commands = createMandatoryCommands(notificationData) diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/responsehandler/ClientInfoResponseHandler.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/responsehandler/ClientInfoResponseHandler.kt index fdd1955a..55992dc0 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/responsehandler/ClientInfoResponseHandler.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/responsehandler/ClientInfoResponseHandler.kt @@ -1,13 +1,12 @@ package com.emarsys.mobileengage.responsehandler -import com.emarsys.core.Mockable import com.emarsys.core.device.DeviceInfo import com.emarsys.core.response.AbstractResponseHandler import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.Storage import com.emarsys.mobileengage.endpoint.Endpoint -@Mockable + class ClientInfoResponseHandler(private val deviceInfo: DeviceInfo, private val deviceInfoPayloadStorage: Storage) : AbstractResponseHandler() { diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/responsehandler/MobileEngageClientStateResponseHandler.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/responsehandler/MobileEngageClientStateResponseHandler.kt index d83915f2..b79f3117 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/responsehandler/MobileEngageClientStateResponseHandler.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/responsehandler/MobileEngageClientStateResponseHandler.kt @@ -1,13 +1,12 @@ package com.emarsys.mobileengage.responsehandler -import com.emarsys.core.Mockable import com.emarsys.core.response.AbstractResponseHandler import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.Storage import com.emarsys.core.util.getCaseInsensitive import com.emarsys.mobileengage.util.RequestModelHelper -@Mockable + class MobileEngageClientStateResponseHandler(private val clientStateStorage: Storage, private val requestModelHelper: RequestModelHelper) : AbstractResponseHandler() { diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/responsehandler/MobileEngageTokenResponseHandler.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/responsehandler/MobileEngageTokenResponseHandler.kt index 9a11ef0d..8d7c9ade 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/responsehandler/MobileEngageTokenResponseHandler.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/responsehandler/MobileEngageTokenResponseHandler.kt @@ -9,9 +9,11 @@ import org.json.JSONException import org.json.JSONObject @Mockable -class MobileEngageTokenResponseHandler(private val tokenKey: String, - private val tokenStorage: Storage, - private val requestModelHelper: RequestModelHelper) : AbstractResponseHandler() { +class MobileEngageTokenResponseHandler( + private val tokenKey: String, + private val tokenStorage: Storage, + private val requestModelHelper: RequestModelHelper +) : AbstractResponseHandler() { override fun shouldHandleResponse(responseModel: ResponseModel): Boolean { val body = responseModel.parsedBody diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/service/MessagingServiceUtils.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/service/MessagingServiceUtils.kt index 9eec1b6d..ca2a64ad 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/service/MessagingServiceUtils.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/service/MessagingServiceUtils.kt @@ -8,7 +8,6 @@ import android.os.Build import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat -import com.emarsys.core.Mockable import com.emarsys.core.api.notification.NotificationSettings import com.emarsys.core.device.DeviceInfo import com.emarsys.core.util.AndroidVersionUtils @@ -24,7 +23,7 @@ import org.json.JSONArray import org.json.JSONException import org.json.JSONObject -@Mockable + object MessagingServiceUtils { const val MESSAGE_FILTER = "ems_msg" const val V2_MESSAGE_FILTER = "ems.version" diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/service/mapper/RemoteMessageMapperV1.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/service/mapper/RemoteMessageMapperV1.kt index caaa87fb..6888db00 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/service/mapper/RemoteMessageMapperV1.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/service/mapper/RemoteMessageMapperV1.kt @@ -33,7 +33,8 @@ class RemoteMessageMapperV1( val campaignId = ems.optString("multichannelId") val body = messageDataCopy.remove("body") val channelId = messageDataCopy.remove("channel_id") - val sid = messageDataCopy.remove("u")?.let { JSONObject(it).getNullableString("sid") } ?: "Missing sid" + val sid = messageDataCopy.remove("u")?.let { JSONObject(it).getNullableString("sid") } + ?: "Missing sid" val notificationMethod: NotificationMethod = if (ems.has("notificationMethod")) { parseNotificationMethod(ems.optJSONObject("notificationMethod")) } else { diff --git a/predict-api/build.gradle.kts b/predict-api/build.gradle.kts index 33e67fc5..c0c7bc97 100644 --- a/predict-api/build.gradle.kts +++ b/predict-api/build.gradle.kts @@ -9,11 +9,29 @@ dependencies { implementation(project(":core")) api(project(":core-api")) androidTestImplementation(project(":testUtils")) + + coreLibraryDesugaring(libs.android.tools.desugar) } android { namespace = "com.emarsys.predict.api" defaultConfig { compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + + multiDexEnabled = true + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + testInstrumentationRunnerArgument( + "runnerBuilder", + "de.mannodermaus.junit5.AndroidJUnit5Builder" + ) + } + compileOptions { + isCoreLibraryDesugaringEnabled = true + } + packaging { + resources { + excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + } } } diff --git a/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationFilterTest.kt b/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationFilterTest.kt index 2f53155e..a07940bf 100644 --- a/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationFilterTest.kt +++ b/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationFilterTest.kt @@ -1,14 +1,11 @@ package com.emarsys.predict.api.model -import com.emarsys.testUtil.TimeoutUtils.timeoutRule import com.emarsys.predict.api.model.RecommendationFilter.Companion.exclude import com.emarsys.predict.api.model.RecommendationFilter.Companion.include -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import java.util.* +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import java.util.Arrays class RecommendationFilterTest { @@ -23,11 +20,8 @@ class RecommendationFilterTest { lateinit var exclude: RecommendationFilter.Exclude lateinit var include: RecommendationFilter.Include - @Rule - @JvmField - var timeout: TestRule = timeoutRule - @Before + @BeforeEach fun setUp() { exclude = exclude(FIELD) include = include(FIELD) diff --git a/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationLogicTest.kt b/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationLogicTest.kt index 036deacb..455aa816 100644 --- a/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationLogicTest.kt +++ b/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationLogicTest.kt @@ -1,29 +1,18 @@ package com.emarsys.predict.api.model -import com.emarsys.testUtil.TimeoutUtils.timeoutRule - -import com.emarsys.predict.api.model.RecommendationLogic.Companion.search - +import com.emarsys.predict.api.model.RecommendationLogic.Companion.alsoBought import com.emarsys.predict.api.model.RecommendationLogic.Companion.cart -import com.emarsys.predict.api.model.RecommendationLogic.Companion.related import com.emarsys.predict.api.model.RecommendationLogic.Companion.category -import com.emarsys.predict.api.model.RecommendationLogic.Companion.alsoBought -import com.emarsys.predict.api.model.RecommendationLogic.Companion.popular -import com.emarsys.predict.api.model.RecommendationLogic.Companion.personal import com.emarsys.predict.api.model.RecommendationLogic.Companion.home -import io.kotlintest.shouldBe +import com.emarsys.predict.api.model.RecommendationLogic.Companion.personal +import com.emarsys.predict.api.model.RecommendationLogic.Companion.popular +import com.emarsys.predict.api.model.RecommendationLogic.Companion.related +import com.emarsys.predict.api.model.RecommendationLogic.Companion.search +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.Test -import org.junit.Assert -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import java.util.ArrayList -import java.util.HashMap class RecommendationLogicTest { - @Rule - @JvmField - var timeout: TestRule = timeoutRule @Test fun testConstructor_variants_mustBeEmptyList_withoutVariantsParam() { diff --git a/predict/build.gradle.kts b/predict/build.gradle.kts index 331af248..fa3647f9 100644 --- a/predict/build.gradle.kts +++ b/predict/build.gradle.kts @@ -11,12 +11,30 @@ dependencies { implementation(project(":predict-api")) androidTestImplementation(project(":testUtils")) + + coreLibraryDesugaring(libs.android.tools.desugar) } android { namespace = "com.emarsys.predict" defaultConfig { compileSdk = libs.versions.android.compileSdk.get().toInt() + minSdk = libs.versions.android.minSdk.get().toInt() + + multiDexEnabled = true + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + testInstrumentationRunnerArgument( + "runnerBuilder", + "de.mannodermaus.junit5.AndroidJUnit5Builder" + ) + } + compileOptions { + isCoreLibraryDesugaringEnabled = true + } + packaging { + resources { + excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + } } } diff --git a/predict/src/androidTest/java/com/emarsys/predict/DefaultPredictInternalTest.kt b/predict/src/androidTest/java/com/emarsys/predict/DefaultPredictInternalTest.kt index 95c694d6..c274bce2 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/DefaultPredictInternalTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/DefaultPredictInternalTest.kt @@ -19,7 +19,11 @@ import com.emarsys.core.response.ResponseModel import com.emarsys.core.shard.ShardModel import com.emarsys.core.storage.KeyValueStore import com.emarsys.core.worker.DelegatorCompletionHandlerProvider -import com.emarsys.predict.api.model.* +import com.emarsys.predict.api.model.CartItem +import com.emarsys.predict.api.model.Logic +import com.emarsys.predict.api.model.PredictCartItem +import com.emarsys.predict.api.model.Product +import com.emarsys.predict.api.model.RecommendationFilter import com.emarsys.predict.fake.FakeRestClient import com.emarsys.predict.fake.FakeResultListener import com.emarsys.predict.model.LastTrackedItemContainer @@ -27,18 +31,22 @@ import com.emarsys.predict.provider.PredictRequestModelBuilderProvider import com.emarsys.predict.request.PredictRequestContext import com.emarsys.predict.request.PredictRequestModelBuilder import com.emarsys.testUtil.ReflectionTestUtils -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.ThreadSpy import com.emarsys.testUtil.mockito.anyNotNull import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import io.kotlintest.shouldThrow -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.kotlin.* +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.doReturnConsecutively +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify import java.util.concurrent.CountDownLatch class DefaultPredictInternalTest { @@ -56,9 +64,6 @@ class DefaultPredictInternalTest { const val CONTACT_FIELD_ID = 999 } - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule private lateinit var mockKeyValueStore: KeyValueStore private lateinit var predictInternal: PredictInternal @@ -79,7 +84,7 @@ class DefaultPredictInternalTest { private lateinit var mockResultListener: ResultListener>> private lateinit var mockLastTrackedItemContainer: LastTrackedItemContainer - @Before + @BeforeEach @Suppress("UNCHECKED_CAST") fun init() { latch = CountDownLatch(1) @@ -171,7 +176,7 @@ class DefaultPredictInternalTest { @Test fun testTrackCart_returnsShardId() { - Assert.assertEquals(ID1, predictInternal.trackCart(listOf())) + predictInternal.trackCart(listOf()) shouldBe ID1 } @Test @@ -200,7 +205,7 @@ class DefaultPredictInternalTest { @Test fun testTrackPurchase_returnsShardId() { - Assert.assertEquals(ID1, predictInternal.trackPurchase("orderId", listOf(mock()))) + predictInternal.trackPurchase("orderId", listOf(mock())) shouldBe ID1 } @Test @@ -240,7 +245,7 @@ class DefaultPredictInternalTest { @Test fun testTrackItemView_returnsShardId() { - Assert.assertEquals(ID1, predictInternal.trackItemView("itemId")) + predictInternal.trackItemView("itemId") shouldBe ID1 } @Test @@ -262,7 +267,7 @@ class DefaultPredictInternalTest { @Test fun testTrackCategoryView_returnsShardId() { - Assert.assertEquals(ID1, predictInternal.trackCategoryView("categoryPath")) + predictInternal.trackCategoryView("categoryPath") shouldBe ID1 } @Test @@ -284,7 +289,7 @@ class DefaultPredictInternalTest { @Test fun testTrackSearchTerm_returnsShardId() { - Assert.assertEquals(ID1, predictInternal.trackSearchTerm("searchTerm")) + predictInternal.trackSearchTerm("searchTerm") shouldBe ID1 } @Test @@ -615,7 +620,7 @@ class DefaultPredictInternalTest { @Test fun testTrackRecommendationClick_returnsShardId() { - Assert.assertEquals(ID1, predictInternal.trackRecommendationClick(PRODUCT)) + predictInternal.trackRecommendationClick(PRODUCT) shouldBe ID1 } @Test diff --git a/predict/src/androidTest/java/com/emarsys/predict/PredictResponseMapperTest.kt b/predict/src/androidTest/java/com/emarsys/predict/PredictResponseMapperTest.kt index bb1813c3..2e0cec13 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/PredictResponseMapperTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/PredictResponseMapperTest.kt @@ -2,14 +2,13 @@ package com.emarsys.predict import com.emarsys.core.response.ResponseModel import com.emarsys.predict.api.model.Product -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.matchers.collections.shouldContainAll -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.collections.shouldContainAll +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito class PredictResponseMapperTest { @@ -18,11 +17,8 @@ class PredictResponseMapperTest { private lateinit var mockResponseModel: ResponseModel private lateinit var expectedResult: List - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { predictResponseMapper = PredictResponseMapper() mockResponseModel = Mockito.mock(ResponseModel::class.java) diff --git a/predict/src/androidTest/java/com/emarsys/predict/provider/PredictRequestModelBuilderProviderTest.kt b/predict/src/androidTest/java/com/emarsys/predict/provider/PredictRequestModelBuilderProviderTest.kt index 63c51b0d..255a3e99 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/provider/PredictRequestModelBuilderProviderTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/provider/PredictRequestModelBuilderProviderTest.kt @@ -4,14 +4,14 @@ import com.emarsys.core.endpoint.ServiceEndpointProvider import com.emarsys.predict.request.PredictHeaderFactory import com.emarsys.predict.request.PredictRequestContext import com.emarsys.predict.request.PredictRequestModelBuilder -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import io.kotlintest.shouldNotBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.mock class PredictRequestModelBuilderProviderTest { @@ -20,11 +20,8 @@ class PredictRequestModelBuilderProviderTest { private lateinit var mockHeaderFactory: PredictHeaderFactory private lateinit var mockServiceProvider: ServiceEndpointProvider - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockRequestContext = mock(PredictRequestContext::class.java) mockHeaderFactory = mock(PredictHeaderFactory::class.java) @@ -33,26 +30,37 @@ class PredictRequestModelBuilderProviderTest { } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_predictRequestContext_shouldNotBeNull() { - PredictRequestModelBuilderProvider(null, mockHeaderFactory, mockServiceProvider) + shouldThrow { + PredictRequestModelBuilderProvider(null, mockHeaderFactory, mockServiceProvider) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_headerFactory_shouldNotBeNull() { - PredictRequestModelBuilderProvider(mockRequestContext, null, mockServiceProvider) + shouldThrow { + PredictRequestModelBuilderProvider(mockRequestContext, null, mockServiceProvider) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_predictServiceProvider_shouldNotBeNull() { - PredictRequestModelBuilderProvider(mockRequestContext, mockHeaderFactory, null) + shouldThrow { + PredictRequestModelBuilderProvider(mockRequestContext, mockHeaderFactory, null) + } } @Test fun testProvidePredictRequestModelBuilder_shouldProvideNewRequestModelBuilder() { - val expected = PredictRequestModelBuilder(mockRequestContext, mockHeaderFactory, mockServiceProvider) + val expected = + PredictRequestModelBuilder(mockRequestContext, mockHeaderFactory, mockServiceProvider) - val provider = PredictRequestModelBuilderProvider(mockRequestContext, mockHeaderFactory, mockServiceProvider) + val provider = PredictRequestModelBuilderProvider( + mockRequestContext, + mockHeaderFactory, + mockServiceProvider + ) val result = provider.providePredictRequestModelBuilder() @@ -61,7 +69,11 @@ class PredictRequestModelBuilderProviderTest { @Test fun testProvidePredictRequestModelBuilder_shouldProvideDifferentRequestModelBuilder() { - val provider = PredictRequestModelBuilderProvider(mockRequestContext, mockHeaderFactory, mockServiceProvider) + val provider = PredictRequestModelBuilderProvider( + mockRequestContext, + mockHeaderFactory, + mockServiceProvider + ) val result1 = provider.providePredictRequestModelBuilder() val result2 = provider.providePredictRequestModelBuilder() diff --git a/predict/src/androidTest/java/com/emarsys/predict/request/PredictHeaderFactoryTest.kt b/predict/src/androidTest/java/com/emarsys/predict/request/PredictHeaderFactoryTest.kt index 4e941dfd..aeed55e1 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/request/PredictHeaderFactoryTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/request/PredictHeaderFactoryTest.kt @@ -2,13 +2,13 @@ package com.emarsys.predict.request import com.emarsys.core.device.DeviceInfo import com.emarsys.core.storage.KeyValueStore -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito class PredictHeaderFactoryTest { @@ -22,11 +22,8 @@ class PredictHeaderFactoryTest { private lateinit var mockDeviceInfo: DeviceInfo private lateinit var mockKeyValueStore: KeyValueStore - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockKeyValueStore = Mockito.mock(KeyValueStore::class.java) @@ -42,9 +39,11 @@ class PredictHeaderFactoryTest { headerFactory = PredictHeaderFactory(mockRequestContext) } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_requestContext_mustNotBeNull() { - PredictHeaderFactory(null) + shouldThrow { + PredictHeaderFactory(null) + } } @Test @@ -59,8 +58,10 @@ class PredictHeaderFactoryTest { @Test fun testCreateBaseHeader_shouldPutXpInCookiesInHeader_whenXpIsNotNull() { whenever(mockKeyValueStore.getString("xp")).thenReturn("testXpCookie") - val expected = mapOf("User-Agent" to "EmarsysSDK|osversion:$OS_VERSION|platform:$PLATFORM", - "Cookie" to "xp=testXpCookie;") + val expected = mapOf( + "User-Agent" to "EmarsysSDK|osversion:$OS_VERSION|platform:$PLATFORM", + "Cookie" to "xp=testXpCookie;" + ) val result = headerFactory.createBaseHeader() @@ -70,8 +71,10 @@ class PredictHeaderFactoryTest { @Test fun testCreateBaseHeader_shouldPutVisitorIdInCookiesInHeader_whenVisitorIdIsNotNull() { whenever(mockKeyValueStore.getString("predict_visitor_id")).thenReturn("testVisitorId") - val expected = mapOf("User-Agent" to "EmarsysSDK|osversion:$OS_VERSION|platform:$PLATFORM", - "Cookie" to "cdv=testVisitorId") + val expected = mapOf( + "User-Agent" to "EmarsysSDK|osversion:$OS_VERSION|platform:$PLATFORM", + "Cookie" to "cdv=testVisitorId" + ) val result = headerFactory.createBaseHeader() @@ -82,8 +85,10 @@ class PredictHeaderFactoryTest { fun testCreateBaseHeader_shouldPutVisitorIdAndXpInCookiesInHeader_whenBothAvailable() { whenever(mockKeyValueStore.getString("xp")).thenReturn("testXpCookie") whenever(mockKeyValueStore.getString("predict_visitor_id")).thenReturn("testVisitorId") - val expected = mapOf("User-Agent" to "EmarsysSDK|osversion:$OS_VERSION|platform:$PLATFORM", - "Cookie" to "xp=testXpCookie;cdv=testVisitorId") + val expected = mapOf( + "User-Agent" to "EmarsysSDK|osversion:$OS_VERSION|platform:$PLATFORM", + "Cookie" to "xp=testXpCookie;cdv=testVisitorId" + ) val result = headerFactory.createBaseHeader() diff --git a/predict/src/androidTest/java/com/emarsys/predict/request/PredictRequestModelBuilderTest.kt b/predict/src/androidTest/java/com/emarsys/predict/request/PredictRequestModelBuilderTest.kt index 49722474..ee4a6379 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/request/PredictRequestModelBuilderTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/request/PredictRequestModelBuilderTest.kt @@ -14,17 +14,16 @@ import com.emarsys.predict.api.model.PredictCartItem import com.emarsys.predict.api.model.RecommendationFilter import com.emarsys.predict.api.model.RecommendationLogic import com.emarsys.predict.model.LastTrackedItemContainer -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.data.forall -import io.kotlintest.shouldBe -import io.kotlintest.tables.row +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.data.forAll +import io.kotest.data.row +import io.kotest.matchers.shouldBe +import kotlinx.coroutines.runBlocking import org.json.JSONArray import org.json.JSONObject -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test import org.mockito.Mockito.mock class PredictRequestModelBuilderTest { @@ -62,11 +61,8 @@ class PredictRequestModelBuilderTest { private lateinit var lastTrackedItemContainer: LastTrackedItemContainer private lateinit var mockServiceProvider: ServiceEndpointProvider - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun setUp() { mockKeyValueStore = mock(KeyValueStore::class.java).apply { whenever(getString(PREDICT_VISITOR_ID_KEY)).thenReturn("visitorId") @@ -130,14 +126,16 @@ class PredictRequestModelBuilderTest { ) } - @Test(expected = IllegalArgumentException::class) + @Test fun testWithLimit_limit_mustBeGreaterThanZero() { - requestModelBuilder.withLimit(-10) + shouldThrow { + requestModelBuilder.withLimit(-10) + } } @Test - fun testBuild_withLogic_withLogicData() { - forall( + fun testBuild_withLogic_withLogicData() = runBlocking { + forAll( row( RecommendationLogic.search("searchTerm"), createRequestModelWithUrl( mapOf( @@ -311,8 +309,8 @@ class PredictRequestModelBuilderTest { } @Test - fun testBuild_withHomeOrPersonalLogic_withFiltersData() { - forall( + fun testBuild_withHomeOrPersonalLogic_withFiltersData() = runBlocking { + forAll( row(RecommendationLogic.home()), row(RecommendationLogic.personal()), ) { logic -> @@ -369,8 +367,8 @@ class PredictRequestModelBuilderTest { } @Test - fun testBuild_withLogic_withoutLogicData() { - forall( + fun testBuild_withLogic_withoutLogicData() = runBlocking { + forAll( row( RecommendationLogic.search(), createRequestModelWithUrl( mapOf( @@ -447,9 +445,9 @@ class PredictRequestModelBuilderTest { } @Test - fun testBuild_withLogic_withoutLogicData_withNoLastTrackedItems() { + fun testBuild_withLogic_withoutLogicData_withNoLastTrackedItems() = runBlocking { lastTrackedItemContainer = LastTrackedItemContainer() - forall( + forAll( row( RecommendationLogic.search(), createRequestModelWithUrl( mapOf( diff --git a/predict/src/androidTest/java/com/emarsys/predict/response/VisitorIdResponseHandlerTest.kt b/predict/src/androidTest/java/com/emarsys/predict/response/VisitorIdResponseHandlerTest.kt index ad4af6c1..e95c2b7d 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/response/VisitorIdResponseHandlerTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/response/VisitorIdResponseHandlerTest.kt @@ -6,27 +6,26 @@ import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.KeyValueStore -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe + +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.mock import org.mockito.Mockito.verify class VisitorIdResponseHandlerTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule + private lateinit var keyValueStore: KeyValueStore private lateinit var mockServiceEndpointProvider: ServiceEndpointProvider private lateinit var responseHandler: VisitorIdResponseHandler - @Before + @BeforeEach fun init() { keyValueStore = mock(KeyValueStore::class.java) mockServiceEndpointProvider = mock(ServiceEndpointProvider::class.java).apply { @@ -35,14 +34,18 @@ class VisitorIdResponseHandlerTest { responseHandler = VisitorIdResponseHandler(keyValueStore, mockServiceEndpointProvider) } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_keyValueStore_mustNotBeNull() { - VisitorIdResponseHandler(null, mockServiceEndpointProvider) + shouldThrow { + VisitorIdResponseHandler(null, mockServiceEndpointProvider) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_mockServiceEndpointProvider_mustNotBeNull() { - VisitorIdResponseHandler(keyValueStore, null) + shouldThrow { + VisitorIdResponseHandler(keyValueStore, null) + } } @Test @@ -55,20 +58,21 @@ class VisitorIdResponseHandlerTest { .message("OK") .requestModel(requestModel) .build() - Assert.assertFalse(responseHandler.shouldHandleResponse(response)) + responseHandler.shouldHandleResponse(response) shouldBe false } @Test fun testShouldHandleResponse_withPredictResponse_withoutVisitorIdCookie() { val requestModel = RequestModel.Builder(TimestampProvider(), UUIDProvider()) - .url("https://recommender.scarabresearch.com/merchants/2345432") - .build() + .url("https://recommender.scarabresearch.com/merchants/2345432") + .build() val response = ResponseModel.Builder() - .statusCode(200) - .message("OK") - .requestModel(requestModel) - .build() - Assert.assertFalse(responseHandler.shouldHandleResponse(response)) + .statusCode(200) + .message("OK") + .requestModel(requestModel) + .build() + + responseHandler.shouldHandleResponse(response) shouldBe false } @Test @@ -89,7 +93,7 @@ class VisitorIdResponseHandlerTest { .headers(headers) .requestModel(requestModel) .build() - Assert.assertFalse(responseHandler.shouldHandleResponse(response)) + responseHandler.shouldHandleResponse(response) shouldBe false } @Test @@ -110,7 +114,7 @@ class VisitorIdResponseHandlerTest { .headers(headers) .requestModel(requestModel) .build() - Assert.assertTrue(responseHandler.shouldHandleResponse(response)) + responseHandler.shouldHandleResponse(response) shouldBe true } @Test diff --git a/predict/src/androidTest/java/com/emarsys/predict/response/XPResponseHandlerTest.kt b/predict/src/androidTest/java/com/emarsys/predict/response/XPResponseHandlerTest.kt index dce32224..3e596ca5 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/response/XPResponseHandlerTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/response/XPResponseHandlerTest.kt @@ -6,28 +6,24 @@ import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.KeyValueStore -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.matchers.shouldBe + +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito import org.mockito.Mockito.mock class XPResponseHandlerTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule private lateinit var keyValueStore: KeyValueStore private lateinit var responseHandler: XPResponseHandler private lateinit var mockPredictServiceProvider: ServiceEndpointProvider - @Before + @BeforeEach fun init() { mockPredictServiceProvider = mock(ServiceEndpointProvider::class.java).apply { whenever(provideEndpointHost()).thenReturn("https://recommender.scarabresearch.com") @@ -39,78 +35,79 @@ class XPResponseHandlerTest { @Test fun testShouldHandlerResponse_withoutPredictResponse_withoutXPCookie() { val requestModel = RequestModel.Builder(TimestampProvider(), UUIDProvider()) - .url("https://emarsys.com") - .build() + .url("https://emarsys.com") + .build() val response = ResponseModel.Builder() - .statusCode(200) - .message("OK") - .requestModel(requestModel) - .build() - assertFalse(responseHandler.shouldHandleResponse(response)) + .statusCode(200) + .message("OK") + .requestModel(requestModel) + .build() + + responseHandler.shouldHandleResponse(response) shouldBe false } @Test fun testShouldHandleResponse_withPredictResponse_withXPCookie() { val requestModel = RequestModel.Builder(TimestampProvider(), UUIDProvider()) - .url("https://recommender.scarabresearch.com/merchants/2345432") - .build() + .url("https://recommender.scarabresearch.com/merchants/2345432") + .build() val headers = mapOf( - null to listOf("HTTP/1.1 200 OK"), - "Set-Cookie" to listOf( - "xp=AAABBB;Path=/;Expires=Fri, 20-Sep-2019 14:30:24 GMT", - "s=ASDF1234" - ) + null to listOf("HTTP/1.1 200 OK"), + "Set-Cookie" to listOf( + "xp=AAABBB;Path=/;Expires=Fri, 20-Sep-2019 14:30:24 GMT", + "s=ASDF1234" + ) ) val response = ResponseModel.Builder() - .statusCode(200) - .message("OK") - .headers(headers) - .requestModel(requestModel) - .build() - assertTrue(responseHandler.shouldHandleResponse(response)) + .statusCode(200) + .message("OK") + .headers(headers) + .requestModel(requestModel) + .build() + responseHandler.shouldHandleResponse(response) shouldBe true } @Test fun testShouldNotHandleResponse_withoutPredictResponse_withXPCookie() { val requestModel = RequestModel.Builder(TimestampProvider(), UUIDProvider()) - .url("https://www.emarsys.com") - .build() + .url("https://www.emarsys.com") + .build() val headers = mapOf( - null to listOf("HTTP/1.1 200 OK"), - "Set-Cookie" to listOf( - "xp=AAABBB;Path=/;Expires=Fri, 20-Sep-2019 14:30:24 GMT", - "s=ASDF1234" - ) + null to listOf("HTTP/1.1 200 OK"), + "Set-Cookie" to listOf( + "xp=AAABBB;Path=/;Expires=Fri, 20-Sep-2019 14:30:24 GMT", + "s=ASDF1234" + ) ) val response = ResponseModel.Builder() - .statusCode(200) - .message("OK") - .headers(headers) - .requestModel(requestModel) - .build() - assertFalse(responseHandler.shouldHandleResponse(response)) + .statusCode(200) + .message("OK") + .headers(headers) + .requestModel(requestModel) + .build() + responseHandler.shouldHandleResponse(response) shouldBe false } @Test fun testHandleResponse_shouldStoreXP() { val xp = "AAABBB" val requestModel = RequestModel.Builder(TimestampProvider(), UUIDProvider()) - .url("https://recommender.scarabresearch.com/merchants/2345432") - .build() + .url("https://recommender.scarabresearch.com/merchants/2345432") + .build() val headers = mapOf( - null to listOf("HTTP/1.1 200 OK"), - "Set-Cookie" to listOf( - "xp=$xp;Path=/;Expires=Fri, 20-Sep-2019 14:30:24 GMT", - "s=ASDF1234" - ) + null to listOf("HTTP/1.1 200 OK"), + "Set-Cookie" to listOf( + "xp=$xp;Path=/;Expires=Fri, 20-Sep-2019 14:30:24 GMT", + "s=ASDF1234" + ) ) val response = ResponseModel.Builder() - .statusCode(200) - .message("OK") - .headers(headers) - .requestModel(requestModel) - .build() + .statusCode(200) + .message("OK") + .headers(headers) + .requestModel(requestModel) + .build() responseHandler.handleResponse(response) diff --git a/predict/src/androidTest/java/com/emarsys/predict/shard/PredictShardListMergerTest.kt b/predict/src/androidTest/java/com/emarsys/predict/shard/PredictShardListMergerTest.kt index 46fe4c03..9eef87af 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/shard/PredictShardListMergerTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/shard/PredictShardListMergerTest.kt @@ -9,14 +9,15 @@ import com.emarsys.core.storage.KeyValueStore import com.emarsys.predict.provider.PredictRequestModelBuilderProvider import com.emarsys.predict.request.PredictRequestContext import com.emarsys.predict.request.PredictRequestModelBuilder -import com.emarsys.testUtil.TimeoutUtils import com.emarsys.testUtil.mockito.whenever -import io.kotlintest.shouldBe -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule -import org.mockito.Mockito.* +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.Mockito.any +import org.mockito.Mockito.anyMap +import org.mockito.Mockito.mock +import org.mockito.Mockito.verify class PredictShardListMergerTest { @@ -45,11 +46,8 @@ class PredictShardListMergerTest { private lateinit var shard2: ShardModel private lateinit var shard3: ShardModel - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule - @Before + @BeforeEach fun init() { mockStore = mock(KeyValueStore::class.java) mockTimestampProvider = mock(TimestampProvider::class.java) @@ -69,9 +67,12 @@ class PredictShardListMergerTest { whenever(withShardData(anyMap())).thenReturn(this) } - mockPredictRequestModelBuilderProvider = mock(PredictRequestModelBuilderProvider::class.java).apply { - whenever(providePredictRequestModelBuilder()).thenReturn(mockPredictRequestModelBuilder) - } + mockPredictRequestModelBuilderProvider = + mock(PredictRequestModelBuilderProvider::class.java).apply { + whenever(providePredictRequestModelBuilder()).thenReturn( + mockPredictRequestModelBuilder + ) + } whenever(mockTimestampProvider.provideTimestamp()).thenReturn(TIMESTAMP) @@ -79,48 +80,64 @@ class PredictShardListMergerTest { whenever(mockDeviceInfo.osVersion).thenReturn(OS_VERSION) whenever(mockDeviceInfo.platform).thenReturn(PLATFORM) - merger = PredictShardListMerger(mockPredictRequestContext, mockPredictRequestModelBuilderProvider) + merger = PredictShardListMerger( + mockPredictRequestContext, + mockPredictRequestModelBuilderProvider + ) shard1 = ShardModel("id1", "type1", mapOf("q1" to 1, "q2" to "b"), 100, 100) shard2 = ShardModel("id2", "type2", mapOf("q3" to "c"), 110, 100) shard3 = ShardModel("id3", "type3", mapOf("<>," to "\"`;/?:^%#@&=\$+{}<>,| "), 120, 100) } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_predictRequestContext_mustNotBeNull() { - PredictShardListMerger(null, mockPredictRequestModelBuilderProvider) + shouldThrow { + PredictShardListMerger(null, mockPredictRequestModelBuilderProvider) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testConstructor_predictRequestModelBuilderProvider_mustNotBeNull() { - PredictShardListMerger(mockPredictRequestContext, null) + shouldThrow { + PredictShardListMerger(mockPredictRequestContext, null) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testMap_shards_mustNotBeNull() { - merger.map(null) + shouldThrow { + merger.map(null) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testMap_shards_mustNotContainNullElements() { - merger.map(listOf( - mock(ShardModel::class.java), - null, - mock(ShardModel::class.java) - )) + shouldThrow { + merger.map( + listOf( + mock(ShardModel::class.java), + null, + mock(ShardModel::class.java) + ) + ) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testMap_shards_mustContainAtLeastOneElement() { - merger.map(listOf()) + shouldThrow { + merger.map(listOf()) + } } @Test fun testMap_singletonList_withMultipleParams() { val expected = mapOf( - "cp" to 1, - "q1" to 1, - "q2" to "b") + "cp" to 1, + "q1" to 1, + "q2" to "b" + ) merger.map(listOf(shard1)) verify(mockPredictRequestModelBuilder).withShardData(expected) @@ -130,10 +147,11 @@ class PredictShardListMergerTest { @Test fun testMap_multipleShards() { val expected = mapOf( - "cp" to 1, - "q1" to 1, - "q2" to "b", - "q3" to "c") + "cp" to 1, + "q1" to 1, + "q2" to "b", + "q3" to "c" + ) merger.map(listOf(shard1, shard2)) verify(mockPredictRequestModelBuilder).withShardData(expected) @@ -143,8 +161,9 @@ class PredictShardListMergerTest { @Test fun testMap_withoutVisitorIdOrContactId() { val expected = mapOf( - "cp" to 1, - "<>," to "\"`;/?:^%#@&=\$+{}<>,| ") + "cp" to 1, + "<>," to "\"`;/?:^%#@&=\$+{}<>,| " + ) merger.map(listOf(shard3)) @@ -157,9 +176,10 @@ class PredictShardListMergerTest { whenever(mockStore.getString("predict_visitor_id")).thenReturn(VISITOR_ID) val expected = mapOf( - "cp" to 1, - "q3" to "c", - "vi" to "888999888") + "cp" to 1, + "q3" to "c", + "vi" to "888999888" + ) merger.map(listOf(shard2)) @@ -172,9 +192,10 @@ class PredictShardListMergerTest { whenever(mockStore.getString("predict_contact_id")).thenReturn(CONTACT_ID) val expected = mapOf( - "cp" to 1, - "q3" to "c", - "ci" to "12345") + "cp" to 1, + "q3" to "c", + "ci" to "12345" + ) merger.map(listOf(shard2)) @@ -188,10 +209,11 @@ class PredictShardListMergerTest { whenever(mockStore.getString("predict_contact_id")).thenReturn(CONTACT_ID) val expected = mapOf( - "cp" to 1, - "q3" to "c", - "vi" to "888999888", - "ci" to "12345") + "cp" to 1, + "q3" to "c", + "vi" to "888999888", + "ci" to "12345" + ) merger.map(listOf(shard2)) diff --git a/predict/src/androidTest/java/com/emarsys/predict/storage/PredictStorageKeyTest.kt b/predict/src/androidTest/java/com/emarsys/predict/storage/PredictStorageKeyTest.kt index 9516428f..863ca74a 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/storage/PredictStorageKeyTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/storage/PredictStorageKeyTest.kt @@ -1,27 +1,23 @@ package com.emarsys.predict.storage -import com.emarsys.testUtil.TimeoutUtils -import io.kotlintest.data.forall -import io.kotlintest.shouldBe -import io.kotlintest.tables.row -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.data.forAll +import io.kotest.data.row +import io.kotest.matchers.shouldBe +import kotlinx.coroutines.runBlocking +import org.junit.jupiter.api.Test + class PredictStorageKeyTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule @Test - fun testGetKey() { + fun testGetKey() = runBlocking { PredictStorageKey.values().map { "predict_${it.name.lowercase()}" }.zip(PredictStorageKey.values()) { stringValue, enum -> row(enum, stringValue) }.let { - forall(*it.toTypedArray()) { input, expected -> + forAll(*it.toTypedArray()) { input, expected -> input.key shouldBe expected } } diff --git a/predict/src/androidTest/java/com/emarsys/predict/util/CartItemUtilsTest.kt b/predict/src/androidTest/java/com/emarsys/predict/util/CartItemUtilsTest.kt index d0fbe3c3..c653478b 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/util/CartItemUtilsTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/util/CartItemUtilsTest.kt @@ -2,62 +2,67 @@ package com.emarsys.predict.util import com.emarsys.predict.api.model.CartItem import com.emarsys.predict.api.model.PredictCartItem -import com.emarsys.testUtil.TimeoutUtils -import org.junit.Assert.assertEquals -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TestRule +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe + +import org.junit.jupiter.api.BeforeEach + +import org.junit.jupiter.api.Test + import org.mockito.Mockito.mock class CartItemUtilsTest { - @Rule - @JvmField - val timeout: TestRule = TimeoutUtils.timeoutRule private lateinit var cartItem1: CartItem private lateinit var cartItem2: CartItem private lateinit var cartItem3: CartItem - @Before + @BeforeEach fun init() { cartItem1 = PredictCartItem("1", 100.0, 2.0) cartItem2 = PredictCartItem("2", 200.0, 4.0) cartItem3 = PredictCartItem("3", 300.0, 8.0) } - @Test(expected = IllegalArgumentException::class) + @Test fun testCartItemsToQueryParam_cartItems_mustNotBeNull() { - CartItemUtils.cartItemsToQueryParam(null) + shouldThrow { + CartItemUtils.cartItemsToQueryParam(null) + } } - @Test(expected = IllegalArgumentException::class) + @Test fun testCartItemsToQueryParam_cartItems_mustNotContainNullElements() { - CartItemUtils.cartItemsToQueryParam(listOf( - mock(CartItem::class.java), - null, - mock(CartItem::class.java) - )) + shouldThrow { + CartItemUtils.cartItemsToQueryParam( + listOf( + mock(CartItem::class.java), + null, + mock(CartItem::class.java) + ) + ) + } } @Test fun testCartItemsToQueryParam_emptyList() { - assertEquals("", CartItemUtils.cartItemsToQueryParam(listOf())) + CartItemUtils.cartItemsToQueryParam(listOf()) shouldBe "" } @Test fun testCartItemsToQueryParam_singletonList() { - assertEquals( - "i:1,p:100.0,q:2.0", - CartItemUtils.cartItemsToQueryParam(listOf(cartItem1))) + CartItemUtils.cartItemsToQueryParam(listOf(cartItem1)) shouldBe "i:1,p:100.0,q:2.0" } @Test fun testCartItemsToQueryParam() { - assertEquals( - "i:1,p:100.0,q:2.0|i:2,p:200.0,q:4.0|i:3,p:300.0,q:8.0", - CartItemUtils.cartItemsToQueryParam(listOf(cartItem1, cartItem2, cartItem3))) + CartItemUtils.cartItemsToQueryParam( + listOf( + cartItem1, + cartItem2, + cartItem3 + ) + ) shouldBe "i:1,p:100.0,q:2.0|i:2,p:200.0,q:4.0|i:3,p:300.0,q:8.0" } - } \ No newline at end of file diff --git a/sample/build.gradle.kts b/sample/build.gradle.kts index 043083e2..ef34aa25 100644 --- a/sample/build.gradle.kts +++ b/sample/build.gradle.kts @@ -16,6 +16,8 @@ android { applicationId = "com.emarsys.sample" compileSdk = libs.versions.android.compileSdk.get().toInt() minSdk = libs.versions.android.minSdk.get().toInt() + multiDexEnabled = true + lint { targetSdk = libs.versions.android.targetSdk.get().toInt() } @@ -34,11 +36,15 @@ android { } buildFeatures { + buildConfig = true compose = true } + compileOptions { + isCoreLibraryDesugaringEnabled = true + } allOpen { - annotation("com.emarsys.core.Mockable") + annotation("kotlin.AnyClass") } kotlin { @@ -73,7 +79,7 @@ android { multiDexEnabled = true } } - packagingOptions { + packaging { resources { excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") } @@ -93,30 +99,32 @@ dependencies { // Getting a "Could not find firebase-core" error? Make sure you have // the latest Google Repository in the Android SDK manager - implementation("org.jetbrains.kotlin:kotlin-reflect:1.9.21") - implementation("org.jetbrains.kotlin:kotlin-stdlib:1.9.21") - implementation("com.google.android.material:material:1.11.0") - implementation("com.android.support:cardview-v7:28.0.0") - implementation("com.google.android.gms:play-services-auth:20.7.0") - implementation("androidx.appcompat:appcompat:1.6.1") - implementation("io.coil-kt:coil:2.5.0") + implementation(libs.kotlin.reflect) + implementation(libs.kotlin.stdlib) + implementation(libs.androidx.material) + // implementation("androidx.cardview:cardview:1.0.0") + implementation(libs.play.services.auth) + implementation(libs.androidx.appcompat) + implementation(libs.io.coil) + + implementation(libs.androidx.core.ktx) + // implementation("com.google.android.material:material:1.11.0") + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.material) + implementation(libs.androidx.compose.ui.tooling.preview) + implementation(libs.androidx.navigation.compose) + implementation(libs.androidx.compose.material.icons) + implementation(libs.androidx.lifecycle.runtime) + implementation(libs.androidx.activity.compose) + implementation(libs.io.coil.compose) + implementation(libs.androidx.datastore.preferences) + implementation(libs.kotpref) + implementation(libs.google.firebase.common) + implementation(libs.google.firebase.messaging) + implementation(libs.play.services.auth) + implementation(libs.google.accompanist.swipetorefresh) + implementation(libs.google.gson) + debugImplementation(libs.androidx.compose.ui.tooling) - implementation("androidx.core:core-ktx:1.12.0") - implementation("com.google.android.material:material:1.11.0") - implementation("androidx.compose.ui:ui:1.6.0") - implementation("androidx.compose.material:material:1.6.0") - implementation("androidx.compose.ui:ui-tooling-preview:1.6.0") - implementation("androidx.navigation:navigation-compose:2.7.6") - implementation("androidx.compose.material:material-icons-extended:1.6.0") - implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0") - implementation("androidx.activity:activity-compose:1.8.2") - implementation("io.coil-kt:coil-compose:2.5.0") - implementation("androidx.datastore:datastore-preferences:1.0.0") - implementation("com.chibatching.kotpref:kotpref:2.13.2") - implementation("com.google.firebase:firebase-common-ktx:20.4.2") - implementation("com.google.firebase:firebase-messaging-ktx:23.4.0") - implementation("com.google.android.gms:play-services-auth:20.7.0") - implementation("com.google.accompanist:accompanist-swiperefresh:0.34.0") - implementation("com.google.code.gson:gson:2.10.1") - debugImplementation("androidx.compose.ui:ui-tooling:1.6.0") + coreLibraryDesugaring(libs.android.tools.desugar) } \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts index 97ee31f5..f8af2969 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,11 +1,10 @@ pluginManagement { repositories { google() - mavenCentral() gradlePluginPortal() - maven(url = "https://androidx.dev/storage/compose-compiler/repository/") - maven(url = "https://developer.huawei.com/repo/") - maven(url = "https://ajoberstar.org/bintray-backup/") + mavenCentral() + maven("https://maven.pkg.jetbrains.space/public/p/compose/dev") + maven("https://developer.huawei.com/repo/") } resolutionStrategy { eachPlugin { @@ -17,31 +16,31 @@ pluginManagement { } } } + dependencyResolutionManagement { repositories { google() mavenCentral() - maven(url = "https://maven.google.com") - maven(url = "https://developer.huawei.com/repo/") - maven(url = "https://ajoberstar.org/bintray-backup/") - maven(url = "https://androidx.dev/storage/compose-compiler/repository/") + maven("https://maven.pkg.jetbrains.space/public/p/compose/dev") + maven("https://developer.huawei.com/repo/") } } + rootProject.name = "Android Emarsys SDK" include( ":common", - "core", + ":core", ":core-api", - "emarsys", + ":emarsys", ":emarsys-e2e-test", - "emarsys-firebase", + ":emarsys-firebase", ":emarsys-huawei", - "emarsys-sdk", + ":emarsys-sdk", ":mobile-engage", - "mobile-engage-api", + ":mobile-engage-api", ":predict", - "predict-api", + ":predict-api", ":sample", - "testUtils" + ":testUtils" ) \ No newline at end of file diff --git a/testUtils/build.gradle.kts b/testUtils/build.gradle.kts index 08c54dc6..2dd8eaee 100644 --- a/testUtils/build.gradle.kts +++ b/testUtils/build.gradle.kts @@ -1,17 +1,25 @@ plugins { alias(libs.plugins.android.library) alias(libs.plugins.kotlin) + alias(libs.plugins.android.junit5) } android { namespace = "com.emarsys.testUtil" - compileSdk = libs.versions.android.compileSdk.get().toInt() defaultConfig { + compileSdk = libs.versions.android.compileSdk.get().toInt() minSdk = libs.versions.android.minSdk.get().toInt() + + multiDexEnabled = true lint { targetSdk = libs.versions.android.targetSdk.get().toInt() } testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + testInstrumentationRunnerArgument( + "runnerBuilder", + "de.mannodermaus.junit5.AndroidJUnit5Builder" + ) + } buildTypes { release { @@ -22,11 +30,14 @@ android { multiDexEnabled = true } } - packagingOptions { + packaging { resources { excludes += arrayOf("README.txt", "META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") } } + compileOptions { + isCoreLibraryDesugaringEnabled = true + } lint { abortOnError = false @@ -34,8 +45,8 @@ android { kotlin { jvmToolchain(17) } -} +} group = "com.emarsys.testUtil" dependencies { @@ -47,17 +58,28 @@ dependencies { implementation(libs.kotlin.reflect) api(libs.kotest.assertions.core) api(libs.mockito.android) - api(libs.mockito.core) api(libs.mockito.kotlin) - api(libs.byte.buddy) - api(libs.androidx.test.runner) api(libs.androidx.test.rules) api(libs.androidx.test.multidex) + api(libs.androidx.test.core) api(libs.mockk.android) api(libs.mockk.agent) + + api("de.mannodermaus.junit5:android-test-core:1.4.0") + api("de.mannodermaus.junit5:android-test-runner:1.4.0") + api("de.mannodermaus.junit5:android-test-extensions:1.4.0") + api("org.junit.jupiter:junit-jupiter-api:5.10.0") + api("org.junit.jupiter:junit-jupiter:5.10.0") + api("org.junit-pioneer:junit-pioneer:2.2.0") + runtimeOnly("org.junit.jupiter:junit-jupiter-engine:5.10.0") + androidTestApi("org.junit.jupiter:junit-jupiter-api:5.10.0") + androidTestRuntimeOnly("de.mannodermaus.junit5:android-test-runner:1.4.0") + + coreLibraryDesugaring(libs.android.tools.desugar) } configurations { api { exclude(group = "io.mockk", module = "mockk-agent-jvm") } -} \ No newline at end of file +} +junitPlatform {} \ No newline at end of file diff --git a/testUtils/src/main/java/com/emarsys/testUtil/ExtensionTestUtils.kt b/testUtils/src/main/java/com/emarsys/testUtil/ExtensionTestUtils.kt index 1a398d8b..3baf9fbd 100644 --- a/testUtils/src/main/java/com/emarsys/testUtil/ExtensionTestUtils.kt +++ b/testUtils/src/main/java/com/emarsys/testUtil/ExtensionTestUtils.kt @@ -15,13 +15,17 @@ object ExtensionTestUtils { fun Any.runOnMain(logic: () -> T): T { val uiHandler = Handler(Looper.getMainLooper()) - var result: T? = null - val latch = CountDownLatch(1) - uiHandler.post { - result = logic() - latch.countDown() + return if (Thread.currentThread() != uiHandler.looper.thread) { + var result: T? = null + val latch = CountDownLatch(1) + uiHandler.post { + result = logic() + latch.countDown() + } + latch.await() + result!! + } else { + logic() } - latch.await() - return result!! } } \ No newline at end of file diff --git a/testUtils/src/main/java/com/emarsys/testUtil/RetryUtils.kt b/testUtils/src/main/java/com/emarsys/testUtil/RetryUtils.kt deleted file mode 100644 index 54168b21..00000000 --- a/testUtils/src/main/java/com/emarsys/testUtil/RetryUtils.kt +++ /dev/null @@ -1,9 +0,0 @@ -package com.emarsys.testUtil - -import com.emarsys.testUtil.rules.RetryRule - -object RetryUtils { - @JvmStatic - val retryRule - get() = RetryRule(3) -} \ No newline at end of file diff --git a/testUtils/src/main/java/com/emarsys/testUtil/mockito/ThreadSpy.kt b/testUtils/src/main/java/com/emarsys/testUtil/mockito/ThreadSpy.kt index f383932a..e8fb4ae7 100644 --- a/testUtils/src/main/java/com/emarsys/testUtil/mockito/ThreadSpy.kt +++ b/testUtils/src/main/java/com/emarsys/testUtil/mockito/ThreadSpy.kt @@ -1,7 +1,7 @@ package com.emarsys.testUtil.mockito import android.os.Looper -import io.kotlintest.shouldBe +import io.kotest.matchers.shouldBe import org.mockito.invocation.InvocationOnMock import org.mockito.stubbing.Answer import java.util.concurrent.CountDownLatch diff --git a/testUtils/src/main/java/com/emarsys/testUtil/rules/ConnectionRule.kt b/testUtils/src/main/java/com/emarsys/testUtil/rules/ConnectionRule.kt index fab45427..0eec0aca 100644 --- a/testUtils/src/main/java/com/emarsys/testUtil/rules/ConnectionRule.kt +++ b/testUtils/src/main/java/com/emarsys/testUtil/rules/ConnectionRule.kt @@ -2,20 +2,12 @@ package com.emarsys.testUtil.rules import android.app.Application import com.emarsys.testUtil.ConnectionTestUtils -import org.junit.rules.TestRule -import org.junit.runner.Description -import org.junit.runners.model.Statement +import org.junit.jupiter.api.extension.BeforeEachCallback +import org.junit.jupiter.api.extension.ExtensionContext -class ConnectionRule(private val application: Application) : TestRule { - - override fun apply(base: Statement?, description: Description?): Statement { - return object : Statement() { - override fun evaluate() { - ConnectionTestUtils.checkConnection(application) - base?.evaluate() - return - } - } +class ConnectionExtension(private val application: Application) : BeforeEachCallback { + override fun beforeEach(p0: ExtensionContext?) { + ConnectionTestUtils.checkConnection(application) } diff --git a/testUtils/src/main/java/com/emarsys/testUtil/rules/DuplicatedThreadRule.kt b/testUtils/src/main/java/com/emarsys/testUtil/rules/DuplicatedThreadRule.kt index 5d566cf0..592bc89b 100644 --- a/testUtils/src/main/java/com/emarsys/testUtil/rules/DuplicatedThreadRule.kt +++ b/testUtils/src/main/java/com/emarsys/testUtil/rules/DuplicatedThreadRule.kt @@ -1,21 +1,17 @@ package com.emarsys.testUtil.rules -import org.junit.rules.TestRule -import org.junit.runner.Description -import org.junit.runners.model.Statement -class DuplicatedThreadRule(private val threadName: String) : TestRule { +import org.junit.jupiter.api.extension.BeforeEachCallback +import org.junit.jupiter.api.extension.ExtensionContext - override fun apply(base: Statement?, description: Description?): Statement { - return object : Statement() { - override fun evaluate() { - val threads = Thread.getAllStackTraces().keys.map { it.name }.filter { it.startsWith(threadName) } - if (threads.size > 1) { - throw Throwable("TEST: $threadName thread is duplicated") - } - base?.evaluate() - return - } +class DuplicatedThreadExtension(private val threadName: String = "CoreSDKHandlerThread") : + BeforeEachCallback { + + override fun beforeEach(p0: ExtensionContext?) { + val threads = + Thread.getAllStackTraces().keys.map { it.name }.filter { it.startsWith(threadName) } + if (threads.size > 1) { + throw Throwable("TEST: $threadName thread is duplicated") } } diff --git a/testUtils/src/main/java/com/emarsys/testUtil/rules/RetryRule.kt b/testUtils/src/main/java/com/emarsys/testUtil/rules/RetryRule.kt deleted file mode 100644 index b0bba3e9..00000000 --- a/testUtils/src/main/java/com/emarsys/testUtil/rules/RetryRule.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.emarsys.testUtil.rules - -import android.util.Log -import org.junit.rules.TestRule -import org.junit.runner.Description -import org.junit.runners.model.Statement - - -class RetryRule(private val retryCount: Int) : TestRule { - - override fun apply(base: Statement, description: Description) = statement(base, description) - - private fun statement(base: Statement, description: Description): Statement { - return object : Statement() { - override fun evaluate() { - var caughtThrowable: Throwable? = null - - for (i in 0..retryCount) { - try { - base.evaluate() - return - } catch (t: Throwable) { - caughtThrowable = t - Log.e("TEST", "${description.displayName}: run ${(i + 1)} failed.") - } - } - Log.e("TEST", "${description.displayName}: giving up after $retryCount failures.") - throw caughtThrowable!! - } - } - } -} \ No newline at end of file From 99df43429188db2e78fc869ca083292e605bcb2d Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Thu, 22 Feb 2024 17:06:37 +0100 Subject: [PATCH 10/63] chore(gradle): update gradle version SUITEDEV-35237 Co-authored-by: megamegax --- gradle/wrapper/gradle-wrapper.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index b93c46a5..510e4efa 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-8.2-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-all.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists From 5b1540dd3b23dcb64762ded039907696d19bd640 Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Thu, 22 Feb 2024 17:07:33 +0100 Subject: [PATCH 11/63] chore(pipeline): updated env variable reading and makefile SUITEDEV-35237 Co-authored-by: megamegax --- Makefile | 3 +-- buildSrc/build.gradle.kts | 1 - sample/build.gradle.kts | 14 +++++++------- 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/Makefile b/Makefile index 070ecf53..10c41c05 100644 --- a/Makefile +++ b/Makefile @@ -27,13 +27,12 @@ help: check-env ## Show this help @echo build-test: check-env ## builds android tests excluding and lint - @./gradlew clean assembleAndroidTest -x lint -x + @./gradlew clean assembleAndroidTest -x lint create-apks: check-env ## create apks for testing @./gradlew assembleAndroidTest -x :sample:test prepare-ci: check-env ## setup prerequisites for pipeline - @chmod +x gradlew @echo $ANDROID_HOME > local.properties @./gradlew base64EnvToFile -PpropertyName=GOOGLE_SERVICES_JSON_BASE64 -Pfile=./sample/google-services.json diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index 4c576351..ddb09cf0 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -1,6 +1,5 @@ plugins { id("org.jetbrains.kotlin.jvm") version "1.9.0" - `kotlin-dsl` } repositories { diff --git a/sample/build.gradle.kts b/sample/build.gradle.kts index ef34aa25..7da579f0 100644 --- a/sample/build.gradle.kts +++ b/sample/build.gradle.kts @@ -31,7 +31,7 @@ android { buildConfigField( "String", "GOOGLE_OAUTH_SERVER_CLIENT_ID", - "\"${env.GOOGLE_OAUTH_SERVER_CLIENT_ID.value}\"" + env.fetch("GOOGLE_OAUTH_SERVER_CLIENT_ID", System.getenv("GOOGLE_OAUTH_SERVER_CLIENT_ID") ?: "") ) } @@ -55,13 +55,13 @@ android { kotlinCompilerExtensionVersion = libs.versions.compose.compiler.get().toString() } - if (env.RELEASE_MODE.orElse("false") == "true") { + if (env.fetch("RELEASE_MODE", (System.getenv("RELEASE_MODE") ?: "false")) == "true") { signingConfigs { create("release") { - storePassword = env.ANDROID_RELEASE_STORE_PASSWORD.value - keyAlias = env.ANDROID_RELEASE_KEY_ALIAS.value - keyPassword = env.ANDROID_RELEASE_KEY_PASSWORD.value - storeFile = file(env.ANDROID_RELEASE_STORE_FILE_BASE64.value) + storePassword = env.fetch( "ANDROID_RELEASE_STORE_PASSWORD", (System.getenv("ANDROID_RELEASE_STORE_PASSWORD") ?: "")) + keyAlias = env.fetch("ANDROID_RELEASE_KEY_ALIAS", (System.getenv("ANDROID_RELEASE_KEY_ALIAS") ?: "")) + keyPassword = env.fetch("ANDROID_RELEASE_KEY_PASSWORD", (System.getenv("ANDROID_RELEASE_KEY_PASSWORD") ?: "")) + storeFile = file(env.fetch("ANDROID_RELEASE_STORE_FILE_BASE64", (System.getenv("ANDROID_RELEASE_STORE_FILE_BASE64") ?: ""))) } } buildTypes { @@ -87,7 +87,7 @@ android { } dependencies { - if (env.USE_LOCAL_DEPENDENCY.orElse("false") == "true") { + if (env.fetch("USE_LOCAL_DEPENDENCY", (System.getenv("USE_LOCAL_DEPENDENCY") ?: "false")) == "true") { implementation(project(":emarsys-sdk")) implementation(project(":emarsys-firebase")) implementation(project(":emarsys-huawei")) From bda8731fb5ed0fe9c5883ca25f8e79a321ea3d49 Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Thu, 22 Feb 2024 17:13:11 +0100 Subject: [PATCH 12/63] chore(pipeline): rename new workflow SUITEDEV-35237 Co-authored-by: megamegax --- .github/workflows/on_push_workflow_new.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml index 837d25f4..a4396803 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/on_push_workflow_new.yml @@ -1,4 +1,4 @@ -name: Last push build +name: New on commit workflow on: workflow_dispatch: From b3964405c14ed452d21612f647074934f1af0b56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Thu, 22 Feb 2024 17:18:19 +0100 Subject: [PATCH 13/63] test(chore): remove warnings and fix huawei tests SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> --- common/build.gradle.kts | 4 +--- core-api/build.gradle.kts | 4 +--- core/build.gradle.kts | 5 ++--- emarsys-e2e-test/build.gradle.kts | 4 +--- emarsys-firebase/build.gradle.kts | 4 +--- emarsys-huawei/build.gradle.kts | 4 +--- .../com/emarsys/service/EmarsysHuaweiMessagingServiceTest.kt | 5 +++-- emarsys-sdk/build.gradle.kts | 4 +--- emarsys/build.gradle.kts | 4 +--- mobile-engage-api/build.gradle.kts | 4 +--- mobile-engage/build.gradle.kts | 4 +--- predict-api/build.gradle.kts | 4 +--- predict/build.gradle.kts | 4 +--- testUtils/build.gradle.kts | 4 +--- 14 files changed, 17 insertions(+), 41 deletions(-) diff --git a/common/build.gradle.kts b/common/build.gradle.kts index 838c9b10..b1c6ae25 100644 --- a/common/build.gradle.kts +++ b/common/build.gradle.kts @@ -19,10 +19,8 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArgument( - "runnerBuilder", + testInstrumentationRunnerArguments["runnerBuilder"] = "de.mannodermaus.junit5.AndroidJUnit5Builder" - ) } compileOptions { isCoreLibraryDesugaringEnabled = true diff --git a/core-api/build.gradle.kts b/core-api/build.gradle.kts index 9913c2aa..0ebd99ad 100644 --- a/core-api/build.gradle.kts +++ b/core-api/build.gradle.kts @@ -25,10 +25,8 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArgument( - "runnerBuilder", + testInstrumentationRunnerArguments["runnerBuilder"] = "de.mannodermaus.junit5.AndroidJUnit5Builder" - ) } compileOptions { isCoreLibraryDesugaringEnabled = true diff --git a/core/build.gradle.kts b/core/build.gradle.kts index 9166561e..206ad6be 100644 --- a/core/build.gradle.kts +++ b/core/build.gradle.kts @@ -25,10 +25,9 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArgument( - "runnerBuilder", + testInstrumentationRunnerArguments["runnerBuilder"] = "de.mannodermaus.junit5.AndroidJUnit5Builder" - ) + val version: GitVersion by rootProject.extra buildConfigField("int", "VERSION_CODE", "${version.versionCode}") diff --git a/emarsys-e2e-test/build.gradle.kts b/emarsys-e2e-test/build.gradle.kts index a3bde3d3..7182a6cf 100644 --- a/emarsys-e2e-test/build.gradle.kts +++ b/emarsys-e2e-test/build.gradle.kts @@ -23,10 +23,8 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArgument( - "runnerBuilder", + testInstrumentationRunnerArguments["runnerBuilder"] = "de.mannodermaus.junit5.AndroidJUnit5Builder" - ) } compileOptions { isCoreLibraryDesugaringEnabled = true diff --git a/emarsys-firebase/build.gradle.kts b/emarsys-firebase/build.gradle.kts index 2ea33f05..04aa81ed 100644 --- a/emarsys-firebase/build.gradle.kts +++ b/emarsys-firebase/build.gradle.kts @@ -25,10 +25,8 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArgument( - "runnerBuilder", + testInstrumentationRunnerArguments["runnerBuilder"] = "de.mannodermaus.junit5.AndroidJUnit5Builder" - ) } compileOptions { isCoreLibraryDesugaringEnabled = true diff --git a/emarsys-huawei/build.gradle.kts b/emarsys-huawei/build.gradle.kts index c6fea274..42152171 100644 --- a/emarsys-huawei/build.gradle.kts +++ b/emarsys-huawei/build.gradle.kts @@ -26,10 +26,8 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArgument( - "runnerBuilder", + testInstrumentationRunnerArguments["runnerBuilder"] = "de.mannodermaus.junit5.AndroidJUnit5Builder" - ) } compileOptions { isCoreLibraryDesugaringEnabled = true diff --git a/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceTest.kt b/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceTest.kt index c0a6b68f..337f1d54 100644 --- a/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceTest.kt +++ b/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceTest.kt @@ -27,7 +27,6 @@ import org.mockito.kotlin.verify class EmarsysHuaweiMessagingServiceTest { - private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application @@ -48,7 +47,9 @@ class EmarsysHuaweiMessagingServiceTest { "coreHandler", spyCoreHandler ) - Looper.prepare() + if (Looper.myLooper() == null) { + Looper.prepare() + } emarsysHuaweiMessagingService = EmarsysHuaweiMessagingService() } diff --git a/emarsys-sdk/build.gradle.kts b/emarsys-sdk/build.gradle.kts index cc70e838..59c15d51 100644 --- a/emarsys-sdk/build.gradle.kts +++ b/emarsys-sdk/build.gradle.kts @@ -29,10 +29,8 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArgument( - "runnerBuilder", + testInstrumentationRunnerArguments["runnerBuilder"] = "de.mannodermaus.junit5.AndroidJUnit5Builder" - ) } compileOptions { isCoreLibraryDesugaringEnabled = true diff --git a/emarsys/build.gradle.kts b/emarsys/build.gradle.kts index 9e5f2b81..11d1e7f0 100644 --- a/emarsys/build.gradle.kts +++ b/emarsys/build.gradle.kts @@ -27,10 +27,8 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArgument( - "runnerBuilder", + testInstrumentationRunnerArguments["runnerBuilder"] = "de.mannodermaus.junit5.AndroidJUnit5Builder" - ) } compileOptions { isCoreLibraryDesugaringEnabled = true diff --git a/mobile-engage-api/build.gradle.kts b/mobile-engage-api/build.gradle.kts index b42470a4..e094252d 100644 --- a/mobile-engage-api/build.gradle.kts +++ b/mobile-engage-api/build.gradle.kts @@ -23,10 +23,8 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArgument( - "runnerBuilder", + testInstrumentationRunnerArguments["runnerBuilder"] = "de.mannodermaus.junit5.AndroidJUnit5Builder" - ) } compileOptions { isCoreLibraryDesugaringEnabled = true diff --git a/mobile-engage/build.gradle.kts b/mobile-engage/build.gradle.kts index c87207db..fde89e99 100644 --- a/mobile-engage/build.gradle.kts +++ b/mobile-engage/build.gradle.kts @@ -27,10 +27,8 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArgument( - "runnerBuilder", + testInstrumentationRunnerArguments["runnerBuilder"] = "de.mannodermaus.junit5.AndroidJUnit5Builder" - ) } compileOptions { isCoreLibraryDesugaringEnabled = true diff --git a/predict-api/build.gradle.kts b/predict-api/build.gradle.kts index c0c7bc97..20a8c2a6 100644 --- a/predict-api/build.gradle.kts +++ b/predict-api/build.gradle.kts @@ -20,10 +20,8 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArgument( - "runnerBuilder", + testInstrumentationRunnerArguments["runnerBuilder"] = "de.mannodermaus.junit5.AndroidJUnit5Builder" - ) } compileOptions { isCoreLibraryDesugaringEnabled = true diff --git a/predict/build.gradle.kts b/predict/build.gradle.kts index fa3647f9..1145c55e 100644 --- a/predict/build.gradle.kts +++ b/predict/build.gradle.kts @@ -23,10 +23,8 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArgument( - "runnerBuilder", + testInstrumentationRunnerArguments["runnerBuilder"] = "de.mannodermaus.junit5.AndroidJUnit5Builder" - ) } compileOptions { isCoreLibraryDesugaringEnabled = true diff --git a/testUtils/build.gradle.kts b/testUtils/build.gradle.kts index 2dd8eaee..95269230 100644 --- a/testUtils/build.gradle.kts +++ b/testUtils/build.gradle.kts @@ -15,10 +15,8 @@ android { targetSdk = libs.versions.android.targetSdk.get().toInt() } testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArgument( - "runnerBuilder", + testInstrumentationRunnerArguments["runnerBuilder"] = "de.mannodermaus.junit5.AndroidJUnit5Builder" - ) } buildTypes { From 6a576cb1a19849f6e87762bc116ed250350cba58 Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Thu, 22 Feb 2024 17:29:24 +0100 Subject: [PATCH 14/63] fix(sample): fix buildConfigField SUITEDEV-35237 Co-authored-by: megamegax --- sample/build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sample/build.gradle.kts b/sample/build.gradle.kts index 7da579f0..77d47c5b 100644 --- a/sample/build.gradle.kts +++ b/sample/build.gradle.kts @@ -31,7 +31,7 @@ android { buildConfigField( "String", "GOOGLE_OAUTH_SERVER_CLIENT_ID", - env.fetch("GOOGLE_OAUTH_SERVER_CLIENT_ID", System.getenv("GOOGLE_OAUTH_SERVER_CLIENT_ID") ?: "") + "\"${env.fetch("GOOGLE_OAUTH_SERVER_CLIENT_ID", System.getenv("GOOGLE_OAUTH_SERVER_CLIENT_ID") ?: "")}\"" ) } From 50febdb8738bdef9658667e5c35877256e9c269e Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Thu, 22 Feb 2024 20:33:34 +0100 Subject: [PATCH 15/63] chore(pipeline): updated emulators to supported minSDK SUITEDEV-35237 Co-authored-by: megamegax --- .github/workflows/on_push_workflow_new.yml | 2 ++ Makefile | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml index a4396803..d9287000 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/on_push_workflow_new.yml @@ -2,6 +2,8 @@ name: New on commit workflow on: workflow_dispatch: + push: + branches: [ dev ] env: USE_LOCAL_DEPENDENCY: ${{ vars.USE_LOCAL_DEPENDENCY }} diff --git a/Makefile b/Makefile index 10c41c05..1339f5c6 100644 --- a/Makefile +++ b/Makefile @@ -41,7 +41,7 @@ test-android-firebase-emulator: check-env ## run Android Instrumented tests on e --type instrumentation \ --app ./sample/build/outputs/apk/androidTest/debug/sample-debug-androidTest.apk \ --test ./$(MODULE_NAME)/build/outputs/apk/androidTest/debug/$(MODULE_NAME)-debug-androidTest.apk \ - --device model=Nexus5X,version=24,locale=en,orientation=portrait \ + --device model=Pixel2.arm,version=28,locale=en,orientation=portrait \ --device model=Pixel2,version=30,locale=en,orientation=portrait \ --device model=SmallPhone,version=33,locale=en,orientation=portrait \ --client-details matrixLabel="Android Emarsys SDK" From 7f6a2c2e2a6d509456ab9ab2743c02c6418680fc Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Thu, 22 Feb 2024 21:09:44 +0100 Subject: [PATCH 16/63] chore(pipeline): updated emulators to supported minSDK SUITEDEV-35237 Co-authored-by: megamegax --- .github/workflows/on_push_workflow_new.yml | 14 ++ testWithSomeVirtualDevices.yml | 144 ++++++++++----------- 2 files changed, 86 insertions(+), 72 deletions(-) diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml index d9287000..c3d4bd0c 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/on_push_workflow_new.yml @@ -47,6 +47,10 @@ jobs: - name: Setup Gradle uses: gradle/actions/setup-gradle@v3 + with: + gradle-version: 8.6 + cache-overwrite-existing: true + gradle-home-cache-cleanup: true - name: Prepare CI run: make prepare-ci @@ -74,8 +78,18 @@ jobs: submodules: true fetch-depth: 0 # 0 indicates all history + - name: set up JDK 1.17 + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: 17 + - name: Setup Gradle uses: gradle/actions/setup-gradle@v3 + with: + gradle-version: 8.6 + cache-overwrite-existing: true + gradle-home-cache-cleanup: true - name: Prepare CI run: make prepare-ci diff --git a/testWithSomeVirtualDevices.yml b/testWithSomeVirtualDevices.yml index 0c00d813..9701fa59 100644 --- a/testWithSomeVirtualDevices.yml +++ b/testWithSomeVirtualDevices.yml @@ -3,16 +3,16 @@ core-api: app: sample-debug-androidTest.apk test: core-api-debug-androidTest.apk device: - - model: Nexus5X - version: 24 + - model: Pixel2.arm + version: 28 locale: 'en' orientation: portrait - - model: Nexus6P - version: 26 + - model: MediumPhone.arm + version: 30 locale: 'en' orientation: portrait - - model: redfin - version: 30 + - model: SmallPhone.arm + version: 33 locale: 'en' orientation: portrait @@ -21,16 +21,16 @@ core: app: sample-debug-androidTest.apk test: core-debug-androidTest.apk device: - - model: Nexus5X - version: 24 + - model: Pixel2.arm + version: 28 locale: 'en' orientation: portrait - - model: Nexus6P - version: 26 + - model: MediumPhone.arm + version: 30 locale: 'en' orientation: portrait - - model: Pixel2 - version: 30 + - model: SmallPhone.arm + version: 33 locale: 'en' orientation: portrait @@ -39,16 +39,16 @@ mobile-engage-api: app: sample-debug-androidTest.apk test: mobile-engage-api-debug-androidTest.apk device: - - model: Nexus5X - version: 24 + - model: Pixel2.arm + version: 28 locale: 'en' orientation: portrait - - model: Nexus6P - version: 26 + - model: MediumPhone.arm + version: 30 locale: 'en' orientation: portrait - - model: Pixel2 - version: 30 + - model: SmallPhone.arm + version: 33 locale: 'en' orientation: portrait @@ -57,16 +57,16 @@ mobile-engage: app: sample-debug-androidTest.apk test: mobile-engage-debug-androidTest.apk device: - - model: Nexus5X - version: 24 + - model: Pixel2.arm + version: 28 locale: 'en' orientation: portrait - - model: Nexus6P - version: 26 + - model: MediumPhone.arm + version: 30 locale: 'en' orientation: portrait - - model: Pixel2 - version: 30 + - model: SmallPhone.arm + version: 33 locale: 'en' orientation: portrait @@ -75,16 +75,16 @@ predict-api: app: sample-debug-androidTest.apk test: predict-api-debug-androidTest.apk device: - - model: Nexus5X - version: 24 + - model: Pixel2.arm + version: 28 locale: 'en' orientation: portrait - - model: Nexus6P - version: 26 + - model: MediumPhone.arm + version: 30 locale: 'en' orientation: portrait - - model: Pixel2 - version: 30 + - model: SmallPhone.arm + version: 33 locale: 'en' orientation: portrait @@ -93,16 +93,16 @@ predict: app: sample-debug-androidTest.apk test: predict-debug-androidTest.apk device: - - model: Nexus5X - version: 24 + - model: Pixel2.arm + version: 28 locale: 'en' orientation: portrait - - model: Nexus6P - version: 26 + - model: MediumPhone.arm + version: 30 locale: 'en' orientation: portrait - - model: Pixel2 - version: 30 + - model: SmallPhone.arm + version: 33 locale: 'en' orientation: portrait @@ -111,16 +111,16 @@ emarsys-sdk: app: sample-debug-androidTest.apk test: emarsys-sdk-debug-androidTest.apk device: - - model: Nexus5X - version: 24 + - model: Pixel2.arm + version: 28 locale: 'en' orientation: portrait - - model: Nexus6P - version: 26 + - model: MediumPhone.arm + version: 30 locale: 'en' orientation: portrait - - model: Pixel2 - version: 30 + - model: SmallPhone.arm + version: 33 locale: 'en' orientation: portrait @@ -129,16 +129,16 @@ emarsys: app: sample-debug-androidTest.apk test: emarsys-debug-androidTest.apk device: - - model: Nexus5X - version: 24 + - model: Pixel2.arm + version: 28 locale: 'en' orientation: portrait - - model: Nexus6P - version: 26 + - model: MediumPhone.arm + version: 30 locale: 'en' orientation: portrait - - model: Pixel2 - version: 30 + - model: SmallPhone.arm + version: 33 locale: 'en' orientation: portrait @@ -147,16 +147,16 @@ common: app: sample-debug-androidTest.apk test: common-debug-androidTest.apk device: - - model: Nexus5X - version: 24 + - model: Pixel2.arm + version: 28 locale: 'en' orientation: portrait - - model: Nexus6P - version: 26 + - model: MediumPhone.arm + version: 30 locale: 'en' orientation: portrait - - model: Pixel2 - version: 30 + - model: SmallPhone.arm + version: 33 locale: 'en' orientation: portrait @@ -165,16 +165,16 @@ emarsys-e2e-test: app: sample-debug-androidTest.apk test: emarsys-e2e-test-debug-androidTest.apk device: - - model: Nexus5X - version: 24 + - model: Pixel2.arm + version: 28 locale: 'en' orientation: portrait - - model: Nexus6P - version: 26 + - model: MediumPhone.arm + version: 30 locale: 'en' orientation: portrait - - model: Pixel2 - version: 30 + - model: SmallPhone.arm + version: 33 locale: 'en' orientation: portrait @@ -183,16 +183,16 @@ emarsys-firebase: app: sample-debug-androidTest.apk test: emarsys-firebase-debug-androidTest.apk device: - - model: Nexus5X - version: 24 + - model: Pixel2.arm + version: 28 locale: 'en' orientation: portrait - - model: Nexus6P - version: 26 + - model: MediumPhone.arm + version: 30 locale: 'en' orientation: portrait - - model: Pixel2 - version: 30 + - model: SmallPhone.arm + version: 33 locale: 'en' orientation: portrait @@ -201,15 +201,15 @@ emarsys-huawei: app: sample-debug-androidTest.apk test: emarsys-huawei-debug-androidTest.apk device: - - model: Nexus5X - version: 24 + - model: Pixel2.arm + version: 28 locale: 'en' orientation: portrait - - model: Nexus6P - version: 26 + - model: MediumPhone.arm + version: 30 locale: 'en' orientation: portrait - - model: Pixel2 - version: 30 + - model: SmallPhone.arm + version: 33 locale: 'en' orientation: portrait \ No newline at end of file From d1bb086920164b3528d9b0b72b8754ab16115cc7 Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Thu, 22 Feb 2024 21:42:12 +0100 Subject: [PATCH 17/63] chore(pipeline): modified new on_push workflow and updated devices in Makefile SUITEDEV-35237 Co-authored-by: megamegax --- .github/workflows/on_push_workflow_new.yml | 48 ++++------------------ Makefile | 8 ++-- 2 files changed, 12 insertions(+), 44 deletions(-) diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml index c3d4bd0c..733f5597 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/on_push_workflow_new.yml @@ -29,37 +29,7 @@ env: SLACK_WEBHOOK: ${{ secrets.SLACK_MOBILE_TEAM_CI_CHANNEL_WEBHOOK }} jobs: - Build: - runs-on: ubuntu-latest - name: Build job - steps: - - uses: actions/checkout@v4 - with: - ref: dev - submodules: true - fetch-depth: 0 # 0 indicates all history - - - name: set up JDK 1.17 - uses: actions/setup-java@v4 - with: - distribution: 'temurin' - java-version: 17 - - - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 - with: - gradle-version: 8.6 - cache-overwrite-existing: true - gradle-home-cache-cleanup: true - - - name: Prepare CI - run: make prepare-ci - - - name: Build with Gradle - run: make build-test - Test: - needs: Build runs-on: ubuntu-latest name: Test modules strategy: @@ -95,41 +65,39 @@ jobs: run: make prepare-ci - name: Authenticate to Google Cloud - if: matrix.platform == 'android' uses: google-github-actions/auth@v2.1.1 with: credentials_json: ${{ env.FIREBASE_SERVICE_ACCOUNT_JSON }} - name: Set up Cloud SDK - if: matrix.platform == 'android' uses: google-github-actions/setup-gcloud@v2 with: project_id: ${{ env.FIREBASE_PROJECT_ID }} - - name: create apks - run: make create-apks + - name: Build + run: make build-test - - name: test core + - name: Test core if: matrix.module == 'core' run: make test-android-firebase MODULE_NAME=core - - name: test mobile-engage + - name: Test mobile-engage if: matrix.module == 'mobile-engage' run: make test-android-firebase MODULE_NAME=mobile-engage - - name: test predict + - name: Test predict if: matrix.module == 'predict' run: make test-android-firebase MODULE_NAME=predict - - name: test emarsys-firebase + - name: Test emarsys-firebase if: matrix.module == 'emarsys-firebase' run: make test-android-firebase MODULE_NAME=emarsys-firebase - - name: test emarsys-huawei + - name: Test emarsys-huawei if: matrix.module == 'emarsys-huawei' run: make test-android-firebase MODULE_NAME=emarsys-huawei - - name: test emarsys-sdk + - name: Test emarsys-sdk if: matrix.module == 'emarsys-sdk' run: make test-android-firebase MODULE_NAME=emarsys-sdk diff --git a/Makefile b/Makefile index 1339f5c6..924a284b 100644 --- a/Makefile +++ b/Makefile @@ -42,9 +42,9 @@ test-android-firebase-emulator: check-env ## run Android Instrumented tests on e --app ./sample/build/outputs/apk/androidTest/debug/sample-debug-androidTest.apk \ --test ./$(MODULE_NAME)/build/outputs/apk/androidTest/debug/$(MODULE_NAME)-debug-androidTest.apk \ --device model=Pixel2.arm,version=28,locale=en,orientation=portrait \ - --device model=Pixel2,version=30,locale=en,orientation=portrait \ - --device model=SmallPhone,version=33,locale=en,orientation=portrait \ - --client-details matrixLabel="Android Emarsys SDK" + --device model=MediumPhone.arm,version=30,locale=en,orientation=portrait \ + --device model=SmallPhone.arm,version=33,locale=en,orientation=portrait \ + --client-details matrixLabel="Android Emarsys SDK - virtual devices" test-android-firebase: check-env ## run Android Instrumented tests on real devices on Firebase Test Lab @gcloud firebase test android run \ @@ -55,7 +55,7 @@ test-android-firebase: check-env ## run Android Instrumented tests on real devic --device model=a51,version=31,locale=en,orientation=portrait \ --device model=bluejay,version=32,locale=en,orientation=portrait \ --device model=b4q,version=33,locale=en,orientation=portrait \ - --client-details matrixLabel="Unified SDK" + --client-details matrixLabel="Unified SDK - physical devices" run-github-workflow-locally: check-env ## needs act to be installed: `brew install act` and docker running. Pass in workflow path to run @act --secret-file ./workflow.secrets -W $(WORKFLOW_PATH) --container-architecture linux/amd64 From 15d18f36166b6084b5bb7f7577af10d7aa07ab61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Thu, 22 Feb 2024 22:14:05 +0100 Subject: [PATCH 18/63] feat(firebase): add missing junit5 argument for runner SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- Makefile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Makefile b/Makefile index 924a284b..f31869f0 100644 --- a/Makefile +++ b/Makefile @@ -44,6 +44,7 @@ test-android-firebase-emulator: check-env ## run Android Instrumented tests on e --device model=Pixel2.arm,version=28,locale=en,orientation=portrait \ --device model=MediumPhone.arm,version=30,locale=en,orientation=portrait \ --device model=SmallPhone.arm,version=33,locale=en,orientation=portrait \ + --environment-variables runnerBuilder=de.mannodermaus.junit5.AndroidJUnit5Builder \ --client-details matrixLabel="Android Emarsys SDK - virtual devices" test-android-firebase: check-env ## run Android Instrumented tests on real devices on Firebase Test Lab @@ -55,6 +56,7 @@ test-android-firebase: check-env ## run Android Instrumented tests on real devic --device model=a51,version=31,locale=en,orientation=portrait \ --device model=bluejay,version=32,locale=en,orientation=portrait \ --device model=b4q,version=33,locale=en,orientation=portrait \ + --environment-variables runnerBuilder=de.mannodermaus.junit5.AndroidJUnit5Builder \ --client-details matrixLabel="Unified SDK - physical devices" run-github-workflow-locally: check-env ## needs act to be installed: `brew install act` and docker running. Pass in workflow path to run From 78d2ca546da19905264f7332eaccade114bc694b Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Fri, 23 Feb 2024 10:18:28 +0100 Subject: [PATCH 19/63] chore(pipeline): make use of android test orchestrator SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> --- .github/workflows/on_push_workflow_new.yml | 12 ++++++------ Makefile | 6 ++++-- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml index 733f5597..903d2fcb 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/on_push_workflow_new.yml @@ -79,27 +79,27 @@ jobs: - name: Test core if: matrix.module == 'core' - run: make test-android-firebase MODULE_NAME=core + run: make test-android-firebase-emulator MODULE_NAME=core - name: Test mobile-engage if: matrix.module == 'mobile-engage' - run: make test-android-firebase MODULE_NAME=mobile-engage + run: make test-android-firebase-emulator MODULE_NAME=mobile-engage - name: Test predict if: matrix.module == 'predict' - run: make test-android-firebase MODULE_NAME=predict + run: make test-android-firebase-emulator MODULE_NAME=predict - name: Test emarsys-firebase if: matrix.module == 'emarsys-firebase' - run: make test-android-firebase MODULE_NAME=emarsys-firebase + run: make test-android-firebase-emulator MODULE_NAME=emarsys-firebase - name: Test emarsys-huawei if: matrix.module == 'emarsys-huawei' - run: make test-android-firebase MODULE_NAME=emarsys-huawei + run: make test-android-firebase-emulator MODULE_NAME=emarsys-huawei - name: Test emarsys-sdk if: matrix.module == 'emarsys-sdk' - run: make test-android-firebase MODULE_NAME=emarsys-sdk + run: make test-android-firebase-emulator MODULE_NAME=emarsys-sdk # GradleLint: # name: Run lint on project diff --git a/Makefile b/Makefile index f31869f0..bcbb3853 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: check-env help build-test create-apks prepare-ci run-github-workflow-locally test-android-firebase test-android-firebase-emulator +.PHONY: check-env help build-test create-testing-apks prepare-ci run-github-workflow-locally test-android-firebase test-android-firebase-emulator .DEFAULT_GOAL := help SHELL := /bin/bash @@ -29,7 +29,7 @@ help: check-env ## Show this help build-test: check-env ## builds android tests excluding and lint @./gradlew clean assembleAndroidTest -x lint -create-apks: check-env ## create apks for testing +create-testing-apks: check-env ## create apks for testing @./gradlew assembleAndroidTest -x :sample:test prepare-ci: check-env ## setup prerequisites for pipeline @@ -45,6 +45,7 @@ test-android-firebase-emulator: check-env ## run Android Instrumented tests on e --device model=MediumPhone.arm,version=30,locale=en,orientation=portrait \ --device model=SmallPhone.arm,version=33,locale=en,orientation=portrait \ --environment-variables runnerBuilder=de.mannodermaus.junit5.AndroidJUnit5Builder \ + --environment-variables clearPackageData=true \ --client-details matrixLabel="Android Emarsys SDK - virtual devices" test-android-firebase: check-env ## run Android Instrumented tests on real devices on Firebase Test Lab @@ -57,6 +58,7 @@ test-android-firebase: check-env ## run Android Instrumented tests on real devic --device model=bluejay,version=32,locale=en,orientation=portrait \ --device model=b4q,version=33,locale=en,orientation=portrait \ --environment-variables runnerBuilder=de.mannodermaus.junit5.AndroidJUnit5Builder \ + --environment-variables clearPackageData=true \ --client-details matrixLabel="Unified SDK - physical devices" run-github-workflow-locally: check-env ## needs act to be installed: `brew install act` and docker running. Pass in workflow path to run From e2cc60faf1202ba4ed05441b6247379a5752ee7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Mon, 26 Feb 2024 10:48:27 +0100 Subject: [PATCH 20/63] test(firebase): fix tests on low API levels SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .../HardwareIdContentResolverTest.kt | 36 +++++++++---------- .../ActivityLifecycleActionRegistry.kt | 4 +-- .../contentresolver/EmarsysContentResolver.kt | 18 ++++++++++ .../hardwareid/HardwareIdContentResolver.kt | 33 ++++++++++------- .../core/handler/ConcurrentHandlerHolder.kt | 8 ++++- .../com/emarsys/di/DefaultEmarsysComponent.kt | 4 ++- gradle/libs.versions.toml | 2 +- 7 files changed, 70 insertions(+), 35 deletions(-) create mode 100644 core/src/main/java/com/emarsys/core/contentresolver/EmarsysContentResolver.kt diff --git a/core/src/androidTest/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolverTest.kt b/core/src/androidTest/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolverTest.kt index 229a8bc7..28706f70 100644 --- a/core/src/androidTest/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolverTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolverTest.kt @@ -1,17 +1,14 @@ -package com.emarsys.core.contentresolver.hardwareid - -import android.content.Context import android.database.Cursor import android.net.Uri +import com.emarsys.core.contentresolver.EmarsysContentResolver +import com.emarsys.core.contentresolver.hardwareid.HardwareIdContentResolver import com.emarsys.core.crypto.HardwareIdentificationCrypto import com.emarsys.core.database.DatabaseContract import com.emarsys.core.device.HardwareIdentification -import com.emarsys.core.provider.hardwareid.HardwareIdProviderTest import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import io.mockk.verify - import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test @@ -26,7 +23,7 @@ class HardwareIdContentResolverTest { } - private var mockContext: Context = mockk() + private var mockEmarsysContentResolver: EmarsysContentResolver = mockk() private lateinit var contentResolver: HardwareIdContentResolver private lateinit var mockHardwareIdentificationCrypto: HardwareIdentificationCrypto private lateinit var mockCursor: Cursor @@ -38,12 +35,12 @@ class HardwareIdContentResolverTest { every { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_ENCRYPTED_HARDWARE_ID) } returns 0 every { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_SALT) } returns 1 every { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_IV) } returns 2 - every { getString(0) } returns HardwareIdProviderTest.ENCRYPTED_HARDWARE_ID - every { getString(1) } returns HardwareIdProviderTest.SALT - every { getString(2) } returns HardwareIdProviderTest.IV + every { getString(0) } returns ENCRYPTED_HARDWARE_ID + every { getString(1) } returns SALT + every { getString(2) } returns IV } every { - mockContext.contentResolver.query( + mockEmarsysContentResolver.query( any(), any(), any(), @@ -66,7 +63,7 @@ class HardwareIdContentResolverTest { IV ) contentResolver = HardwareIdContentResolver( - mockContext, + mockEmarsysContentResolver, mockHardwareIdentificationCrypto, SHARED_PACKAGE_NAMES ) @@ -86,13 +83,12 @@ class HardwareIdContentResolverTest { every { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_ENCRYPTED_HARDWARE_ID) } returns 0 every { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_SALT) } returns 1 every { getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_IV) } returns 2 - every { getString(0) } returns HardwareIdProviderTest.ENCRYPTED_HARDWARE_ID - every { getString(1) } returns HardwareIdProviderTest.SALT - every { getString(2) } returns HardwareIdProviderTest.IV + every { getString(0) } returns ENCRYPTED_HARDWARE_ID + every { getString(1) } returns SALT + every { getString(2) } returns IV } - val mockContext: Context = mockk() every { - mockContext.contentResolver.query( + mockEmarsysContentResolver.query( any(), any(), any(), @@ -101,7 +97,7 @@ class HardwareIdContentResolverTest { ) } returns mockCursor val contentResolver = HardwareIdContentResolver( - mockContext, + mockEmarsysContentResolver, mockHardwareIdentificationCrypto, SHARED_PACKAGE_NAMES ) @@ -114,7 +110,11 @@ class HardwareIdContentResolverTest { @Test fun testProvideHardwareId_shouldReturnFalse_whenSharedPackageNamesIsMissing() { val contentResolver = - HardwareIdContentResolver(mockContext, mockHardwareIdentificationCrypto, null) + HardwareIdContentResolver( + mockEmarsysContentResolver, + mockHardwareIdentificationCrypto, + null + ) val result = contentResolver.resolveHardwareId() diff --git a/core/src/main/java/com/emarsys/core/activity/ActivityLifecycleActionRegistry.kt b/core/src/main/java/com/emarsys/core/activity/ActivityLifecycleActionRegistry.kt index 356d942a..2a8d6364 100644 --- a/core/src/main/java/com/emarsys/core/activity/ActivityLifecycleActionRegistry.kt +++ b/core/src/main/java/com/emarsys/core/activity/ActivityLifecycleActionRegistry.kt @@ -14,7 +14,7 @@ class ActivityLifecycleActionRegistry( val triggerOnActivityActions: MutableList = mutableListOf() fun execute(activity: Activity?, lifecycles: List) { - concurrentHandlerHolder.coreHandler.post { + concurrentHandlerHolder.post { (lifecycleActions + triggerOnActivityActions) .filter { lifecycles.contains(it.triggeringLifecycle) @@ -33,7 +33,7 @@ class ActivityLifecycleActionRegistry( } fun addTriggerOnActivityAction(activityLifecycleAction: ActivityLifecycleAction) { - concurrentHandlerHolder.coreHandler.post { + concurrentHandlerHolder.post { val currentActivity = currentActivityProvider.get() triggerOnActivityActions.add(activityLifecycleAction) if (currentActivity != null) { diff --git a/core/src/main/java/com/emarsys/core/contentresolver/EmarsysContentResolver.kt b/core/src/main/java/com/emarsys/core/contentresolver/EmarsysContentResolver.kt new file mode 100644 index 00000000..071d4f8b --- /dev/null +++ b/core/src/main/java/com/emarsys/core/contentresolver/EmarsysContentResolver.kt @@ -0,0 +1,18 @@ +package com.emarsys.core.contentresolver + +import android.content.Context +import android.database.Cursor +import android.net.Uri +import com.emarsys.core.Mockable + +@Mockable +class EmarsysContentResolver(private val context: Context) { + + fun query( + uri: Uri, + projection: Array?, selection: String?, + selectionArgs: Array?, sortOrder: String? + ): Cursor? { + return context.contentResolver.query(uri, projection, selection, selectionArgs, sortOrder) + } +} \ No newline at end of file diff --git a/core/src/main/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolver.kt b/core/src/main/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolver.kt index c92e688a..db411456 100644 --- a/core/src/main/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolver.kt +++ b/core/src/main/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolver.kt @@ -1,14 +1,16 @@ package com.emarsys.core.contentresolver.hardwareid -import android.content.Context import com.emarsys.core.Mockable +import com.emarsys.core.contentresolver.EmarsysContentResolver import com.emarsys.core.crypto.HardwareIdentificationCrypto import com.emarsys.core.database.DatabaseContract @Mockable -class HardwareIdContentResolver(private val context: Context, - private val crypto: HardwareIdentificationCrypto, - private val sharedPackageNames: List?) { +class HardwareIdContentResolver( + private val emarsysContentResolver: EmarsysContentResolver, + private val crypto: HardwareIdentificationCrypto, + private val sharedPackageNames: List? +) { fun resolveHardwareId(): String? { var index = 0 @@ -16,15 +18,22 @@ class HardwareIdContentResolver(private val context: Context, var encryptedHardwareId: String? = null if (sharedPackageNames != null) { while (encryptedHardwareId == null && index < sharedPackageNames.size) { - val cursor = context.contentResolver.query(DatabaseContract.getHardwareIdProviderUri(sharedPackageNames[index]), - arrayOf(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_ENCRYPTED_HARDWARE_ID, - DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_SALT, - DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_IV), - null, null, null) + val cursor = emarsysContentResolver.query( + DatabaseContract.getHardwareIdProviderUri(sharedPackageNames[index]), + arrayOf( + DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_ENCRYPTED_HARDWARE_ID, + DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_SALT, + DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_IV + ), + null, null, null + ) if (cursor != null && cursor.moveToFirst()) { - encryptedHardwareId = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_ENCRYPTED_HARDWARE_ID)) - val salt = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_SALT)) - val iv = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_IV)) + encryptedHardwareId = + cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_ENCRYPTED_HARDWARE_ID)) + val salt = + cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_SALT)) + val iv = + cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.HARDWARE_IDENTIFICATION_COLUMN_NAME_IV)) sharedHardwareId = crypto.decrypt(encryptedHardwareId, salt, iv) cursor.close() } diff --git a/core/src/main/java/com/emarsys/core/handler/ConcurrentHandlerHolder.kt b/core/src/main/java/com/emarsys/core/handler/ConcurrentHandlerHolder.kt index 6d079fdf..cd12ccc8 100644 --- a/core/src/main/java/com/emarsys/core/handler/ConcurrentHandlerHolder.kt +++ b/core/src/main/java/com/emarsys/core/handler/ConcurrentHandlerHolder.kt @@ -17,7 +17,13 @@ class ConcurrentHandlerHolder( val backgroundLooper = backgroundHandler.handler.looper fun post(runnable: Runnable) { - coreHandler.post(runnable) + if (coreHandler.handler.looper.thread.state != Thread.State.TERMINATED) { + coreHandler.post(runnable) + } else { + postOnMain { + coreHandler.post(runnable) + } + } } fun postOnMain(runnable: Runnable) { diff --git a/emarsys-sdk/src/main/java/com/emarsys/di/DefaultEmarsysComponent.kt b/emarsys-sdk/src/main/java/com/emarsys/di/DefaultEmarsysComponent.kt index d1226a80..92c5679f 100644 --- a/emarsys-sdk/src/main/java/com/emarsys/di/DefaultEmarsysComponent.kt +++ b/emarsys-sdk/src/main/java/com/emarsys/di/DefaultEmarsysComponent.kt @@ -32,6 +32,7 @@ import com.emarsys.core.app.AppLifecycleObserver import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.connection.ConnectionProvider import com.emarsys.core.connection.ConnectionWatchDog +import com.emarsys.core.contentresolver.EmarsysContentResolver import com.emarsys.core.contentresolver.hardwareid.HardwareIdContentResolver import com.emarsys.core.crypto.Crypto import com.emarsys.core.crypto.HardwareIdentificationCrypto @@ -452,8 +453,9 @@ open class DefaultEmarsysComponent(config: EmarsysConfig) : EmarsysComponent { override val hardwareIdProvider: HardwareIdProvider by lazy { val hardwareRepository = HardwareRepository(coreDbHelper, concurrentHandlerHolder) val hardwareIdentificationCrypto = HardwareIdentificationCrypto(config.sharedSecret, crypto) + val emarsysContentResolver = EmarsysContentResolver(config.application) val hardwareIdContentResolver = HardwareIdContentResolver( - config.application, + emarsysContentResolver, hardwareIdentificationCrypto, config.sharedPackageNames ) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index a26472e0..14463451 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -8,7 +8,7 @@ androidx-navigation-compose = "2.7.6" compose-compiler = "1.5.6" compose-plugin = "1.6.0-dev1419" android-compileSdk = "34" -android-minSdk = "28" +android-minSdk = "26" android-targetSdk = "34" androidx-activity = "1.8.2" androidx-activityCompose = "1.8.2" From eaa591e2e5e86c8454953fd65e0cf813d8343dfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Mon, 26 Feb 2024 14:50:57 +0100 Subject: [PATCH 21/63] test(geofence): fix tests on low API levels SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .../emarsys/core/util/AndroidVersionUtils.kt | 3 + .../geofence/DefaultGeofenceInternalTest.kt | 593 +++++++++++------- .../geofence/DefaultGeofenceInternal.kt | 3 +- .../mobileengage/geofence/GeofenceFilter.kt | 3 +- .../geofence/GeofencePendingIntentProvider.kt | 3 +- .../geofence/GeofenceResponseMapper.kt | 3 +- 6 files changed, 367 insertions(+), 241 deletions(-) diff --git a/core/src/main/java/com/emarsys/core/util/AndroidVersionUtils.kt b/core/src/main/java/com/emarsys/core/util/AndroidVersionUtils.kt index 4cacfed5..912a4373 100644 --- a/core/src/main/java/com/emarsys/core/util/AndroidVersionUtils.kt +++ b/core/src/main/java/com/emarsys/core/util/AndroidVersionUtils.kt @@ -9,6 +9,9 @@ object AndroidVersionUtils { get() = Build.VERSION.SDK_INT < Build.VERSION_CODES.O val isBelowQ: Boolean get() = Build.VERSION.SDK_INT < Build.VERSION_CODES.Q + + val isBelow30: Boolean + get() = Build.VERSION.SDK_INT < Build.VERSION_CODES.R val isBelowS: Boolean get() = Build.VERSION.SDK_INT < Build.VERSION_CODES.S val isBelowTiramisu: Boolean diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt index 7a018938..b38b0b72 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt @@ -16,6 +16,7 @@ import com.emarsys.core.request.RequestManager import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.Storage +import com.emarsys.core.util.AndroidVersionUtils import com.emarsys.mobileengage.api.geofence.Trigger import com.emarsys.mobileengage.api.geofence.TriggerType import com.emarsys.mobileengage.event.CacheableEventHandler @@ -25,8 +26,8 @@ import com.emarsys.mobileengage.geofence.model.GeofenceResponse import com.emarsys.mobileengage.geofence.model.TriggeringEmarsysGeofence import com.emarsys.mobileengage.notification.ActionCommandFactory import com.emarsys.mobileengage.request.MobileEngageRequestModelFactory -import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.ReflectionTestUtils +import com.emarsys.testUtil.mockito.whenever import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.Geofence import com.google.android.gms.location.GeofencingClient @@ -34,15 +35,18 @@ import com.google.android.gms.location.GeofencingRequest import com.google.android.gms.tasks.OnCompleteListener import com.google.android.gms.tasks.Task import io.kotest.matchers.shouldBe -import io.mockk.Called -import io.mockk.every -import io.mockk.mockk -import io.mockk.slot -import io.mockk.spyk -import io.mockk.verify import org.json.JSONObject import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import org.mockito.Mockito.spy +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.timeout +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions import java.util.concurrent.CountDownLatch import com.emarsys.mobileengage.api.geofence.Geofence as MEGeofence @@ -80,7 +84,6 @@ class DefaultGeofenceInternalTest { } - private lateinit var mockResponseModel: ResponseModel private lateinit var mockGeofenceRequestModel: RequestModel private lateinit var mockRequestModelFactory: MobileEngageRequestModelFactory @@ -92,7 +95,6 @@ class DefaultGeofenceInternalTest { private lateinit var mockGeofenceFilter: GeofenceFilter private lateinit var mockLocation: Location private lateinit var mockGeofencingClient: GeofencingClient - private lateinit var context: Context private lateinit var mockActionCommandFactory: ActionCommandFactory private lateinit var mockContext: Context private lateinit var mockCacheableEventHandler: CacheableEventHandler @@ -107,72 +109,91 @@ class DefaultGeofenceInternalTest { @BeforeEach fun setUp() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() - mockInitialEnterTriggerEnabledStorage = mockk(relaxed = true) { - every { get() } returns false - } - context = InstrumentationRegistry.getTargetContext() - mockResponseModel = mockk(relaxed = true) - mockGeofenceRequestModel = mockk(relaxed = true) - mockRequestModelFactory = mockk(relaxed = true) { - every { createFetchGeofenceRequest() } returns mockGeofenceRequestModel + mockInitialEnterTriggerEnabledStorage = mock() + + whenever(mockInitialEnterTriggerEnabledStorage.get()).thenReturn(false) + + mockResponseModel = mock() + mockGeofenceRequestModel = mock() + mockRequestModelFactory = mock() + whenever(mockRequestModelFactory.createFetchGeofenceRequest()).thenReturn( + mockGeofenceRequestModel + ) + + mockContext = mock() + whenever(mockContext.packageName).thenReturn( + "com.emarsys.mobileengage.test" + ) + if (!AndroidVersionUtils.isBelow30) { + whenever(mockContext.attributionTag).thenReturn("tag") } + + val intent = Intent("com.emarsys.sdk.GEOFENCE_ACTION") pendingIntent = - PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE) + PendingIntent.getBroadcast(mockContext, 0, intent, PendingIntent.FLAG_IMMUTABLE) + + mockPendingIntentProvider = mock() + whenever(mockPendingIntentProvider.providePendingIntent()).thenReturn(pendingIntent) - mockPendingIntentProvider = mockk(relaxed = true) { - every { providePendingIntent() } returns pendingIntent - } fakeRequestManager = - spyk(FakeRequestManager(FakeRequestManager.ResponseType.SUCCESS, mockResponseModel)) - mockGeofenceResponseMapper = mockk(relaxed = true) - every { + spy(FakeRequestManager(FakeRequestManager.ResponseType.SUCCESS, mockResponseModel)) + + mockGeofenceResponseMapper = mock() + whenever( mockGeofenceResponseMapper.map(any()) - } returns GeofenceResponse(listOf()) + ).thenReturn(GeofenceResponse(listOf())) + + mockPermissionChecker = mock() + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)).thenReturn( + PackageManager.PERMISSION_DENIED + ) - mockPermissionChecker = mockk(relaxed = true) { - every { checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) } returns PackageManager.PERMISSION_DENIED - } - mockLocation = mockk(relaxed = true) + mockLocation = mock() - mockTask = mockk(relaxed = true) - val onCompleteListenerSlot = slot>() - every { mockTask.addOnCompleteListener(capture(onCompleteListenerSlot)) } answers { - onCompleteListenerSlot.captured.onComplete(mockTask) - mockTask + mockTask = mock() + argumentCaptor> { + whenever(mockTask.addOnCompleteListener(capture())).thenAnswer { + firstValue.onComplete(mockTask) + mockTask + } } - mockFusedLocationProviderClient = mockk(relaxed = true) - every { + + mockFusedLocationProviderClient = mock() + whenever( mockFusedLocationProviderClient.requestLocationUpdates( any(), any() ) - } returns mockTask - every { mockFusedLocationProviderClient.lastLocation } returns FakeLocationTask(mockLocation) - mockGeofenceFilter = mockk(relaxed = true) + ).thenReturn(mockTask) - every { + whenever(mockFusedLocationProviderClient.lastLocation).thenReturn( + FakeLocationTask(mockLocation) + ) + mockGeofenceFilter = mock() + + whenever( mockGeofenceFilter.findNearestGeofences( any(), any() ) - } returns nearestGeofencesWithRefreshArea + ).thenReturn(nearestGeofencesWithRefreshArea) - mockLocation = mockk(relaxed = true) - every { mockLocation.latitude } returns 47.493165 - every { mockLocation.longitude } returns 19.058359 + mockLocation = mock() + whenever(mockLocation.latitude).thenReturn(47.493165) + whenever(mockLocation.longitude).thenReturn(19.058359) - mockGeofencingClient = mockk(relaxed = true) + mockGeofencingClient = mock() + + mockActionCommandFactory = mock() + mockCacheableEventHandler = mock() + mockEnabledStorage = mock() + + whenever(mockEnabledStorage.get()).thenReturn(true) - mockContext = mockk(relaxed = true) - mockActionCommandFactory = mockk(relaxed = true) - mockCacheableEventHandler = mockk(relaxed = true) - mockEnabledStorage = mockk(relaxed = true) { - every { get() } returns true - } geofenceInternal = DefaultGeofenceInternal( mockRequestModelFactory, @@ -182,7 +203,7 @@ class DefaultGeofenceInternalTest { mockFusedLocationProviderClient, mockGeofenceFilter, mockGeofencingClient, - context, + mockContext, mockActionCommandFactory, mockCacheableEventHandler, mockEnabledStorage, @@ -213,22 +234,22 @@ class DefaultGeofenceInternalTest { fun testFetchGeofences_shouldSendRequest_viaRequestManager_submitNow() { geofenceInternal.fetchGeofences(null) - verify { fakeRequestManager.submitNow(any(), any()) } + verify(fakeRequestManager).submitNow(any(), any()) } @Test fun testFetchGeofences_callsMapOnResponseMapper_onSuccess() { geofenceInternal.fetchGeofences(null) - verify { mockGeofenceResponseMapper.map(mockResponseModel) } + verify(mockGeofenceResponseMapper).map(mockResponseModel) } @Test fun testFetchGeofences_callsEnable_onSuccess() { - val spyGeofenceInternal = spyk(geofenceInternal) + val spyGeofenceInternal = spy(geofenceInternal) spyGeofenceInternal.fetchGeofences(null) - verify { spyGeofenceInternal.enable(null) } + verify(spyGeofenceInternal).enable(null) } @Test @@ -236,9 +257,9 @@ class DefaultGeofenceInternalTest { geofenceInternal.enable(null) if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) { - verify { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } + verify(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)) } - verify { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } + verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } @Test @@ -246,9 +267,11 @@ class DefaultGeofenceInternalTest { geofenceInternalWithMockContext.enable(null) geofenceInternalWithMockContext.enable(null) - verify(exactly = 1, timeout = 100) { - mockContext.registerReceiver(any(), any()) - } + verify( + mockContext, + timeout(100).times(1) + ).registerReceiver(any(), any()) + } @Test @@ -256,8 +279,8 @@ class DefaultGeofenceInternalTest { geofenceInternalWithMockContext.enable(null) geofenceInternalWithMockContext.disable() - verify { mockContext.unregisterReceiver(any()) } - verify { mockFusedLocationProviderClient.removeLocationUpdates(pendingIntent) } + verify(mockContext).unregisterReceiver(any()) + verify(mockFusedLocationProviderClient).removeLocationUpdates(pendingIntent) } @Test @@ -266,9 +289,11 @@ class DefaultGeofenceInternalTest { geofenceInternalWithMockContext.disable() geofenceInternalWithMockContext.disable() - verify(exactly = 1, timeout = 100) { - mockContext.unregisterReceiver(any()) - } + verify( + mockContext, + timeout(100).times(1) + ).unregisterReceiver(any()) + } @Test @@ -289,41 +314,47 @@ class DefaultGeofenceInternalTest { geofenceInternalWithMockContext.disable() geofenceInternalWithMockContext.enable(null) - verify(exactly = 2, timeout = 100) { - mockContext.registerReceiver(any(), any()) - } + verify( + mockContext, timeout(100).times(2) + ).registerReceiver(any(), any()) + } @Test fun testFetch_doNotFetch_whenGeofenceIsNotEnabled() { - every { mockEnabledStorage.get() } returns false + whenever(mockEnabledStorage.get()).thenReturn(false) geofenceInternal.fetchGeofences(null) - verify(exactly = 0) { mockRequestModelFactory.createFetchGeofenceRequest() } - verify(exactly = 0) { fakeRequestManager.submit(any(), any()) } + verify(mockRequestModelFactory, times(0)).createFetchGeofenceRequest() + verify(fakeRequestManager, times(0)).submit(any(), any()) } @Test fun testFetch_fetch_whenGeofenceIsEnabled() { - every { mockEnabledStorage.get() } returns true + whenever(mockEnabledStorage.get()).thenReturn( + true + ) geofenceInternal.fetchGeofences(null) - verify { mockRequestModelFactory.createFetchGeofenceRequest() } - verify { fakeRequestManager.submitNow(mockGeofenceRequestModel, any()) } + verify(mockRequestModelFactory).createFetchGeofenceRequest() + verify(fakeRequestManager).submitNow(eq(mockGeofenceRequestModel), any()) + } @Test fun testEnable_shouldSetEnabledStorage_andFetchIfWasDisabled() { val latch = CountDownLatch(1) var completionListenerHasBeenCalled = false - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } returns - PackageManager.PERMISSION_GRANTED - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) - every { mockEnabledStorage.get() } returns false andThen true + whenever(mockEnabledStorage.get()).thenReturn(false).thenReturn(true) geofenceInternal.enable { it shouldBe null @@ -333,79 +364,91 @@ class DefaultGeofenceInternalTest { latch.await() completionListenerHasBeenCalled shouldBe true - verify(timeout = 100) { mockEnabledStorage.set(true) } - verify { mockRequestModelFactory.createFetchGeofenceRequest() } + verify(mockEnabledStorage, timeout(100)).set(true) + verify(mockRequestModelFactory).createFetchGeofenceRequest() } + @Test fun testDisable_shouldClearEnabledStorage() { geofenceInternalWithMockContext.enable(null) geofenceInternalWithMockContext.disable() - verify { mockEnabledStorage.set(false) } + verify(mockEnabledStorage).set(false) + } @Test fun testIsEnabled_shouldReturnTrue_whenGeofenceIsEnabled() { - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) - every { mockEnabledStorage.get() } returns false andThen false andThen true + whenever(mockEnabledStorage.get()).thenReturn(false).thenReturn(false).thenReturn(true) geofenceInternal.isEnabled() shouldBe false geofenceInternal.enable(null) - verify(exactly = 1) { mockEnabledStorage.set(true) } + verify(mockEnabledStorage, timeout(100)).set(true) geofenceInternal.isEnabled() shouldBe true } @Test fun testIsEnabled_shouldReturnFalse_whenGeofenceIsDisabled() { - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) - every { mockEnabledStorage.get() } returns true andThen true andThen false + whenever(mockEnabledStorage.get()).thenReturn(true).thenReturn(true).thenReturn(false) geofenceInternal.isEnabled() shouldBe true geofenceInternal.disable() - verify(exactly = 1) { mockEnabledStorage.set(false) } + verify(mockEnabledStorage, timeout(100)).set(false) geofenceInternal.isEnabled() shouldBe false } @Test fun testEnable_fetchLastKnownLocation_fromLocationManager_whenPermissionGranted() { - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever( + mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) + ).thenReturn( + PackageManager.PERMISSION_GRANTED + ) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) geofenceInternal.enable(null) if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) { - verify { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } + verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) + verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) + verify(mockFusedLocationProviderClient.lastLocation) } - verify { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } - verify { mockFusedLocationProviderClient.lastLocation } } @Test fun testEnable_fetchLastKnownLocation_fromLocationManager_whenPermissionGranted_withCompletionListener() { val latch = CountDownLatch(1) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) var completionListenerHasBeenCalled = false @@ -417,23 +460,28 @@ class DefaultGeofenceInternalTest { latch.await() completionListenerHasBeenCalled shouldBe true if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) { - verify { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } + verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } - verify { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } - verify { mockFusedLocationProviderClient.lastLocation } + + verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) + + verify(mockFusedLocationProviderClient).lastLocation } @Test fun testEnable_returnDoNoTReturn_PermissionForLocationException_whenFineLocationPermissionDenied_andCoarseLocationGranted() { val latch = CountDownLatch(1) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } returns - PackageManager.PERMISSION_DENIED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)).thenReturn( + PackageManager.PERMISSION_DENIED + ) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) var completionListenerHasBeenCalled = false @@ -445,29 +493,36 @@ class DefaultGeofenceInternalTest { latch.await() completionListenerHasBeenCalled shouldBe true if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) { - verify { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } + verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } - verify { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } - verify { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) } - verify { mockFusedLocationProviderClient.lastLocation } + + verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) + + verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) + verify(mockFusedLocationProviderClient).lastLocation } @Test fun testEnable_returnNoPermissionForLocationException_whenFineLocationPermissionDenied() { val geofenceResponse = GeofenceResponse(listOf(), 0.0) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } returns - PackageManager.PERMISSION_DENIED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)).thenReturn( + PackageManager.PERMISSION_DENIED + ) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) - every { mockFusedLocationProviderClient.lastLocation } returns - FakeLocationTask( - mockLocation - ) + whenever(mockFusedLocationProviderClient.lastLocation).thenReturn( + FakeLocationTask( + mockLocation + ) + ) - every { mockGeofenceResponseMapper.map(any()) } returns geofenceResponse + whenever(mockGeofenceResponseMapper.map(any())).thenReturn( + geofenceResponse + ) var completionListenerHasBeenCalled = false geofenceInternal.enable { @@ -478,29 +533,40 @@ class DefaultGeofenceInternalTest { completionListenerHasBeenCalled shouldBe true if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - verify { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } + verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } - verify { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } - verify { mockFusedLocationProviderClient wasNot Called } - verify { mockGeofenceFilter wasNot Called } + + verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) + + verifyNoInteractions( + mockFusedLocationProviderClient + ) + + verifyNoInteractions(mockGeofenceFilter) } + @Test fun testEnable_returnNoPermissionForLocationException_whenBackgroundLocationPermissionDenied() { val geofenceResponse = GeofenceResponse(listOf(), 0.0) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } returns - PackageManager.PERMISSION_DENIED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)).thenReturn( + PackageManager.PERMISSION_DENIED + ) - every { mockFusedLocationProviderClient.lastLocation } returns - FakeLocationTask( - mockLocation - ) + whenever(mockFusedLocationProviderClient.lastLocation).thenReturn( + FakeLocationTask( + mockLocation + ) + ) - every { mockGeofenceResponseMapper.map(any()) } returns geofenceResponse + whenever(mockGeofenceResponseMapper.map(any())).thenReturn( + geofenceResponse + ) var completionListenerHasBeenCalled = false geofenceInternal.enable { @@ -513,29 +579,35 @@ class DefaultGeofenceInternalTest { completionListenerHasBeenCalled shouldBe true if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - verify { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } - verify { mockFusedLocationProviderClient wasNot Called } - verify { mockGeofenceFilter wasNot Called } + verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) + verifyNoInteractions(mockFusedLocationProviderClient) + verifyNoInteractions(mockGeofenceFilter) } - verify { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } + + verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } @Test fun testEnable_returnNoPermissionForLocationException_whenPermissionsDenied() { val geofenceResponse = GeofenceResponse(listOf(), 0.0) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } returns - PackageManager.PERMISSION_DENIED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)).thenReturn( + PackageManager.PERMISSION_DENIED + ) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } returns - PackageManager.PERMISSION_DENIED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)).thenReturn( + PackageManager.PERMISSION_DENIED + ) - every { mockFusedLocationProviderClient.lastLocation } returns - FakeLocationTask( - mockLocation - ) + whenever(mockFusedLocationProviderClient.lastLocation).thenReturn( + FakeLocationTask( + mockLocation + ) + ) - every { mockGeofenceResponseMapper.map(any()) } returns geofenceResponse + whenever(mockGeofenceResponseMapper.map(any())).thenReturn( + geofenceResponse + ) var completionListenerHasBeenCalled = false geofenceInternal.enable { @@ -550,74 +622,93 @@ class DefaultGeofenceInternalTest { completionListenerHasBeenCalled shouldBe true if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - verify { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } + verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } - verify { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } - verify { mockFusedLocationProviderClient wasNot Called } - verify { mockGeofenceFilter wasNot Called } + verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) + + verifyNoInteractions( + mockFusedLocationProviderClient + ) + + verifyNoInteractions(mockGeofenceFilter) + } @Test fun testEnable_registersGeofencesWithAdditionalRefreshArea() { val geofenceResponse = GeofenceResponse(listOf(), 0.3) - every { mockGeofenceResponseMapper.map(any()) } returns geofenceResponse + whenever(mockGeofenceResponseMapper.map(any())).thenReturn( + geofenceResponse + ) - val spyGeofenceInternal: GeofenceInternal = spyk(geofenceInternal) + val spyGeofenceInternal: GeofenceInternal = spy(geofenceInternal) spyGeofenceInternal.fetchGeofences(null) - every { mockGeofenceFilter.findNearestGeofences(any(), any()) } returns - nearestGeofencesWithoutRefreshArea + whenever(mockGeofenceFilter.findNearestGeofences(any(), any())).thenReturn( + nearestGeofencesWithoutRefreshArea + ) - val currentLocation = (Location(LocationManager.GPS_PROVIDER).apply { + val currentLocation = Location(LocationManager.GPS_PROVIDER).apply { this.latitude = 47.493160 this.longitude = 19.058355 - }) - - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + } - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) - every { mockFusedLocationProviderClient.lastLocation } returns - FakeLocationTask( - currentLocation - ) + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) - val meGeofenceSlot = slot>() - every { spyGeofenceInternal.registerGeofences(capture(meGeofenceSlot)) } answers {} + whenever(mockFusedLocationProviderClient.lastLocation).thenReturn( + FakeLocationTask( + currentLocation + ) + ) spyGeofenceInternal.enable(null) - meGeofenceSlot.captured.size shouldBe 4 - meGeofenceSlot.captured[3].toString() shouldBe refreshArea.toString() + + argumentCaptor> { + verify(spyGeofenceInternal, times(2)).registerGeofences(capture()) + + lastValue.size shouldBe 4 + lastValue[3].toString() shouldBe refreshArea.toString() + } } @Test fun testEnable_shouldNotCrash_registersGeofencesWhenRefreshRadiusWouldBeNegative() { val geofenceResponse = GeofenceResponse(listOf(), 1.0) - every { mockGeofenceResponseMapper.map(any()) } returns geofenceResponse + whenever(mockGeofenceResponseMapper.map(any())).thenReturn( + geofenceResponse + ) - val spyGeofenceInternal: GeofenceInternal = spyk(geofenceInternal) + val spyGeofenceInternal: GeofenceInternal = spy(geofenceInternal) spyGeofenceInternal.fetchGeofences(null) - every { mockGeofenceFilter.findNearestGeofences(any(), any()) } returns - listOf(nearestGeofencesWithoutRefreshArea[0]) + whenever(mockGeofenceFilter.findNearestGeofences(any(), any())).thenReturn( + listOf(nearestGeofencesWithoutRefreshArea[0]) + ) val currentLocation = (Location(LocationManager.GPS_PROVIDER).apply { this.latitude = 47.493160 this.longitude = 19.058355 }) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) - every { mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } returns - PackageManager.PERMISSION_GRANTED + whenever(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)).thenReturn( + PackageManager.PERMISSION_GRANTED + ) - every { mockFusedLocationProviderClient.lastLocation } returns - FakeLocationTask(currentLocation) + whenever(mockFusedLocationProviderClient.lastLocation).thenReturn( + FakeLocationTask(currentLocation) + ) spyGeofenceInternal.enable(null) } @@ -629,54 +720,62 @@ class DefaultGeofenceInternalTest { refreshArea ) val geofencingRequest = - GeofencingRequest.Builder().addGeofences(geofencesToTest).setInitialTrigger(0).build() - - val geofencingRequestSlot = slot() - every { - mockGeofencingClient.addGeofences( - capture(geofencingRequestSlot), - any() + GeofencingRequest.Builder().addGeofences(geofencesToTest).setInitialTrigger(0) + .build() + argumentCaptor { + whenever( + mockGeofencingClient.addGeofences( + capture(), + any() + ) + ).thenReturn( + mockTask ) - } returns mockTask - geofenceInternal.registerGeofences(nearestGeofencesWithoutRefreshArea + refreshArea) + geofenceInternal.registerGeofences(nearestGeofencesWithoutRefreshArea + refreshArea) - geofencingRequestSlot.captured.initialTrigger shouldBe geofencingRequest.initialTrigger - geofencingRequestSlot.captured.geofences.forEachIndexed { index, geofence -> - geofence.requestId shouldBe geofencingRequest.geofences[index].requestId + firstValue.initialTrigger shouldBe geofencingRequest.initialTrigger + firstValue.geofences.forEachIndexed { index, geofence -> + geofence.requestId shouldBe geofencingRequest.geofences[index].requestId + } } + } @Test fun testRegisterGeofences_geofencingRequest_shouldIncludeInitialEnterTrigger() { val geofencesToTest = - nearestGeofencesWithoutRefreshArea.map { createGeofence(it) } + createGeofence(Companion.refreshArea) - val geofencingRequest = GeofencingRequest.Builder().addGeofences(geofencesToTest).build() - - val geofencingRequestSlot = slot() - every { - mockGeofencingClient.addGeofences( - capture(geofencingRequestSlot), - any() + nearestGeofencesWithoutRefreshArea.map { createGeofence(it) } + createGeofence( + Companion.refreshArea + ) + val geofencingRequest = + GeofencingRequest.Builder().addGeofences(geofencesToTest).build() + argumentCaptor { + whenever( + mockGeofencingClient.addGeofences( + capture(), + any() + ) + ).thenReturn( + mockTask ) - } returns mockTask - - geofenceInternal.setInitialEnterTriggerEnabled(true) - geofenceInternal.registerGeofences(nearestGeofencesWithoutRefreshArea + refreshArea) - verify { mockInitialEnterTriggerEnabledStorage.set(true) } + geofenceInternal.setInitialEnterTriggerEnabled(true) + geofenceInternal.registerGeofences(nearestGeofencesWithoutRefreshArea + refreshArea) - geofencingRequestSlot.captured.initialTrigger shouldBe GeofencingRequest.INITIAL_TRIGGER_ENTER - geofencingRequestSlot.captured.geofences.forEachIndexed { index, geofence -> - geofence.requestId shouldBe geofencingRequest.geofences[index].requestId + verify(mockInitialEnterTriggerEnabledStorage).set(true) + firstValue.initialTrigger shouldBe GeofencingRequest.INITIAL_TRIGGER_ENTER + firstValue.geofences.forEachIndexed { index, geofence -> + geofence.requestId shouldBe geofencingRequest.geofences[index].requestId + } } } @Test fun testOnGeofenceTriggered() { val latch = CountDownLatch(1) - val mockAction: Runnable = mockk(relaxed = true) + val mockAction: Runnable = mock() val appEventAction = JSONObject( """ { @@ -708,8 +807,10 @@ class DefaultGeofenceInternalTest { MEGeofence("geofenceId5", 47.492292, 19.056440, 10.0, null, listOf(trigger)) ) ReflectionTestUtils.setInstanceField(geofenceInternal, "nearestGeofences", allGeofences) - every { mockAction.run() } answers { latch.countDown() } - every { mockActionCommandFactory.createActionCommand(appEventAction) } returns mockAction + whenever(mockAction.run()).thenAnswer { latch.countDown() } + whenever(mockActionCommandFactory.createActionCommand(appEventAction)).thenReturn( + mockAction + ) geofenceInternal.onGeofenceTriggered( listOf( TriggeringEmarsysGeofence( @@ -718,16 +819,23 @@ class DefaultGeofenceInternalTest { ) ) ) - verify(exactly = 1) { mockActionCommandFactory.createActionCommand(appEventAction) } + + verify( + mockActionCommandFactory, times(1) + ).createActionCommand( + appEventAction + ) + latch.await() - verify { mockAction.run() } + verify(mockAction).run() } + @Test fun testOnGeofenceTriggered_onRefreshArea_recalculateGeofences() { - val spyGeofenceInternal = spyk(geofenceInternal) + val spyGeofenceInternal = spy(geofenceInternal) val latch = CountDownLatch(1) - val mockAction: Runnable = mockk(relaxed = true) + val mockAction: Runnable = mock() val appEventAction = JSONObject( """ { @@ -802,21 +910,23 @@ class DefaultGeofenceInternalTest { "geofenceResponse", geofenceResponse ) - every { mockAction.run() } answers { latch.countDown() } - every { mockActionCommandFactory.createActionCommand(appEventAction) } returns mockAction + whenever(mockAction.run()).thenAnswer { latch.countDown() } + whenever(mockActionCommandFactory.createActionCommand(appEventAction)).thenReturn( + mockAction + ) - every { mockFusedLocationProviderClient.lastLocation } returns - FakeLocationTask(currentLocation) + whenever(mockFusedLocationProviderClient.lastLocation).thenReturn( + FakeLocationTask(currentLocation) + ) - every { + whenever( mockGeofenceFilter.findNearestGeofences( currentLocation, geofenceResponse ) - } returns nearestGeofences2 - - val meGeofenceSlot = slot>() - every { spyGeofenceInternal.registerGeofences(capture(meGeofenceSlot)) } answers {} + ).thenReturn( + nearestGeofences2 + ) spyGeofenceInternal.onGeofenceTriggered( listOf( @@ -827,15 +937,24 @@ class DefaultGeofenceInternalTest { ) ) - verify { mockActionCommandFactory.createActionCommand(appEventAction) } + argumentCaptor> { + verify(spyGeofenceInternal).registerGeofences(capture()) + verify(mockActionCommandFactory).createActionCommand(appEventAction) - latch.await() + latch.await() + + verify(mockAction).run() - verify { mockAction.run() } - verify { mockGeofenceFilter.findNearestGeofences(currentLocation, geofenceResponse) } + verify( + mockGeofenceFilter + ).findNearestGeofences( + currentLocation, + geofenceResponse + ) - meGeofenceSlot.captured.size shouldBe 2 - meGeofenceSlot.captured[1].toString() shouldBe refreshArea.toString() + firstValue.size shouldBe 2 + firstValue[1].toString() shouldBe refreshArea.toString() + } } private fun createGeofence(geofence: MEGeofence): Geofence { diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternal.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternal.kt index c96b961e..c00bfee9 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternal.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternal.kt @@ -8,6 +8,7 @@ import android.content.pm.PackageManager import android.location.Location import androidx.annotation.RequiresPermission import com.emarsys.core.CoreCompletionHandler +import com.emarsys.core.Mockable import com.emarsys.core.api.MissingPermissionException import com.emarsys.core.api.result.CompletionListener import com.emarsys.core.handler.ConcurrentHandlerHolder @@ -33,7 +34,7 @@ import org.json.JSONObject import kotlin.math.abs import com.emarsys.mobileengage.api.geofence.Geofence as MEGeofence - +@Mockable class DefaultGeofenceInternal( private val requestModelFactory: MobileEngageRequestModelFactory, private val requestManager: RequestManager, diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceFilter.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceFilter.kt index 0b9ed6f8..900d54f1 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceFilter.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceFilter.kt @@ -2,10 +2,11 @@ package com.emarsys.mobileengage.geofence import android.location.Location import android.location.LocationManager +import com.emarsys.core.Mockable import com.emarsys.mobileengage.api.geofence.Geofence import com.emarsys.mobileengage.geofence.model.GeofenceResponse - +@Mockable class GeofenceFilter(private val limit: Int) { fun findNearestGeofences(currentLocation: Location, geofenceResponse: GeofenceResponse): List { val geofences = geofenceResponse.geofenceGroups diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProvider.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProvider.kt index 47c8cb3c..dc70d19b 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProvider.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProvider.kt @@ -3,9 +3,10 @@ package com.emarsys.mobileengage.geofence import android.app.PendingIntent import android.content.Context import android.content.Intent +import com.emarsys.core.Mockable import com.emarsys.core.util.AndroidVersionUtils - +@Mockable class GeofencePendingIntentProvider(private val context: Context) { fun providePendingIntent(): PendingIntent { val intent = Intent("com.emarsys.sdk.GEOFENCE_ACTION") diff --git a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapper.kt b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapper.kt index b1dce214..45492567 100644 --- a/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapper.kt +++ b/mobile-engage/src/main/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapper.kt @@ -1,6 +1,7 @@ package com.emarsys.mobileengage.geofence import com.emarsys.core.Mapper +import com.emarsys.core.Mockable import com.emarsys.core.response.ResponseModel import com.emarsys.core.util.log.Logger import com.emarsys.core.util.log.entry.CrashLog @@ -14,7 +15,7 @@ import org.json.JSONException import org.json.JSONObject @Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") - +@Mockable class GeofenceResponseMapper : Mapper { override fun map(responseModel: ResponseModel): GeofenceResponse { From 3e4087f0aed98708ba1b434f1287cf61382a4fa1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Tue, 27 Feb 2024 11:04:41 +0100 Subject: [PATCH 22/63] test(junit4): revert to junit4 using kotest everywhere possible SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- Makefile | 14 +- common/build.gradle.kts | 12 +- .../common/feature/InnerFeatureTest.kt | 4 +- core-api/build.gradle.kts | 12 +- .../java/com/emarsys/core/api/ApiTest.kt | 4 +- core/build.gradle.kts | 13 +- .../core/DefaultCoreCompletionHandlerTest.kt | 7 +- .../java/com/emarsys/core/DeviceInfoTest.kt | 10 +- .../ActivityLifecycleActionRegistryTest.kt | 7 +- .../activity/ActivityLifecycleWatchdogTest.kt | 9 +- .../activity/CurrentActivityWatchdogTest.kt | 7 +- .../com/emarsys/core/api/AsyncProxyTest.kt | 9 +- .../emarsys/core/api/LogExceptionProxyTest.kt | 10 +- .../core/app/AppLifecycleObserverTest.kt | 9 +- .../ConcurrentHandlerHolderFactoryTest.kt | 10 +- .../core/concurrency/CoreHandlerTest.kt | 10 +- .../core/connection/ConnectionProviderTest.kt | 7 +- .../core/connection/ConnectionWatchDogTest.kt | 7 +- .../ConnectivityChangeReceiverTest.kt | 10 +- ...ty_getConnectionState_ParameterizedTest.kt | 4 +- .../HardwareIdContentResolverTest.kt | 7 +- .../com/emarsys/core/crypto/CryptoTest.kt | 12 +- .../HardwareIdentificationCryptoTest.kt | 10 +- .../DelegatingCoreSQLiteDatabaseTest.kt | 16 +- ...abase_registerTrigger_parameterizedTest.kt | 217 +++++++++--------- ...base_triggerRecursion_parameterizedTest.kt | 91 ++++---- .../database/helper/AbstractDbHelperTest.kt | 7 +- .../core/database/helper/CoreDbHelperTest.kt | 11 +- .../AbstractSqliteRepositoryTest.kt | 7 +- .../specification/EverythingTest.kt | 8 +- .../specification/FilterByRequestIdsTest.kt | 8 +- .../QueryLatestRequestModelTest.kt | 8 +- .../core/device/LanguageProviderTest.kt | 7 +- .../endpoint/ServiceEndpointProviderTest.kt | 10 +- .../emarsys/core/fake/FakeRequestTask.java | 2 + .../core/feature/FeatureRegistryTest.kt | 10 +- .../NotificationManagerHelperTest.kt | 9 +- .../activity/CurrentActivityProviderTest.kt | 7 +- .../hardwareid/HardwareIdProviderTest.kt | 7 +- .../provider/random/RandomProviderTest.kt | 6 +- .../timestamp/TimestampProviderTest.kt | 4 +- .../core/provider/uuid/UUIDProviderTest.kt | 4 +- .../provider/version/VersionProviderTest.kt | 8 +- .../core/request/RequestManagerDennaTest.kt | 10 +- .../core/request/RequestManagerOfflineTest.kt | 11 +- .../core/request/RequestManagerTest.kt | 61 +++-- .../emarsys/core/request/RequestTaskTest.kt | 13 +- .../emarsys/core/request/RestClientTest.kt | 9 +- ...CompletionHandlerMiddlewareProviderTest.kt | 8 +- .../model/CompositeRequestModelTest.kt | 7 +- .../model/RequestModelRepositoryTest.kt | 17 +- .../core/request/model/RequestModelTest.kt | 10 +- .../specification/FilterByUrlPatternTest.kt | 8 +- .../core/resource/MetaDataReaderTest.kt | 7 +- .../response/AbstractResponseHandlerTest.kt | 7 +- .../response/ResponseHandlersProcessorTest.kt | 9 +- .../core/response/ResponseModelTest.kt | 12 +- .../core/shard/ShardModelRepositoryTest.kt | 14 +- .../com/emarsys/core/shard/ShardModelTest.kt | 7 +- .../specification/FilterByShardIdsTest.kt | 8 +- .../specification/FilterByShardTypeTest.kt | 8 +- .../core/storage/AbstractStorageTest.kt | 9 +- .../core/storage/BooleanStorageTest.kt | 7 +- .../core/storage/CoreStorageKeyTest.kt | 4 +- .../core/storage/DefaultKeyValueStoreTest.kt | 34 ++- .../SecureSharedPreferencesProviderTest.kt | 8 +- .../emarsys/core/storage/StringStorageTest.kt | 7 +- .../core/testUtil/RequestModelTestUtils.kt | 4 +- .../java/com/emarsys/core/util/AssertTest.kt | 6 +- .../com/emarsys/core/util/DatabaseUtilTest.kt | 4 +- .../core/util/ExceptionExtensionsKtTest.kt | 4 +- .../emarsys/core/util/FileDownloaderTest.kt | 37 +-- .../util/HeaderUtilsInstrumentationTest.kt | 4 +- .../com/emarsys/core/util/ImageUtilsTest.kt | 27 ++- .../com/emarsys/core/util/JsonUtilsTest.kt | 8 +- .../emarsys/core/util/MapExtensionsKtTest.kt | 7 +- .../core/util/RequestModelUtilsTest.kt | 5 +- .../core/util/SerializationUtilsTest.kt | 4 +- .../com/emarsys/core/util/SystemUtilsTest.kt | 5 +- .../emarsys/core/util/TimestampUtilsTest.kt | 7 +- .../util/batch/BatchingShardTriggerTest.kt | 7 +- .../core/util/batch/ListChunkerTest.kt | 10 +- .../core/util/log/LogShardListMergerTest.kt | 10 +- .../com/emarsys/core/util/log/LoggerTest.kt | 11 +- .../core/util/log/entry/AppEventLogTest.kt | 5 +- .../core/util/log/entry/CrashLogTest.kt | 8 +- .../core/util/log/entry/InAppLogTest.kt | 6 +- .../core/util/log/entry/LogEntryKtTest.kt | 4 +- .../util/log/entry/MethodNotAlllowedTest.kt | 5 +- .../util/log/entry/OfflineQueueSizeTest.kt | 5 +- .../core/util/log/entry/RequestLogTest.kt | 9 +- .../core/util/log/entry/StatusLogTest.kt | 15 +- .../util/predicate/ListSizeAtLeastTest.kt | 8 +- .../core/validate/JsonObjectValidatorTest.kt | 10 +- .../CoreCompletionHandlerMiddlewareTest.kt | 7 +- .../emarsys/core/worker/DefaultWorkerTest.kt | 7 +- emarsys-e2e-test/build.gradle.kts | 12 +- .../java/com/emarsys/EmarsysE2ETests.kt | 48 ++-- emarsys-firebase/build.gradle.kts | 12 +- .../EmarsysFirebaseMessagingServiceTest.kt | 12 +- ...marsysFirebaseMessagingServiceUtilsTest.kt | 7 +- emarsys-huawei/build.gradle.kts | 12 +- .../EmarsysHuaweiMessagingServiceTest.kt | 11 +- .../EmarsysHuaweiMessagingServiceUtilsTest.kt | 7 +- emarsys-sdk/build.gradle.kts | 12 +- .../emarsys/DefaultInboxIntegrationTest.kt | 32 +-- .../java/com/emarsys/EmarsysTest.kt | 52 ++++- .../androidTest/java/com/emarsys/InAppTest.kt | 10 +- .../InappNotificationIntegrationTest.kt | 18 +- .../emarsys/MobileEngageIntegrationTest.kt | 58 +++-- ...ngageRefreshContactTokenIntegrationTest.kt | 29 +-- .../com/emarsys/PredictIntegrationTest.kt | 111 +++++---- .../java/com/emarsys/PredictTest.kt | 10 +- .../androidTest/java/com/emarsys/PushTest.kt | 10 +- .../emarsys/RemoteConfigIntegrationTest.kt | 28 ++- .../com/emarsys/config/ConfigLoaderTest.kt | 7 +- .../java/com/emarsys/config/ConfigTest.kt | 24 +- .../com/emarsys/config/EmarsysConfigTest.kt | 11 +- .../java/com/emarsys/deeplink/DeepLinkTest.kt | 11 +- .../di/EmarsysDependencyInjectionTest.kt | 7 +- .../emarsys/eventservice/EventServiceTest.kt | 11 +- .../java/com/emarsys/geofence/GeofenceTest.kt | 11 +- .../emarsys/inapp/ui/InlineInAppViewTest.kt | 11 +- .../com/emarsys/inbox/MessageInboxTest.kt | 11 +- .../emarsys/mobileengage/MobileEngageTest.kt | 12 +- .../mapper/RemoteMessageMapperFactoryTest.kt | 7 +- .../oneventaction/OnEventActionTest.kt | 11 +- .../emarsys/predict/PredictRestrictedTest.kt | 12 +- ...rdwareIdentificationContentProviderTest.kt | 7 +- emarsys/build.gradle.kts | 12 +- .../emarsys/EmarsysRequestModelFactoryTest.kt | 10 +- .../config/DefaultConfigInternalTest.kt | 11 +- .../config/FetchRemoteConfigActionTest.kt | 12 +- .../config/RemoteConfigResponseMapperTest.kt | 10 +- gradle/libs.versions.toml | 1 + mobile-engage-api/build.gradle.kts | 12 +- .../com/emarsys/mobileengage/api/MEApiTest.kt | 4 +- mobile-engage/build.gradle.kts | 12 +- .../DefaultMobileEngageInternalTest.kt | 8 +- .../MobileEngageRequestContextTest.kt | 7 +- .../DefaultClientServiceInternalTest.kt | 10 +- .../deeplink/DeepLinkActionTest.kt | 12 +- .../deeplink/DefaultDeepLinkInternalTest.kt | 7 +- .../device/DeviceInfoStartActionTest.kt | 11 +- .../event/CacheableEventHandlerTest.kt | 7 +- .../event/DefaultEventServiceInternalTest.kt | 10 +- .../geofence/DefaultGeofenceInternalTest.kt | 7 +- .../geofence/FetchGeofencesActionTest.kt | 13 +- .../geofence/GeofenceFilterTest.kt | 19 +- .../GeofencePendingIntentProviderTest.kt | 7 +- .../geofence/GeofenceResponseMapperTest.kt | 10 +- .../mobileengage/iam/AppStartActionTest.kt | 10 +- .../iam/InAppEventHandlerInternalTest.kt | 8 +- .../mobileengage/iam/InAppInternalTest.kt | 8 +- .../iam/OverlayInAppPresenterTest.kt | 7 +- .../mobileengage/iam/PushToInAppActionTest.kt | 8 +- .../iam/SaveDisplayedIamActionTest.kt | 11 +- .../iam/dialog/IamDialogProviderTest.kt | 12 +- .../mobileengage/iam/dialog/IamDialogTest.kt | 11 +- .../action/SendDisplayedIamActionTest.kt | 11 +- .../iam/jsbridge/IamJsBridgeFactoryTest.kt | 4 +- .../iam/jsbridge/IamJsBridgeTest.kt | 11 +- .../jsbridge/JSCommandFactoryProviderTest.kt | 4 +- .../iam/jsbridge/JSCommandFactoryTest.kt | 11 +- .../iam/model/IamConversionUtilsTest.kt | 7 +- .../ButtonClickedRepositoryTest.kt | 7 +- .../DisplayedIamRepositoryTest.kt | 7 +- .../RequestRepositoryProxyTest.kt | 11 +- .../specification/FilterByCampaignIdTest.kt | 8 +- .../iam/webview/IamWebViewClientTest.kt | 7 +- .../iam/webview/IamWebViewFactoryTest.kt | 13 +- .../iam/webview/IamWebViewTest.kt | 11 +- .../inbox/DefaultMessageInboxInternalTest.kt | 7 +- .../inbox/MessageInboxResponseMapperTest.kt | 7 +- .../notification/ActionCommandFactoryTest.kt | 11 +- ...ityCommandLifecycleCallbacksFactoryTest.kt | 4 +- ...chActivityCommandLifecycleCallbacksTest.kt | 12 +- .../NotificationCommandFactoryTest.kt | 11 +- .../command/AppEventCommandTest.kt | 11 +- .../command/CompositeCommandTest.kt | 4 +- .../command/CustomEventCommandTest.kt | 7 +- .../command/DismissNotificationCommandTest.kt | 4 +- .../command/LaunchApplicationCommandTest.kt | 11 +- .../NotificationInformationCommandTest.kt | 20 +- .../command/OpenExternalUrlCommandTest.kt | 4 +- .../PreloadedInappHandlerCommandTest.kt | 11 +- ...ilentNotificationInformationCommandTest.kt | 20 +- .../command/TrackActionClickCommandTest.kt | 4 +- .../command/TrackMessageOpenCommandTest.kt | 4 +- .../push/DefaultPushInternalTest.kt | 7 +- .../push/DefaultPushTokenProviderTest.kt | 6 +- ...ionHandlerRefreshTokenProxyProviderTest.kt | 10 +- ...eCompletionHandlerRefreshTokenProxyTest.kt | 11 +- .../MobileEngageRequestModelFactoryTest.kt | 10 +- .../mapper/ContactTokenHeaderMapperTest.kt | 10 +- .../mapper/DefaultRequestHeaderMapperTest.kt | 10 +- .../DeviceEventStateRequestMapperTest.kt | 7 +- .../mapper/MobileEngageHeaderMapperTest.kt | 10 +- .../mapper/OpenIdTokenRequestMapperTest.kt | 10 +- .../ClientInfoResponseHandlerTest.kt | 13 +- .../DeviceEventStateResponseHandlerTest.kt | 7 +- .../InAppCleanUpResponseHandlerTest.kt | 10 +- .../InAppCleanUpResponseHandlerV4Test.kt | 7 +- .../InAppMessageResponseHandlerTest.kt | 11 +- ...ileEngageClientStateResponseHandlerTest.kt | 13 +- .../MobileEngageTokenResponseHandlerTest.kt | 10 +- .../OnEventActionResponseHandlerTest.kt | 11 +- .../mobileengage/service/IntentUtilsTest.kt | 7 +- .../service/MessagingServiceUtilsTest.kt | 13 +- .../service/NotificationActionUtilsTest.kt | 12 +- .../service/RemoteMessageMapperV1Test.kt | 11 +- .../service/RemoteMessageMapperV2Test.kt | 11 +- .../session/MobileEngageSessionTest.kt | 8 +- .../storage/MobileEngageStorageKeyTest.kt | 4 +- .../util/RequestModelHelperTest.kt | 10 +- .../util/RequestPayloadUtilsTest.kt | 9 +- predict-api/build.gradle.kts | 12 +- .../api/model/RecommendationFilterTest.kt | 7 +- .../api/model/RecommendationLogicTest.kt | 4 +- predict/build.gradle.kts | 12 +- .../predict/DefaultPredictInternalTest.kt | 7 +- .../predict/PredictResponseMapperTest.kt | 10 +- .../PredictRequestModelBuilderProviderTest.kt | 10 +- .../request/PredictHeaderFactoryTest.kt | 10 +- .../request/PredictRequestModelBuilderTest.kt | 7 +- .../response/VisitorIdResponseHandlerTest.kt | 12 +- .../predict/response/XPResponseHandlerTest.kt | 11 +- .../shard/PredictShardListMergerTest.kt | 7 +- .../predict/storage/PredictStorageKeyTest.kt | 4 +- .../emarsys/predict/util/CartItemUtilsTest.kt | 11 +- sample/build.gradle.kts | 45 +++- testUtils/build.gradle.kts | 27 +-- .../testUtil/JUnitTestEngineListener.kt | 41 ++++ .../emarsys/testUtil/KotestRunnerAndroid.kt | 45 ++++ .../java/com/emarsys/testUtil/RetryUtils.kt | 9 + .../main/java/com/emarsys/testUtil/Specs.kt | 44 ++++ .../emarsys/testUtil/rules/ConnectionRule.kt | 18 +- .../testUtil/rules/DuplicatedThreadRule.kt | 25 +- .../com/emarsys/testUtil/rules/RetryRule.kt | 32 +++ 239 files changed, 1592 insertions(+), 1466 deletions(-) create mode 100644 testUtils/src/main/java/com/emarsys/testUtil/JUnitTestEngineListener.kt create mode 100644 testUtils/src/main/java/com/emarsys/testUtil/KotestRunnerAndroid.kt create mode 100644 testUtils/src/main/java/com/emarsys/testUtil/RetryUtils.kt create mode 100644 testUtils/src/main/java/com/emarsys/testUtil/Specs.kt create mode 100644 testUtils/src/main/java/com/emarsys/testUtil/rules/RetryRule.kt diff --git a/Makefile b/Makefile index bcbb3853..14f23679 100644 --- a/Makefile +++ b/Makefile @@ -44,8 +44,6 @@ test-android-firebase-emulator: check-env ## run Android Instrumented tests on e --device model=Pixel2.arm,version=28,locale=en,orientation=portrait \ --device model=MediumPhone.arm,version=30,locale=en,orientation=portrait \ --device model=SmallPhone.arm,version=33,locale=en,orientation=portrait \ - --environment-variables runnerBuilder=de.mannodermaus.junit5.AndroidJUnit5Builder \ - --environment-variables clearPackageData=true \ --client-details matrixLabel="Android Emarsys SDK - virtual devices" test-android-firebase: check-env ## run Android Instrumented tests on real devices on Firebase Test Lab @@ -53,13 +51,11 @@ test-android-firebase: check-env ## run Android Instrumented tests on real devic --type instrumentation \ --app ./sample/build/outputs/apk/androidTest/debug/sample-debug-androidTest.apk \ --test ./$(MODULE_NAME)/build/outputs/apk/androidTest/debug/$(MODULE_NAME)-debug-androidTest.apk \ - --device model=f2q,version=30,locale=en,orientation=portrait \ - --device model=a51,version=31,locale=en,orientation=portrait \ - --device model=bluejay,version=32,locale=en,orientation=portrait \ - --device model=b4q,version=33,locale=en,orientation=portrait \ - --environment-variables runnerBuilder=de.mannodermaus.junit5.AndroidJUnit5Builder \ - --environment-variables clearPackageData=true \ - --client-details matrixLabel="Unified SDK - physical devices" + --device model=redfin,version=30,locale=en,orientation=portrait \ + --device model=q2q,version=31,locale=en,orientation=portrait \ + --device model=oriole,version=32,locale=en,orientation=portrait \ + --device model=felix,version=33,locale=en,orientation=portrait \ + --client-details matrixLabel="Android Emarsys SDK - physical devices" run-github-workflow-locally: check-env ## needs act to be installed: `brew install act` and docker running. Pass in workflow path to run @act --secret-file ./workflow.secrets -W $(WORKFLOW_PATH) --container-architecture linux/amd64 diff --git a/common/build.gradle.kts b/common/build.gradle.kts index b1c6ae25..ea6f251b 100644 --- a/common/build.gradle.kts +++ b/common/build.gradle.kts @@ -19,15 +19,21 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArguments["runnerBuilder"] = - "de.mannodermaus.junit5.AndroidJUnit5Builder" } compileOptions { isCoreLibraryDesugaringEnabled = true } packaging { resources { - excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + excludes += arrayOf( + "README.txt", + "META-INF/LICENSE.md", + "META-INF/LICENSE-notice.md", + "**/attach_hotspot_windows.dll", + "META-INF/AL2.0", + "META-INF/LGPL2.1", + "META-INF/licenses/ASM" + ) } } } diff --git a/common/src/androidTest/java/com/emarsys/common/feature/InnerFeatureTest.kt b/common/src/androidTest/java/com/emarsys/common/feature/InnerFeatureTest.kt index 71b503b8..6862cbe3 100644 --- a/common/src/androidTest/java/com/emarsys/common/feature/InnerFeatureTest.kt +++ b/common/src/androidTest/java/com/emarsys/common/feature/InnerFeatureTest.kt @@ -1,13 +1,13 @@ package com.emarsys.common.feature +import com.emarsys.testUtil.AnnotationSpec import io.kotest.data.forAll import io.kotest.data.row import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.Test -class InnerFeatureTest { +class InnerFeatureTest : AnnotationSpec() { @Test fun testValues_shouldReturnCorrectValues() { diff --git a/core-api/build.gradle.kts b/core-api/build.gradle.kts index 0ebd99ad..2c145d3b 100644 --- a/core-api/build.gradle.kts +++ b/core-api/build.gradle.kts @@ -25,15 +25,21 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArguments["runnerBuilder"] = - "de.mannodermaus.junit5.AndroidJUnit5Builder" } compileOptions { isCoreLibraryDesugaringEnabled = true } packaging { resources { - excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + excludes += arrayOf( + "README.txt", + "META-INF/LICENSE.md", + "META-INF/LICENSE-notice.md", + "**/attach_hotspot_windows.dll", + "META-INF/AL2.0", + "META-INF/LGPL2.1", + "META-INF/licenses/ASM" + ) } } } diff --git a/core-api/src/androidTest/java/com/emarsys/core/api/ApiTest.kt b/core-api/src/androidTest/java/com/emarsys/core/api/ApiTest.kt index 0898dd37..9a53a0b4 100644 --- a/core-api/src/androidTest/java/com/emarsys/core/api/ApiTest.kt +++ b/core-api/src/androidTest/java/com/emarsys/core/api/ApiTest.kt @@ -1,10 +1,10 @@ package com.emarsys.core.api -import org.junit.jupiter.api.Test +import com.emarsys.testUtil.AnnotationSpec -class ApiTest { +class ApiTest : AnnotationSpec() { @Test diff --git a/core/build.gradle.kts b/core/build.gradle.kts index 206ad6be..a8d73efd 100644 --- a/core/build.gradle.kts +++ b/core/build.gradle.kts @@ -25,9 +25,6 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArguments["runnerBuilder"] = - "de.mannodermaus.junit5.AndroidJUnit5Builder" - val version: GitVersion by rootProject.extra buildConfigField("int", "VERSION_CODE", "${version.versionCode}") @@ -44,7 +41,15 @@ android { packaging { resources { - excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + excludes += arrayOf( + "README.txt", + "META-INF/LICENSE.md", + "META-INF/LICENSE-notice.md", + "**/attach_hotspot_windows.dll", + "META-INF/AL2.0", + "META-INF/LGPL2.1", + "META-INF/licenses/ASM" + ) } } } diff --git a/core/src/androidTest/java/com/emarsys/core/DefaultCoreCompletionHandlerTest.kt b/core/src/androidTest/java/com/emarsys/core/DefaultCoreCompletionHandlerTest.kt index 26ca2b18..1deb110c 100644 --- a/core/src/androidTest/java/com/emarsys/core/DefaultCoreCompletionHandlerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/DefaultCoreCompletionHandlerTest.kt @@ -4,9 +4,8 @@ import com.emarsys.core.api.ResponseErrorException import com.emarsys.core.api.result.CompletionListener import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.spy @@ -15,7 +14,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.verifyNoMoreInteractions -class DefaultCoreCompletionHandlerTest { +class DefaultCoreCompletionHandlerTest : AnnotationSpec() { companion object { const val STATUS_CODE = 500 @@ -30,7 +29,7 @@ class DefaultCoreCompletionHandlerTest { private lateinit var responseErrorException: ResponseErrorException - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun init() { mockMap = mock() diff --git a/core/src/androidTest/java/com/emarsys/core/DeviceInfoTest.kt b/core/src/androidTest/java/com/emarsys/core/DeviceInfoTest.kt index f254094b..9acb7efe 100644 --- a/core/src/androidTest/java/com/emarsys/core/DeviceInfoTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/DeviceInfoTest.kt @@ -13,6 +13,7 @@ import com.emarsys.core.device.LanguageProvider import com.emarsys.core.provider.hardwareid.HardwareIdProvider import com.emarsys.core.provider.version.VersionProvider import com.emarsys.core.util.AndroidVersionUtils +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ApplicationTestUtils.applicationDebug import com.emarsys.testUtil.ApplicationTestUtils.applicationRelease import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext @@ -22,16 +23,13 @@ import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import org.json.JSONObject -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import java.util.* -class DeviceInfoTest { +class DeviceInfoTest : AnnotationSpec() { companion object { private const val HARDWARE_ID = "hwid" @@ -49,7 +47,7 @@ class DeviceInfoTest { private lateinit var mockNotificationManagerHelper: NotificationSettings - @BeforeEach + @Before fun setup() { tz = TimeZone.getTimeZone("Asia/Tokyo") TimeZone.setDefault(tz) @@ -72,7 +70,7 @@ class DeviceInfoTest { ) } - @AfterEach + @After fun teardown() { TimeZone.setDefault(null) } diff --git a/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleActionRegistryTest.kt b/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleActionRegistryTest.kt index 3f244579..5499e56b 100644 --- a/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleActionRegistryTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleActionRegistryTest.kt @@ -6,9 +6,8 @@ import com.emarsys.core.activity.ActivityLifecycleAction.ActivityLifecycle.RESUM import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.provider.activity.CurrentActivityProvider +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doReturn @@ -19,7 +18,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch -class ActivityLifecycleActionRegistryTest { +class ActivityLifecycleActionRegistryTest : AnnotationSpec() { private lateinit var activityLifecycleActionRegistry: ActivityLifecycleActionRegistry private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder @@ -30,7 +29,7 @@ class ActivityLifecycleActionRegistryTest { private lateinit var mockActions: MutableList private lateinit var mockActivity: Activity - @BeforeEach + @Before fun setup() { mockActivity = mock() mockAction1 = mock { diff --git a/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleWatchdogTest.kt b/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleWatchdogTest.kt index f5ecc4cf..e78abe04 100644 --- a/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleWatchdogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/activity/ActivityLifecycleWatchdogTest.kt @@ -1,20 +1,17 @@ package com.emarsys.core.activity import android.app.Activity -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - +import com.emarsys.testUtil.AnnotationSpec import org.mockito.kotlin.mock import org.mockito.kotlin.verify -class ActivityLifecycleWatchdogTest { +class ActivityLifecycleWatchdogTest : AnnotationSpec() { private lateinit var watchdog: ActivityLifecycleWatchdog private lateinit var mockRegistry: ActivityLifecycleActionRegistry private lateinit var mockActivity: Activity - @BeforeEach + @Before fun setUp() { mockRegistry = mock() mockActivity = mock() diff --git a/core/src/androidTest/java/com/emarsys/core/activity/CurrentActivityWatchdogTest.kt b/core/src/androidTest/java/com/emarsys/core/activity/CurrentActivityWatchdogTest.kt index 8f5f895e..a181c91e 100644 --- a/core/src/androidTest/java/com/emarsys/core/activity/CurrentActivityWatchdogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/activity/CurrentActivityWatchdogTest.kt @@ -5,22 +5,21 @@ import android.os.Bundle import com.emarsys.core.provider.Property import com.emarsys.core.provider.activity.CurrentActivityProvider import com.emarsys.core.provider.activity.FallbackActivityProvider +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions -class CurrentActivityWatchdogTest { +class CurrentActivityWatchdogTest : AnnotationSpec() { private lateinit var watchdog: CurrentActivityWatchdog private lateinit var activity: Activity private lateinit var nextActivity: Activity private lateinit var activityProvider: Property - @BeforeEach + @Before fun setUp() { activityProvider = mock() watchdog = CurrentActivityWatchdog(activityProvider) diff --git a/core/src/androidTest/java/com/emarsys/core/api/AsyncProxyTest.kt b/core/src/androidTest/java/com/emarsys/core/api/AsyncProxyTest.kt index ac6f786d..b83416fd 100644 --- a/core/src/androidTest/java/com/emarsys/core/api/AsyncProxyTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/api/AsyncProxyTest.kt @@ -2,21 +2,18 @@ package com.emarsys.core.api import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.ThreadSpy import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import java.util.concurrent.Callable import java.util.concurrent.CountDownLatch -class AsyncProxyTest { +class AsyncProxyTest : AnnotationSpec() { private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun setUp() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() } diff --git a/core/src/androidTest/java/com/emarsys/core/api/LogExceptionProxyTest.kt b/core/src/androidTest/java/com/emarsys/core/api/LogExceptionProxyTest.kt index 33270a75..0a688bc3 100644 --- a/core/src/androidTest/java/com/emarsys/core/api/LogExceptionProxyTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/api/LogExceptionProxyTest.kt @@ -8,10 +8,8 @@ import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.util.log.LogLevel import com.emarsys.core.util.log.Logger import com.emarsys.core.util.log.entry.CrashLog +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq @@ -21,11 +19,11 @@ import java.lang.reflect.InvocationTargetException import java.util.concurrent.CountDownLatch -class LogExceptionProxyTest { +class LogExceptionProxyTest : AnnotationSpec() { private lateinit var mockLogger: Logger private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun setUp() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() mockLogger = mock() @@ -39,7 +37,7 @@ class LogExceptionProxyTest { setupCoreComponent(dependencyContainer) } - @AfterEach + @After fun tearDown() { tearDownCoreComponent() } diff --git a/core/src/androidTest/java/com/emarsys/core/app/AppLifecycleObserverTest.kt b/core/src/androidTest/java/com/emarsys/core/app/AppLifecycleObserverTest.kt index b80222c0..381fbb07 100644 --- a/core/src/androidTest/java/com/emarsys/core/app/AppLifecycleObserverTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/app/AppLifecycleObserverTest.kt @@ -8,17 +8,14 @@ import androidx.lifecycle.LifecycleRegistry import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.session.Session +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.verify import java.util.concurrent.CountDownLatch -class AppLifecycleObserverTest { +class AppLifecycleObserverTest : AnnotationSpec() { private lateinit var mockSession: Session private lateinit var appLifecycleObserver: AppLifecycleObserver private lateinit var coreHandlerHolder: ConcurrentHandlerHolder @@ -26,7 +23,7 @@ class AppLifecycleObserverTest { private lateinit var uiHandler: Handler - @BeforeEach + @Before fun setUp() { uiHandler = Handler(Looper.getMainLooper()) mockSession = mock() diff --git a/core/src/androidTest/java/com/emarsys/core/concurrency/ConcurrentHandlerHolderFactoryTest.kt b/core/src/androidTest/java/com/emarsys/core/concurrency/ConcurrentHandlerHolderFactoryTest.kt index 09193f6d..2c1e18c2 100644 --- a/core/src/androidTest/java/com/emarsys/core/concurrency/ConcurrentHandlerHolderFactoryTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/concurrency/ConcurrentHandlerHolderFactoryTest.kt @@ -1,23 +1,21 @@ package com.emarsys.core.concurrency import com.emarsys.core.handler.ConcurrentHandlerHolder +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -class ConcurrentHandlerHolderFactoryTest { +class ConcurrentHandlerHolderFactoryTest : AnnotationSpec() { private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun setUp() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() } - @AfterEach + @After fun tearDown() { concurrentHandlerHolder.coreLooper.quit() } diff --git a/core/src/androidTest/java/com/emarsys/core/concurrency/CoreHandlerTest.kt b/core/src/androidTest/java/com/emarsys/core/concurrency/CoreHandlerTest.kt index 04410470..073ef2ef 100644 --- a/core/src/androidTest/java/com/emarsys/core/concurrency/CoreHandlerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/concurrency/CoreHandlerTest.kt @@ -1,19 +1,17 @@ package com.emarsys.core.concurrency import android.os.HandlerThread +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import java.util.concurrent.CountDownLatch -class CoreHandlerTest { +class CoreHandlerTest : AnnotationSpec() { private lateinit var handler: CoreHandler private lateinit var handlerThread: HandlerThread private lateinit var failingRunnable: Runnable - @BeforeEach + @Before fun setUp() { val threadName = "test" handlerThread = HandlerThread(threadName) @@ -22,7 +20,7 @@ class CoreHandlerTest { failingRunnable = Runnable { throw RuntimeException("error") } } - @AfterEach + @After fun tearDown() { handlerThread.quit() } diff --git a/core/src/androidTest/java/com/emarsys/core/connection/ConnectionProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/connection/ConnectionProviderTest.kt index 04b37be0..0ad31940 100644 --- a/core/src/androidTest/java/com/emarsys/core/connection/ConnectionProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/connection/ConnectionProviderTest.kt @@ -1,16 +1,15 @@ package com.emarsys.core.connection import com.emarsys.core.request.model.RequestModel +import com.emarsys.testUtil.AnnotationSpec import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.should import io.kotest.matchers.types.beTheSameInstanceAs -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito.mock import org.mockito.Mockito.`when` import java.net.URL -class ConnectionProviderTest { +class ConnectionProviderTest : AnnotationSpec() { companion object { const val HTTP_PATH = "http://emarsys.com" const val HTTPS_PATH = "https://emarsys.com" @@ -19,7 +18,7 @@ class ConnectionProviderTest { private lateinit var provider: ConnectionProvider - @BeforeEach + @Before fun setUp() { provider = ConnectionProvider() } diff --git a/core/src/androidTest/java/com/emarsys/core/connection/ConnectionWatchDogTest.kt b/core/src/androidTest/java/com/emarsys/core/connection/ConnectionWatchDogTest.kt index dee11c25..70b07824 100644 --- a/core/src/androidTest/java/com/emarsys/core/connection/ConnectionWatchDogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/connection/ConnectionWatchDogTest.kt @@ -8,6 +8,7 @@ import androidx.test.filters.SdkSuppress import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.worker.DefaultWorker +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ConnectionTestUtils.getContextMockWithAppContextWithConnectivityManager import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.ReflectionTestUtils @@ -18,17 +19,15 @@ import io.mockk.every import io.mockk.just import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test @SdkSuppress(minSdkVersion = Build.VERSION_CODES.P) -class ConnectionWatchDogTest { +class ConnectionWatchDogTest : AnnotationSpec() { private lateinit var context: Context private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun setup() { context = getTargetContext().applicationContext concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() diff --git a/core/src/androidTest/java/com/emarsys/core/connection/ConnectivityChangeReceiverTest.kt b/core/src/androidTest/java/com/emarsys/core/connection/ConnectivityChangeReceiverTest.kt index 7ef86038..5621bcb6 100644 --- a/core/src/androidTest/java/com/emarsys/core/connection/ConnectivityChangeReceiverTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/connection/ConnectivityChangeReceiverTest.kt @@ -7,14 +7,12 @@ import androidx.test.platform.app.InstrumentationRegistry import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.fake.FakeConnectionChangeListener import com.emarsys.core.handler.ConcurrentHandlerHolder +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import java.util.concurrent.CountDownLatch -class ConnectivityChangeReceiverTest { +class ConnectivityChangeReceiverTest : AnnotationSpec() { private lateinit var receiver: ConnectivityChangeReceiver private lateinit var mockListener: ConnectionChangeListener private lateinit var context: Context @@ -22,7 +20,7 @@ class ConnectivityChangeReceiverTest { lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun setup() { context = InstrumentationRegistry.getInstrumentation().targetContext concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() @@ -30,7 +28,7 @@ class ConnectivityChangeReceiverTest { mockListener = mock() } - @AfterEach + @After fun tearDown() { concurrentHandlerHolder.coreLooper.quit() } diff --git a/core/src/androidTest/java/com/emarsys/core/connection/Connectivity_getConnectionState_ParameterizedTest.kt b/core/src/androidTest/java/com/emarsys/core/connection/Connectivity_getConnectionState_ParameterizedTest.kt index d25087e5..80032b5c 100644 --- a/core/src/androidTest/java/com/emarsys/core/connection/Connectivity_getConnectionState_ParameterizedTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/connection/Connectivity_getConnectionState_ParameterizedTest.kt @@ -4,6 +4,7 @@ import android.net.NetworkCapabilities import android.os.Build import androidx.test.filters.SdkSuppress import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ConnectionTestUtils.getConnectivityManagerMock import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.ReflectionTestUtils.setInstanceField @@ -11,11 +12,10 @@ import io.kotest.data.forAll import io.kotest.data.row import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.Test @SdkSuppress(minSdkVersion = Build.VERSION_CODES.P) -class Connectivity_getConnectionState_ParameterizedTest { +class Connectivity_getConnectionState_ParameterizedTest : AnnotationSpec() { @Test diff --git a/core/src/androidTest/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolverTest.kt b/core/src/androidTest/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolverTest.kt index 28706f70..070f4e3e 100644 --- a/core/src/androidTest/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolverTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/contentresolver/hardwareid/HardwareIdContentResolverTest.kt @@ -5,14 +5,13 @@ import com.emarsys.core.contentresolver.hardwareid.HardwareIdContentResolver import com.emarsys.core.crypto.HardwareIdentificationCrypto import com.emarsys.core.database.DatabaseContract import com.emarsys.core.device.HardwareIdentification +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -class HardwareIdContentResolverTest { +class HardwareIdContentResolverTest : AnnotationSpec() { companion object { private val SHARED_PACKAGE_NAMES = @@ -28,7 +27,7 @@ class HardwareIdContentResolverTest { private lateinit var mockHardwareIdentificationCrypto: HardwareIdentificationCrypto private lateinit var mockCursor: Cursor - @BeforeEach + @Before fun setUp() { mockCursor = mockk(relaxed = true) { every { moveToFirst() } returns true diff --git a/core/src/androidTest/java/com/emarsys/core/crypto/CryptoTest.kt b/core/src/androidTest/java/com/emarsys/core/crypto/CryptoTest.kt index 96e26bf8..428e8801 100644 --- a/core/src/androidTest/java/com/emarsys/core/crypto/CryptoTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/crypto/CryptoTest.kt @@ -1,16 +1,17 @@ package com.emarsys.core.crypto import android.util.Base64 +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.Test import java.security.KeyFactory import java.security.PublicKey import java.security.spec.X509EncodedKeySpec -class CryptoTest { +class CryptoTest : AnnotationSpec() { private companion object { - private const val PUBLIC_KEY = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELjWEUIBX9zlm1OI4gF1hMCBLzpaBwgs9HlmSIBAqP4MDGy4ibOOV3FVDrnAY0Q34LZTbPBlp3gRNZJ19UoSy2Q==" + private const val PUBLIC_KEY = + "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELjWEUIBX9zlm1OI4gF1hMCBLzpaBwgs9HlmSIBAqP4MDGy4ibOOV3FVDrnAY0Q34LZTbPBlp3gRNZJ19UoSy2Q==" private const val SECRET = "testSecret" private const val OLD_ITERATION_COUNT = 65536 } @@ -18,8 +19,9 @@ class CryptoTest { @Test fun testVerify_success() { val crypto = Crypto(createPublicKey()) - val result = crypto.verify("testData".toByteArray(), - "MEUCIQDb6AxUK2W4IyKJ/P02Y0BNlm2ioP7ytu3dOyumc4hN8gIgEzwKmeCtd6Jn9Neg4Epn+oSkV4wAJNmfAgeeAM0u7Nw=" + val result = crypto.verify( + "testData".toByteArray(), + "MEUCIQDb6AxUK2W4IyKJ/P02Y0BNlm2ioP7ytu3dOyumc4hN8gIgEzwKmeCtd6Jn9Neg4Epn+oSkV4wAJNmfAgeeAM0u7Nw=" ) result shouldBe true diff --git a/core/src/androidTest/java/com/emarsys/core/crypto/HardwareIdentificationCryptoTest.kt b/core/src/androidTest/java/com/emarsys/core/crypto/HardwareIdentificationCryptoTest.kt index 2788ca27..e6ae2889 100644 --- a/core/src/androidTest/java/com/emarsys/core/crypto/HardwareIdentificationCryptoTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/crypto/HardwareIdentificationCryptoTest.kt @@ -1,13 +1,12 @@ package com.emarsys.core.crypto import com.emarsys.core.device.HardwareIdentification +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.whenever -class HardwareIdentificationCryptoTest { +class HardwareIdentificationCryptoTest : AnnotationSpec() { companion object { private const val SECRET = "SECRET" @@ -16,14 +15,15 @@ class HardwareIdentificationCryptoTest { private const val SALT = "testSalt" private const val IV = "testIv" private val HARDWARE = HardwareIdentification(HARDWARE_ID, null, null, null) - private val ENCRYPTED_HARDWARE = HardwareIdentification(HARDWARE_ID, ENCRYPTED_HARDWARE_ID, SALT, IV) + private val ENCRYPTED_HARDWARE = + HardwareIdentification(HARDWARE_ID, ENCRYPTED_HARDWARE_ID, SALT, IV) } private lateinit var hardwareIdentificationCryptoWithSecret: HardwareIdentificationCrypto private lateinit var hardwareIdentificationCryptoWithoutSecret: HardwareIdentificationCrypto private lateinit var mockCrypto: Crypto - @BeforeEach + @Before fun setUp() { mockCrypto = mock() diff --git a/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabaseTest.kt b/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabaseTest.kt index 6ef57c53..82a67562 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabaseTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabaseTest.kt @@ -4,25 +4,23 @@ import com.emarsys.core.database.helper.CoreDbHelper import com.emarsys.core.database.trigger.TriggerEvent import com.emarsys.core.database.trigger.TriggerKey import com.emarsys.core.database.trigger.TriggerType +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.matchers.shouldBe - -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito.mock -class DelegatingCoreSQLiteDatabaseTest { - +class DelegatingCoreSQLiteDatabaseTest : AnnotationSpec() { private lateinit var db: DelegatingCoreSQLiteDatabase private lateinit var triggerMap: MutableMap> - @BeforeEach + @Before fun init() { - val coreDbHelper = CoreDbHelper(InstrumentationRegistry.getTargetContext().applicationContext, mutableMapOf()) + val coreDbHelper = CoreDbHelper( + InstrumentationRegistry.getTargetContext().applicationContext, + mutableMapOf() + ) triggerMap = mutableMapOf() diff --git a/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest.kt b/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest.kt index efbe7441..fd056944 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest.kt @@ -5,22 +5,41 @@ import com.emarsys.core.database.helper.CoreDbHelper import com.emarsys.core.database.trigger.TriggerEvent import com.emarsys.core.database.trigger.TriggerKey import com.emarsys.core.database.trigger.TriggerType +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry +import io.kotest.data.forAll +import io.kotest.data.headers +import io.kotest.data.row +import io.kotest.data.table import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.params.ParameterizedTest -import org.junit.jupiter.params.provider.MethodSource import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions -class DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest { +class DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest : AnnotationSpec() { + + companion object { + + private const val TABLE_NAME = "TEST" + private const val COLUMN_1 = "column1" + private const val COLUMN_2 = "column2" + const val CREATE = "CREATE TABLE $TABLE_NAME ($COLUMN_1 TEXT, $COLUMN_2 INTEGER);" + const val DROP = "DROP TABLE $TABLE_NAME IF EXISTS;" + + private lateinit var mockRunnable: Runnable + private lateinit var db: DelegatingCoreSQLiteDatabase + + private val contentValues = ContentValues().apply { + put(COLUMN_1, "value") + put(COLUMN_2, 1234) + } + } private lateinit var registeredTriggerMap: MutableMap> - @BeforeEach - fun init() { + @Before + fun setUp() { DatabaseTestUtils.deleteCoreDatabase() val coreDbHelper = CoreDbHelper( @@ -35,28 +54,89 @@ class DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest { mockRunnable = mock() } - @ParameterizedTest - @MethodSource("data") - fun testTrigger( - tableName: String, - triggerType: TriggerType, - triggerEvent: TriggerEvent, - setup: Runnable, - trigger: Runnable, - action: Runnable - ) { - setup.run() - - val unusedTriggerMap = createUnusedTriggerMap(tableName, triggerEvent) - unusedTriggerMap.forEach { (key, trigger) -> - db.registerTrigger(key.tableName, key.triggerType, key.triggerEvent, trigger) - } - db.registerTrigger(tableName, triggerType, triggerEvent, trigger) + @Test + fun testTrigger() { + table( + headers("tableName", "triggerType", "triggerEvent", "setup", "trigger", "action"), + row( + TABLE_NAME, + TriggerType.BEFORE, + TriggerEvent.INSERT, + Runnable { + + }, + Runnable { + db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { + it.count shouldBe 0 + } + mockRunnable.run() + }, + Runnable { + db.insert(TABLE_NAME, null, contentValues) + }), + row( + TABLE_NAME, + TriggerType.AFTER, + TriggerEvent.INSERT, + Runnable { + + }, + Runnable { + db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { + it.count shouldBe 1 + } + mockRunnable.run() + }, + Runnable { + db.insert(TABLE_NAME, null, contentValues) + }), + row( + TABLE_NAME, + TriggerType.BEFORE, + TriggerEvent.DELETE, + Runnable { + db.insert(TABLE_NAME, null, contentValues) + }, + Runnable { + db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { + it.count shouldBe 1 + } + mockRunnable.run() + }, + Runnable { + db.delete(TABLE_NAME, null, null) + }), + row( + TABLE_NAME, + TriggerType.AFTER, + TriggerEvent.DELETE, + Runnable { + db.insert(TABLE_NAME, null, contentValues) + }, + Runnable { + db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { + it.count shouldBe 0 + } + mockRunnable.run() + }, + Runnable { + db.delete(TABLE_NAME, null, null) + }) + ).forAll { tableName, triggerType, triggerEvent, setup, trigger, action -> + setUp() + setup.run() + + val unusedTriggerMap = createUnusedTriggerMap(tableName, triggerEvent) + unusedTriggerMap.forEach { (key, trigger) -> + db.registerTrigger(key.tableName, key.triggerType, key.triggerEvent, trigger) + } + db.registerTrigger(tableName, triggerType, triggerEvent, trigger) - action.run() + action.run() - unusedTriggerMap.values.forEach { verifyNoInteractions(it) } - verify(mockRunnable).run() + unusedTriggerMap.values.forEach { verifyNoInteractions(it) } + verify(mockRunnable).run() + } } private fun createUnusedTriggerMap( @@ -80,89 +160,4 @@ class DelegatingCoreSQLiteDatabase_registerTrigger_parameterizedTest { } } - companion object { - - private const val TABLE_NAME = "TEST" - private const val COLUMN_1 = "column1" - private const val COLUMN_2 = "column2" - const val CREATE = "CREATE TABLE $TABLE_NAME ($COLUMN_1 TEXT, $COLUMN_2 INTEGER);" - - private lateinit var mockRunnable: Runnable - private lateinit var db: DelegatingCoreSQLiteDatabase - - private val contentValues = ContentValues().apply { - put(COLUMN_1, "value") - put(COLUMN_2, 1234) - } - - @JvmStatic - fun data(): Collection> { - return listOf( - arrayOf( - TABLE_NAME, - TriggerType.BEFORE, - TriggerEvent.INSERT, - Runnable { - - }, - Runnable { - db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { - it.count shouldBe 0 - } - mockRunnable.run() - }, - Runnable { - db.insert(TABLE_NAME, null, contentValues) - }), - arrayOf( - TABLE_NAME, - TriggerType.AFTER, - TriggerEvent.INSERT, - Runnable { - - }, - Runnable { - db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { - it.count shouldBe 1 - } - mockRunnable.run() - }, - Runnable { - db.insert(TABLE_NAME, null, contentValues) - }), - arrayOf( - TABLE_NAME, - TriggerType.BEFORE, - TriggerEvent.DELETE, - Runnable { - db.insert(TABLE_NAME, null, contentValues) - }, - Runnable { - db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { - it.count shouldBe 1 - } - mockRunnable.run() - }, - Runnable { - db.delete(TABLE_NAME, null, null) - }), - arrayOf( - TABLE_NAME, - TriggerType.AFTER, - TriggerEvent.DELETE, - Runnable { - db.insert(TABLE_NAME, null, contentValues) - }, - Runnable { - db.backingDatabase.rawQuery("SELECT * FROM $TABLE_NAME", emptyArray()).let { - it.count shouldBe 0 - } - mockRunnable.run() - }, - Runnable { - db.delete(TABLE_NAME, null, null) - }) - ) - } - } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_triggerRecursion_parameterizedTest.kt b/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_triggerRecursion_parameterizedTest.kt index b536ad14..de66b790 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_triggerRecursion_parameterizedTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/DelegatingCoreSQLiteDatabase_triggerRecursion_parameterizedTest.kt @@ -4,21 +4,34 @@ import android.content.ContentValues import com.emarsys.core.database.helper.CoreDbHelper import com.emarsys.core.database.trigger.TriggerEvent import com.emarsys.core.database.trigger.TriggerType +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.params.ParameterizedTest -import org.junit.jupiter.params.provider.MethodSource -import org.mockito.Mockito +import io.kotest.data.forAll +import io.kotest.data.row +import kotlinx.coroutines.runBlocking import org.mockito.Mockito.mock +import org.mockito.Mockito.verify -class DelegatingCoreSQLiteDatabase_triggerRecursion_parameterizedTest { +class DelegatingCoreSQLiteDatabase_triggerRecursion_parameterizedTest : AnnotationSpec() { + + companion object { + private const val TABLE_NAME = "TEST" + private const val COLUMN_1 = "column1" + private const val COLUMN_2 = "column2" + const val CREATE = "CREATE TABLE $TABLE_NAME ($COLUMN_1 TEXT, $COLUMN_2 INTEGER);" + + private val contentValues = ContentValues().apply { + put(COLUMN_1, "value") + put(COLUMN_2, 1234) + } + } private lateinit var mockRunnable: Runnable private lateinit var db: DelegatingCoreSQLiteDatabase - @BeforeEach - fun init() { + @Before + fun setUp() { DatabaseTestUtils.deleteCoreDatabase() val coreDbHelper = CoreDbHelper( @@ -29,78 +42,60 @@ class DelegatingCoreSQLiteDatabase_triggerRecursion_parameterizedTest { db.backingDatabase.execSQL(CREATE) - mockRunnable = mock(Runnable::class.java) - } - - @ParameterizedTest - @MethodSource("data") - fun testRegisterTrigger_doesNotRunInto_recursiveTriggerLoop( - triggerType: TriggerType, - triggerEvent: TriggerEvent, - triggerAction: Runnable - ) { - val trigger = Runnable { - triggerAction.run() - mockRunnable.run() - } - - db.registerTrigger(TABLE_NAME, triggerType, triggerEvent, trigger) - - triggerAction.run() - - Mockito.verify(mockRunnable).run() + mockRunnable = mock() } - companion object { - private const val TABLE_NAME = "TEST" - private const val COLUMN_1 = "column1" - private const val COLUMN_2 = "column2" - const val CREATE = "CREATE TABLE $TABLE_NAME ($COLUMN_1 TEXT, $COLUMN_2 INTEGER);" - - private val contentValues = ContentValues().apply { - put(COLUMN_1, "value") - put(COLUMN_2, 1234) - } - } - - fun data(): Collection> { - return listOf( - arrayOf( + @Test + fun testRegisterTrigger_doesNotRunInto_recursiveTriggerLoop() = runBlocking { + forAll( + row( TriggerType.BEFORE, TriggerEvent.INSERT, Runnable { db.insert(TABLE_NAME, null, contentValues) }), - arrayOf( + row( TriggerType.AFTER, TriggerEvent.INSERT, Runnable { db.insert(TABLE_NAME, null, contentValues) }), - arrayOf( + row( TriggerType.BEFORE, TriggerEvent.DELETE, Runnable { db.delete(TABLE_NAME, null, null) }), - arrayOf( + row( TriggerType.AFTER, TriggerEvent.DELETE, Runnable { db.delete(TABLE_NAME, null, null) }), - arrayOf( + row( TriggerType.BEFORE, TriggerEvent.UPDATE, Runnable { db.update(TABLE_NAME, contentValues, null, null) }), - arrayOf( + row( TriggerType.AFTER, TriggerEvent.UPDATE, Runnable { db.update(TABLE_NAME, contentValues, null, null) }) - ) + ) { triggerType, triggerEvent, triggerAction -> + setUp() + val trigger = Runnable { + triggerAction.run() + mockRunnable.run() + } + + db.registerTrigger(TABLE_NAME, triggerType, triggerEvent, trigger) + + triggerAction.run() + + verify(mockRunnable).run() + } } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/database/helper/AbstractDbHelperTest.kt b/core/src/androidTest/java/com/emarsys/core/database/helper/AbstractDbHelperTest.kt index 41aee479..09b7856f 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/helper/AbstractDbHelperTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/helper/AbstractDbHelperTest.kt @@ -3,12 +3,11 @@ package com.emarsys.core.database.helper import android.content.Context import android.database.sqlite.SQLiteDatabase import com.emarsys.core.database.trigger.TriggerKey +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -class AbstractDbHelperTest { +class AbstractDbHelperTest : AnnotationSpec() { private class DummyDbHelper( context: Context, databaseName: String, @@ -24,7 +23,7 @@ class AbstractDbHelperTest { private lateinit var triggerMap: MutableMap> - @BeforeEach + @Before fun init() { context = getTargetContext() triggerMap = mutableMapOf() diff --git a/core/src/androidTest/java/com/emarsys/core/database/helper/CoreDbHelperTest.kt b/core/src/androidTest/java/com/emarsys/core/database/helper/CoreDbHelperTest.kt index 9922deef..8d222e83 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/helper/CoreDbHelperTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/helper/CoreDbHelperTest.kt @@ -2,27 +2,24 @@ package com.emarsys.core.database.helper import android.database.Cursor import android.database.sqlite.SQLiteDatabase +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.matchers.collections.shouldContain import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -class CoreDbHelperTest { +class CoreDbHelperTest : AnnotationSpec() { companion object { const val LATEST_DB_VERSION = 5 } - private lateinit var dbHelper: CoreDbHelper private lateinit var db: SQLiteDatabase - @BeforeEach + @Before fun init() { DatabaseTestUtils.deleteCoreDatabase() dbHelper = CoreDbHelper( @@ -32,7 +29,7 @@ class CoreDbHelperTest { DatabaseTestUtils.dropAllTables(db) } - @AfterEach + @After fun tearDown() { db.close() } diff --git a/core/src/androidTest/java/com/emarsys/core/database/repository/AbstractSqliteRepositoryTest.kt b/core/src/androidTest/java/com/emarsys/core/database/repository/AbstractSqliteRepositoryTest.kt index 4a0b83ed..2da00ac7 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/repository/AbstractSqliteRepositoryTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/repository/AbstractSqliteRepositoryTest.kt @@ -20,13 +20,12 @@ import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.request.model.RequestModel import com.emarsys.core.util.serialization.SerializationUtils.serializableToBlob +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.mockito.anyNotNull import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull @@ -37,7 +36,7 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.whenever -class AbstractSqliteRepositoryTest { +class AbstractSqliteRepositoryTest : AnnotationSpec() { companion object { private const val DISTINCT = true @@ -58,7 +57,7 @@ class AbstractSqliteRepositoryTest { private lateinit var testConcurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun init() { DatabaseTestUtils.deleteCoreDatabase() diff --git a/core/src/androidTest/java/com/emarsys/core/database/repository/specification/EverythingTest.kt b/core/src/androidTest/java/com/emarsys/core/database/repository/specification/EverythingTest.kt index 4d713b4c..e146066c 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/repository/specification/EverythingTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/repository/specification/EverythingTest.kt @@ -5,23 +5,21 @@ import com.emarsys.core.database.helper.CoreDbHelper import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.shard.ShardModel import com.emarsys.core.shard.ShardModelRepository +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.matchers.collections.beEmpty import io.kotest.matchers.should import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test - -class EverythingTest { +class EverythingTest : AnnotationSpec() { private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun init() { DatabaseTestUtils.deleteCoreDatabase() concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() diff --git a/core/src/androidTest/java/com/emarsys/core/database/repository/specification/FilterByRequestIdsTest.kt b/core/src/androidTest/java/com/emarsys/core/database/repository/specification/FilterByRequestIdsTest.kt index f9a10fe5..ddf46b4b 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/repository/specification/FilterByRequestIdsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/repository/specification/FilterByRequestIdsTest.kt @@ -7,15 +7,13 @@ import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.request.model.RequestModel import com.emarsys.core.request.model.RequestModelRepository import com.emarsys.core.request.model.specification.FilterByRequestIds +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test - -class FilterByRequestIdsTest { +class FilterByRequestIdsTest : AnnotationSpec() { private lateinit var repository: RequestModelRepository @@ -24,7 +22,7 @@ class FilterByRequestIdsTest { private lateinit var requestModel3: RequestModel private lateinit var requestModel4: RequestModel - @BeforeEach + @Before fun init() { DatabaseTestUtils.deleteCoreDatabase() val timestampProvider = TimestampProvider() diff --git a/core/src/androidTest/java/com/emarsys/core/database/repository/specification/QueryLatestRequestModelTest.kt b/core/src/androidTest/java/com/emarsys/core/database/repository/specification/QueryLatestRequestModelTest.kt index 8df447c0..05968e42 100644 --- a/core/src/androidTest/java/com/emarsys/core/database/repository/specification/QueryLatestRequestModelTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/database/repository/specification/QueryLatestRequestModelTest.kt @@ -7,21 +7,19 @@ import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.request.model.RequestModel import com.emarsys.core.request.model.RequestModelRepository import com.emarsys.core.request.model.specification.QueryLatestRequestModel +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test - -class QueryLatestRequestModelTest { +class QueryLatestRequestModelTest : AnnotationSpec() { private lateinit var specification: QueryLatestRequestModel - @BeforeEach + @Before fun init() { DatabaseTestUtils.deleteCoreDatabase() specification = QueryLatestRequestModel() diff --git a/core/src/androidTest/java/com/emarsys/core/device/LanguageProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/device/LanguageProviderTest.kt index eef063e8..33c6d2e1 100644 --- a/core/src/androidTest/java/com/emarsys/core/device/LanguageProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/device/LanguageProviderTest.kt @@ -2,18 +2,17 @@ package com.emarsys.core.device import android.os.Build.VERSION_CODES.P import androidx.test.filters.SdkSuppress +import com.emarsys.testUtil.AnnotationSpec import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import java.util.Locale -class LanguageProviderTest { +class LanguageProviderTest : AnnotationSpec() { private lateinit var languageProvider: LanguageProvider - @BeforeEach + @Before fun setUp() { languageProvider = LanguageProvider() } diff --git a/core/src/androidTest/java/com/emarsys/core/endpoint/ServiceEndpointProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/endpoint/ServiceEndpointProviderTest.kt index d2552161..0b8c55a3 100644 --- a/core/src/androidTest/java/com/emarsys/core/endpoint/ServiceEndpointProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/endpoint/ServiceEndpointProviderTest.kt @@ -1,26 +1,22 @@ package com.emarsys.core.endpoint import com.emarsys.core.storage.StringStorage +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito -class ServiceEndpointProviderTest { +class ServiceEndpointProviderTest : AnnotationSpec() { companion object { const val ENDPOINT = "https://emarsys.com" const val DEFAULT_ENDPOINT = "https://default.emarsys.com" } - private lateinit var serviceEndpointProvider: ServiceEndpointProvider private lateinit var mockServiceUrlStorage: StringStorage - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun setUp() { mockServiceUrlStorage = Mockito.mock(StringStorage::class.java) diff --git a/core/src/androidTest/java/com/emarsys/core/fake/FakeRequestTask.java b/core/src/androidTest/java/com/emarsys/core/fake/FakeRequestTask.java index 13b9e482..e6e89a6e 100644 --- a/core/src/androidTest/java/com/emarsys/core/fake/FakeRequestTask.java +++ b/core/src/androidTest/java/com/emarsys/core/fake/FakeRequestTask.java @@ -1,12 +1,14 @@ package com.emarsys.core.fake; import static org.mockito.Mockito.mock; + import com.emarsys.core.api.result.Try; import com.emarsys.core.connection.ConnectionProvider; import com.emarsys.core.provider.timestamp.TimestampProvider; import com.emarsys.core.request.RequestTask; import com.emarsys.core.request.model.RequestModel; import com.emarsys.core.response.ResponseModel; + import java.util.HashMap; import java.util.List; diff --git a/core/src/androidTest/java/com/emarsys/core/feature/FeatureRegistryTest.kt b/core/src/androidTest/java/com/emarsys/core/feature/FeatureRegistryTest.kt index 7b9c29ed..6596f767 100644 --- a/core/src/androidTest/java/com/emarsys/core/feature/FeatureRegistryTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/feature/FeatureRegistryTest.kt @@ -5,21 +5,19 @@ import com.emarsys.core.feature.FeatureRegistry.disableFeature import com.emarsys.core.feature.FeatureRegistry.enableFeature import com.emarsys.core.feature.FeatureRegistry.isFeatureEnabled import com.emarsys.core.feature.FeatureRegistry.reset +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.whenever -class FeatureRegistryTest { +class FeatureRegistryTest : AnnotationSpec() { private lateinit var feature1: FlipperFeature private lateinit var feature2: FlipperFeature private lateinit var feature3: FlipperFeature private lateinit var features: List - @BeforeEach + @Before fun setUp() { reset() feature1 = mock() @@ -31,7 +29,7 @@ class FeatureRegistryTest { features = listOf(feature1, feature2, feature3) } - @AfterEach + @After fun tearDown() { reset() } diff --git a/core/src/androidTest/java/com/emarsys/core/notification/NotificationManagerHelperTest.kt b/core/src/androidTest/java/com/emarsys/core/notification/NotificationManagerHelperTest.kt index 763fca20..28762eae 100644 --- a/core/src/androidTest/java/com/emarsys/core/notification/NotificationManagerHelperTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/notification/NotificationManagerHelperTest.kt @@ -1,15 +1,12 @@ package com.emarsys.core.notification import com.emarsys.core.api.notification.ChannelSettings +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito.mock -class NotificationManagerHelperTest { +class NotificationManagerHelperTest : AnnotationSpec() { private companion object { const val CHANNEL_ID_1 = "channelId1" @@ -21,7 +18,7 @@ class NotificationManagerHelperTest { private lateinit var notificationManagerHelper: NotificationManagerHelper - @BeforeEach + @Before fun setUp() { mockNotificationManagerProxy = mock(NotificationManagerProxy::class.java) notificationManagerHelper = NotificationManagerHelper(mockNotificationManagerProxy) diff --git a/core/src/androidTest/java/com/emarsys/core/provider/activity/CurrentActivityProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/provider/activity/CurrentActivityProviderTest.kt index 69cac77f..e31a8884 100644 --- a/core/src/androidTest/java/com/emarsys/core/provider/activity/CurrentActivityProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/provider/activity/CurrentActivityProviderTest.kt @@ -1,14 +1,13 @@ package com.emarsys.core.provider.activity import android.app.Activity +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import java.lang.ref.WeakReference -class CurrentActivityProviderTest { +class CurrentActivityProviderTest : AnnotationSpec() { private lateinit var provider: CurrentActivityProvider private lateinit var mockFallbackActivityProvider: FallbackActivityProvider @@ -18,7 +17,7 @@ class CurrentActivityProviderTest { } - @BeforeEach + @Before fun setUp() { mockFallbackActivityProvider = mock() provider = CurrentActivityProvider(WeakReference(null), mockFallbackActivityProvider) diff --git a/core/src/androidTest/java/com/emarsys/core/provider/hardwareid/HardwareIdProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/provider/hardwareid/HardwareIdProviderTest.kt index 51ec2f98..e1c397dc 100644 --- a/core/src/androidTest/java/com/emarsys/core/provider/hardwareid/HardwareIdProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/provider/hardwareid/HardwareIdProviderTest.kt @@ -7,11 +7,10 @@ import com.emarsys.core.database.repository.SqlSpecification import com.emarsys.core.device.HardwareIdentification import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.storage.Storage +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -19,7 +18,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions -class HardwareIdProviderTest { +class HardwareIdProviderTest : AnnotationSpec() { companion object { private const val HARDWARE_ID = "hw_value" @@ -47,7 +46,7 @@ class HardwareIdProviderTest { private lateinit var mockRepository: Repository - @BeforeEach + @Before fun setUp() { mockStorage = mock() mockUUIDProvider = mock { diff --git a/core/src/androidTest/java/com/emarsys/core/provider/random/RandomProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/provider/random/RandomProviderTest.kt index 5590774b..0f5c5d56 100644 --- a/core/src/androidTest/java/com/emarsys/core/provider/random/RandomProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/provider/random/RandomProviderTest.kt @@ -1,16 +1,16 @@ package com.emarsys.core.provider.random +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.doubles.shouldBeGreaterThanOrEqual import io.kotest.matchers.doubles.shouldBeLessThanOrEqual -import org.junit.jupiter.api.Test -class RandomProviderTest { +class RandomProviderTest : AnnotationSpec() { @Test fun testProvideRandomDouble() { val randomProvider = RandomProvider() randomProvider.provideDouble(1.0) shouldBeGreaterThanOrEqual 0.0 - randomProvider.provideDouble(1.0) shouldBeLessThanOrEqual 1.0 + randomProvider.provideDouble(1.0) shouldBeLessThanOrEqual 1.0 } } \ No newline at end of file diff --git a/core/src/androidTest/java/com/emarsys/core/provider/timestamp/TimestampProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/provider/timestamp/TimestampProviderTest.kt index ecf4470d..56ea6044 100644 --- a/core/src/androidTest/java/com/emarsys/core/provider/timestamp/TimestampProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/provider/timestamp/TimestampProviderTest.kt @@ -1,9 +1,9 @@ package com.emarsys.core.provider.timestamp +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test -class TimestampProviderTest { +class TimestampProviderTest : AnnotationSpec() { @Test fun testProvideTimestamp_returnsTheCurrentTimestamp() { val before = System.currentTimeMillis() diff --git a/core/src/androidTest/java/com/emarsys/core/provider/uuid/UUIDProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/provider/uuid/UUIDProviderTest.kt index 0b93cc6f..c2530cac 100644 --- a/core/src/androidTest/java/com/emarsys/core/provider/uuid/UUIDProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/provider/uuid/UUIDProviderTest.kt @@ -1,9 +1,9 @@ package com.emarsys.core.provider.uuid +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.Test -class UUIDProviderTest { +class UUIDProviderTest : AnnotationSpec() { @Test fun testProvideId_returnsNotNullId() { val provider = UUIDProvider() diff --git a/core/src/androidTest/java/com/emarsys/core/provider/version/VersionProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/provider/version/VersionProviderTest.kt index 9d6a7b50..73599054 100644 --- a/core/src/androidTest/java/com/emarsys/core/provider/version/VersionProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/provider/version/VersionProviderTest.kt @@ -1,17 +1,15 @@ package com.emarsys.core.provider.version +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test - -class VersionProviderTest { +class VersionProviderTest : AnnotationSpec() { private lateinit var versionProvider: VersionProvider - @BeforeEach + @Before fun setUp() { versionProvider = VersionProvider() } diff --git a/core/src/androidTest/java/com/emarsys/core/request/RequestManagerDennaTest.kt b/core/src/androidTest/java/com/emarsys/core/request/RequestManagerDennaTest.kt index 1d5f45d0..798af610 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/RequestManagerDennaTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/RequestManagerDennaTest.kt @@ -19,21 +19,19 @@ import com.emarsys.core.shard.ShardModel import com.emarsys.core.shard.ShardModelRepository import com.emarsys.core.worker.DefaultWorker import com.emarsys.core.worker.Worker +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ConnectionTestUtils.checkConnection import com.emarsys.testUtil.DatabaseTestUtils.deleteCoreDatabase import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.TestUrls.DENNA_ECHO import io.kotest.matchers.shouldBe import org.json.JSONObject -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer import org.mockito.kotlin.mock import java.util.concurrent.CountDownLatch -class RequestManagerDennaTest { +class RequestManagerDennaTest : AnnotationSpec() { private lateinit var manager: RequestManager private lateinit var headers: MutableMap private lateinit var model: RequestModel @@ -48,7 +46,7 @@ class RequestManagerDennaTest { private lateinit var mockRequestModelMapper: Mapper - @BeforeEach + @Before fun init() { deleteCoreDatabase() val requestModelMappers: MutableList> = mutableListOf() @@ -109,7 +107,7 @@ class RequestManagerDennaTest { headers["Header2"] = "value2" } - @AfterEach + @After fun tearDown() { concurrentHandlerHolder.coreLooper.quit() } diff --git a/core/src/androidTest/java/com/emarsys/core/request/RequestManagerOfflineTest.kt b/core/src/androidTest/java/com/emarsys/core/request/RequestManagerOfflineTest.kt index 5070cb5b..13e544dd 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/RequestManagerOfflineTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/RequestManagerOfflineTest.kt @@ -22,26 +22,23 @@ import com.emarsys.core.shard.ShardModel import com.emarsys.core.shard.ShardModelRepository import com.emarsys.core.worker.DefaultWorker import com.emarsys.core.worker.Worker +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.matchers.collections.beEmpty import io.kotest.matchers.should import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import java.io.IOException import java.util.concurrent.CountDownLatch -class RequestManagerOfflineTest { +class RequestManagerOfflineTest : AnnotationSpec() { companion object { const val URL = "https://www.emarsys.com/" } - private lateinit var connectionStates: Array private lateinit var requestResults: Array private lateinit var requestModels: Array @@ -60,7 +57,7 @@ class RequestManagerOfflineTest { private lateinit var coreCompletionHandlerMiddlewareProvider: CoreCompletionHandlerMiddlewareProvider private lateinit var mockProxyProvider: CompletionHandlerProxyProvider - @BeforeEach + @Before fun setup() { watchDogCountDown = 0 completionHandlerCountDown = 0 @@ -70,7 +67,7 @@ class RequestManagerOfflineTest { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() } - @AfterEach + @After fun tearDown() { concurrentHandlerHolder.coreLooper.quit() concurrentHandlerHolder.networkLooper.quit() diff --git a/core/src/androidTest/java/com/emarsys/core/request/RequestManagerTest.kt b/core/src/androidTest/java/com/emarsys/core/request/RequestManagerTest.kt index 57e5072f..3c2027a6 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/RequestManagerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/RequestManagerTest.kt @@ -22,27 +22,39 @@ import com.emarsys.core.shard.ShardModel import com.emarsys.core.worker.DefaultWorker import com.emarsys.core.worker.DelegatorCompletionHandlerProvider import com.emarsys.core.worker.Worker +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ConnectionTestUtils.checkConnection import com.emarsys.testUtil.DatabaseTestUtils.deleteCoreDatabase import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.ReflectionTestUtils +import com.emarsys.testUtil.RetryUtils import com.emarsys.testUtil.TestUrls.DENNA_ECHO import com.emarsys.testUtil.TestUrls.customResponse import com.emarsys.testUtil.mockito.ThreadSpy +import com.emarsys.testUtil.rules.RetryRule import io.kotest.matchers.shouldBe import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test - -import org.junitpioneer.jupiter.RetryingTest -import org.mockito.kotlin.* +import org.junit.Rule +import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.isNull +import org.mockito.kotlin.mock +import org.mockito.kotlin.timeout +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever import java.net.UnknownHostException import java.util.concurrent.CountDownLatch -class RequestManagerTest { +class RequestManagerTest : AnnotationSpec() { + + @Rule + @JvmField + val retryRule: RetryRule = RetryUtils.retryRule + private lateinit var manager: RequestManager private lateinit var requestModel: RequestModel private lateinit var shardModel: ShardModel @@ -66,8 +78,7 @@ class RequestManagerTest { private lateinit var callbackRegistryThreadSpy: ThreadSpy> private lateinit var shardRepositoryThreadSpy: ThreadSpy> - - @BeforeEach + @Before fun setUp() { deleteCoreDatabase() val requestModelMappers: MutableList> = mutableListOf() @@ -155,13 +166,13 @@ class RequestManagerTest { ) } - @AfterEach + @After fun tearDown() { concurrentHandlerHolder.coreLooper.quit() } @Test - @RetryingTest(3) + fun testSubmit_shouldAddRequestModelToQueue() { manager.submit( requestModel, @@ -173,7 +184,7 @@ class RequestManagerTest { } @Test - @RetryingTest(3) + fun testSubmit_withRequestModel_shouldInvokeRunOnTheWorker() { val worker = mock() ReflectionTestUtils.setInstanceField(manager, "worker", worker) @@ -185,7 +196,7 @@ class RequestManagerTest { } @Test - @RetryingTest(3) + fun testSubmit_withRequestModel_executesRunnableOn_CoreSDKHandlerThread() { runBlocking { withContext(Dispatchers.IO) { @@ -197,7 +208,7 @@ class RequestManagerTest { } @Test - @RetryingTest(3) + fun testSubmit_withRequestModel_Success() { whenever(mockConnectionWatchDog.isConnected).thenReturn(true, false) whenever(mockRequestRepository.isEmpty()).thenReturn(false, false, true) @@ -213,7 +224,7 @@ class RequestManagerTest { } @Test - @RetryingTest(3) + fun testSubmit_withRequestModel_shouldRegisterCallbackToRegistry() { val completionListener = mock() @@ -223,7 +234,7 @@ class RequestManagerTest { } @Test - @RetryingTest(3) + fun testSubmit_withRequestModel_shouldRegister_null_ToRegistryAsWell() { manager.submit(requestModel, null) @@ -232,7 +243,7 @@ class RequestManagerTest { @Test - @RetryingTest(3) + fun testSubmitNow_withoutCompletionHandler_shouldCallProxyProviderForCompletionHandler() { whenever(mockDelegatorCompletionHandlerProvider.provide(any(), any())).doReturn( mockDefaultHandler @@ -248,7 +259,7 @@ class RequestManagerTest { } @Test - @RetryingTest(3) + fun testSubmitNow_shouldCallProxyProviderForCompletionHandler() { manager.submitNow(requestModel, fakeCompletionHandler) verify(mockDelegatorCompletionHandlerProvider).provide( @@ -260,7 +271,7 @@ class RequestManagerTest { } @Test - @RetryingTest(3) + fun testSubmitNow_shouldCallProxyProviderForCompletionHandler_withScope() { val mockOtherHandler: Handler = mock() manager.submitNow(requestModel, fakeCompletionHandler, mockOtherHandler) @@ -273,14 +284,14 @@ class RequestManagerTest { } @Test - @RetryingTest(3) + fun testSubmitNow_shouldCallRestClientsExecuteWithGivenParameters() { manager.submitNow(requestModel, fakeCompletionHandler) verify(mockRestClient).execute(requestModel, mockDefaultHandler) } @Test - @RetryingTest(3) + fun testSubmitNow_shouldCallRestClient_withDefaultHandler() { manager.submitNow(requestModel) @@ -288,7 +299,7 @@ class RequestManagerTest { } @Test - @RetryingTest(3) + fun testError_callbackWithResponseContainsRequestModel() { requestModel = RequestModel.Builder(timestampProvider, uuidProvider).url(customResponse(405)) @@ -308,7 +319,7 @@ class RequestManagerTest { } @Test - @RetryingTest(3) + fun testError_withRequestModel_callbackWithException() { requestModel = RequestModel.Builder(timestampProvider, uuidProvider) .url("https://www.nosuchwebsite.emarsys.com").method(RequestMethod.GET).build() @@ -326,7 +337,7 @@ class RequestManagerTest { } @Test - @RetryingTest(3) + fun testSubmit_shouldAddShardModelToDatabase() { manager.submit(shardModel) runBlocking { @@ -335,7 +346,7 @@ class RequestManagerTest { } @Test - @RetryingTest(3) + fun testSubmit_withShardModel_executesRunnableOn_CoreSDKHandlerThread() { runBlocking { withContext(Dispatchers.IO) { diff --git a/core/src/androidTest/java/com/emarsys/core/request/RequestTaskTest.kt b/core/src/androidTest/java/com/emarsys/core/request/RequestTaskTest.kt index aea3e1ed..36b7efb1 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/RequestTaskTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/RequestTaskTest.kt @@ -3,12 +3,8 @@ package com.emarsys.core.request import com.emarsys.core.connection.ConnectionProvider import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.request.model.RequestModel - -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.fail - +import com.emarsys.testUtil.AnnotationSpec +import io.kotest.assertions.fail import org.mockito.kotlin.doReturn import org.mockito.kotlin.doThrow import org.mockito.kotlin.mock @@ -16,19 +12,18 @@ import org.mockito.kotlin.whenever import java.net.URL import javax.net.ssl.HttpsURLConnection -class RequestTaskTest { +class RequestTaskTest : AnnotationSpec() { private lateinit var connectionProvider: ConnectionProvider private lateinit var mockTimestampProvider: TimestampProvider - companion object { private const val WRONG_URL = "https://localhost/missing" private const val TIMESTAMP_1: Long = 600 private const val TIMESTAMP_2: Long = 1600 } - @BeforeEach + @Before fun setUp() { connectionProvider = ConnectionProvider() mockTimestampProvider = mock() diff --git a/core/src/androidTest/java/com/emarsys/core/request/RestClientTest.kt b/core/src/androidTest/java/com/emarsys/core/request/RestClientTest.kt index d867ab27..c59c81a8 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/RestClientTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/RestClientTest.kt @@ -13,15 +13,12 @@ import com.emarsys.core.request.model.RequestResult import com.emarsys.core.request.model.asRequestResult import com.emarsys.core.response.ResponseHandlersProcessor import com.emarsys.core.testUtil.RequestModelTestUtils +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ConnectionTestUtils import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.TestUrls import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -29,7 +26,7 @@ import org.mockito.kotlin.verify import java.net.UnknownHostException import java.util.concurrent.CountDownLatch -class RestClientTest { +class RestClientTest : AnnotationSpec() { private lateinit var client: RestClient private lateinit var latch: CountDownLatch @@ -43,7 +40,7 @@ class RestClientTest { @Suppress("UNCHECKED_CAST") - @BeforeEach + @Before fun setup() { ConnectionTestUtils.checkConnection(InstrumentationRegistry.getTargetContext()) diff --git a/core/src/androidTest/java/com/emarsys/core/request/factory/CoreCompletionHandlerMiddlewareProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/request/factory/CoreCompletionHandlerMiddlewareProviderTest.kt index 579edf94..60c8db0d 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/factory/CoreCompletionHandlerMiddlewareProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/factory/CoreCompletionHandlerMiddlewareProviderTest.kt @@ -9,19 +9,17 @@ import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel import com.emarsys.core.worker.CoreCompletionHandlerMiddleware import com.emarsys.core.worker.Worker +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.should import io.kotest.matchers.types.beInstanceOf -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.verify import java.util.concurrent.CountDownLatch -class CoreCompletionHandlerMiddlewareProviderTest { - +class CoreCompletionHandlerMiddlewareProviderTest : AnnotationSpec() { private lateinit var mockRequestRepository: Repository @@ -34,7 +32,7 @@ class CoreCompletionHandlerMiddlewareProviderTest { private lateinit var latch: CountDownLatch private lateinit var runnableFactory: RunnableFactory - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun setUp() { latch = CountDownLatch(1) diff --git a/core/src/androidTest/java/com/emarsys/core/request/model/CompositeRequestModelTest.kt b/core/src/androidTest/java/com/emarsys/core/request/model/CompositeRequestModelTest.kt index 46451e05..4a062c41 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/model/CompositeRequestModelTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/model/CompositeRequestModelTest.kt @@ -2,13 +2,12 @@ package com.emarsys.core.request.model import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import java.net.URL -class CompositeRequestModelTest { +class CompositeRequestModelTest : AnnotationSpec() { private companion object { const val TIMESTAMP = 800L @@ -26,7 +25,7 @@ class CompositeRequestModelTest { private lateinit var payload: Map private lateinit var headers: Map - @BeforeEach + @Before fun setUp() { payload = createPayload() headers = createHeaders() diff --git a/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelRepositoryTest.kt b/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelRepositoryTest.kt index 8fc2b1d7..56fe5077 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelRepositoryTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelRepositoryTest.kt @@ -16,18 +16,17 @@ import com.emarsys.core.database.helper.CoreDbHelper import com.emarsys.core.database.repository.specification.Everything import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.util.serialization.SerializationUtils +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils.deleteCoreDatabase import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe import org.json.JSONException -import org.junit.jupiter.api.Assertions -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test +import org.junit.Assert import org.mockito.Mockito import java.util.* -class RequestModelRepositoryTest { +class RequestModelRepositoryTest : AnnotationSpec() { companion object { @@ -49,7 +48,7 @@ class RequestModelRepositoryTest { private var headers: HashMap? = null private var payload: HashMap? = null - @BeforeEach + @Before fun init() { deleteCoreDatabase() context = getTargetContext() @@ -72,21 +71,21 @@ class RequestModelRepositoryTest { result.getAsString(REQUEST_COLUMN_NAME_REQUEST_ID) shouldBe request!!.id result.getAsString(REQUEST_COLUMN_NAME_METHOD) shouldBe request!!.method.name result.getAsString(REQUEST_COLUMN_NAME_URL) shouldBe request!!.url.toString() - Assertions.assertArrayEquals( + Assert.assertArrayEquals( SerializationUtils.serializableToBlob( request!!.headers ), result.getAsByteArray(REQUEST_COLUMN_NAME_HEADERS) ) - Assertions.assertArrayEquals( + Assert.assertArrayEquals( SerializationUtils.serializableToBlob( request!!.payload ), result.getAsByteArray(REQUEST_COLUMN_NAME_PAYLOAD) ) - Assertions.assertEquals( + Assert.assertEquals( request!!.timestamp, result.getAsLong(REQUEST_COLUMN_NAME_TIMESTAMP) as Long ) - Assertions.assertEquals(request!!.ttl, result.getAsLong(REQUEST_COLUMN_NAME_TTL) as Long) + Assert.assertEquals(request!!.ttl, result.getAsLong(REQUEST_COLUMN_NAME_TTL) as Long) } @Test diff --git a/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelTest.kt b/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelTest.kt index 7cb8155a..e04a6e0b 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/model/RequestModelTest.kt @@ -3,19 +3,15 @@ package com.emarsys.core.request.model import android.net.Uri import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe - -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito import java.net.URL import java.util.* -class RequestModelTest { +class RequestModelTest : AnnotationSpec() { private lateinit var url: String private lateinit var method: RequestMethod private lateinit var payload: Map @@ -27,7 +23,7 @@ class RequestModelTest { private lateinit var uuidProvider: UUIDProvider - @BeforeEach + @Before fun init() { url = "https://google.com" method = RequestMethod.PUT diff --git a/core/src/androidTest/java/com/emarsys/core/request/model/specification/FilterByUrlPatternTest.kt b/core/src/androidTest/java/com/emarsys/core/request/model/specification/FilterByUrlPatternTest.kt index 1529ffd0..33b20f16 100644 --- a/core/src/androidTest/java/com/emarsys/core/request/model/specification/FilterByUrlPatternTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/request/model/specification/FilterByUrlPatternTest.kt @@ -8,18 +8,16 @@ import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.request.model.RequestModel import com.emarsys.core.request.model.RequestModelRepository +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.collections.shouldContainAll import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test - -class FilterByUrlPatternTest { +class FilterByUrlPatternTest : AnnotationSpec() { private lateinit var specification: FilterByUrlPattern @@ -28,7 +26,7 @@ class FilterByUrlPatternTest { private lateinit var timestampProvider: TimestampProvider private lateinit var uuidProvider: UUIDProvider - @BeforeEach + @Before fun init() { DatabaseTestUtils.deleteCoreDatabase() pattern = "root/___/_%/event" diff --git a/core/src/androidTest/java/com/emarsys/core/resource/MetaDataReaderTest.kt b/core/src/androidTest/java/com/emarsys/core/resource/MetaDataReaderTest.kt index 1be90226..64acc55e 100644 --- a/core/src/androidTest/java/com/emarsys/core/resource/MetaDataReaderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/resource/MetaDataReaderTest.kt @@ -3,18 +3,17 @@ package com.emarsys.core.resource import android.content.Context import android.content.pm.ApplicationInfo import android.os.Bundle +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.ArgumentMatchers import org.mockito.Mockito -class MetaDataReaderTest { +class MetaDataReaderTest : AnnotationSpec() { private var reader: MetaDataReader? = null - @BeforeEach + @Before @Throws(Exception::class) fun setUp() { reader = MetaDataReader() diff --git a/core/src/androidTest/java/com/emarsys/core/response/AbstractResponseHandlerTest.kt b/core/src/androidTest/java/com/emarsys/core/response/AbstractResponseHandlerTest.kt index 760c2ae8..0ba0947d 100644 --- a/core/src/androidTest/java/com/emarsys/core/response/AbstractResponseHandlerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/response/AbstractResponseHandlerTest.kt @@ -1,7 +1,6 @@ package com.emarsys.core.response -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test +import com.emarsys.testUtil.AnnotationSpec import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -9,11 +8,11 @@ import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever -class AbstractResponseHandlerTest { +class AbstractResponseHandlerTest : AnnotationSpec() { private lateinit var abstractResponseHandler: AbstractResponseHandler - @BeforeEach + @Before fun init() { abstractResponseHandler = mock() } diff --git a/core/src/androidTest/java/com/emarsys/core/response/ResponseHandlersProcessorTest.kt b/core/src/androidTest/java/com/emarsys/core/response/ResponseHandlersProcessorTest.kt index 6b7b8f85..94560e2a 100644 --- a/core/src/androidTest/java/com/emarsys/core/response/ResponseHandlersProcessorTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/response/ResponseHandlersProcessorTest.kt @@ -1,20 +1,17 @@ package com.emarsys.core.response +import com.emarsys.testUtil.AnnotationSpec import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.collections.shouldContainAll -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito.inOrder import org.mockito.Mockito.mock -class ResponseHandlersProcessorTest { +class ResponseHandlersProcessorTest : AnnotationSpec() { private lateinit var responseHandlersProcessor: ResponseHandlersProcessor - @BeforeEach + @Before fun setUp() { responseHandlersProcessor = ResponseHandlersProcessor() } diff --git a/core/src/androidTest/java/com/emarsys/core/response/ResponseModelTest.kt b/core/src/androidTest/java/com/emarsys/core/response/ResponseModelTest.kt index da27a7f5..dca8cb5f 100644 --- a/core/src/androidTest/java/com/emarsys/core/response/ResponseModelTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/response/ResponseModelTest.kt @@ -1,22 +1,18 @@ package com.emarsys.core.response + import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.request.model.RequestModel +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe import org.json.JSONException import org.json.JSONObject - - -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import java.net.HttpCookie import java.util.* -class ResponseModelTest { +class ResponseModelTest : AnnotationSpec() { companion object { private const val timestamp: Long = 4200 @@ -32,7 +28,7 @@ class ResponseModelTest { private lateinit var mockRequestModel: RequestModel - @BeforeEach + @Before fun init() { statusCode = 200 message = "OK" diff --git a/core/src/androidTest/java/com/emarsys/core/shard/ShardModelRepositoryTest.kt b/core/src/androidTest/java/com/emarsys/core/shard/ShardModelRepositoryTest.kt index 1c871d39..6d227c31 100644 --- a/core/src/androidTest/java/com/emarsys/core/shard/ShardModelRepositoryTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/shard/ShardModelRepositoryTest.kt @@ -11,20 +11,16 @@ import com.emarsys.core.database.DatabaseContract.SHARD_COLUMN_TYPE import com.emarsys.core.database.helper.CoreDbHelper import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.util.serialization.SerializationUtils.serializableToBlob +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Assertions - -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - +import org.junit.Assert import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import java.io.Serializable -class ShardModelRepositoryTest { +class ShardModelRepositoryTest : AnnotationSpec() { private lateinit var shardModel: ShardModel private lateinit var repository: ShardModelRepository @@ -39,7 +35,7 @@ class ShardModelRepositoryTest { const val SHARD_ID = "shard_id" } - @BeforeEach + @Before fun init() { DatabaseTestUtils.deleteCoreDatabase() context = InstrumentationRegistry.getTargetContext() @@ -63,7 +59,7 @@ class ShardModelRepositoryTest { result.getAsString(SHARD_COLUMN_TYPE) shouldBe shardModel.type result.getAsLong(SHARD_COLUMN_TIMESTAMP) shouldBe shardModel.timestamp result.getAsLong(SHARD_COLUMN_TTL) shouldBe shardModel.ttl - Assertions.assertArrayEquals( + Assert.assertArrayEquals( serializableToBlob(shardModel.data), result.getAsByteArray(SHARD_COLUMN_DATA) ) diff --git a/core/src/androidTest/java/com/emarsys/core/shard/ShardModelTest.kt b/core/src/androidTest/java/com/emarsys/core/shard/ShardModelTest.kt index 83c63045..f4caf504 100644 --- a/core/src/androidTest/java/com/emarsys/core/shard/ShardModelTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/shard/ShardModelTest.kt @@ -2,14 +2,13 @@ package com.emarsys.core.shard import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider +import com.emarsys.testUtil.AnnotationSpec import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito.mock import org.mockito.Mockito.`when` -class ShardModelTest { +class ShardModelTest : AnnotationSpec() { companion object { const val ID = "shard_id" @@ -24,7 +23,7 @@ class ShardModelTest { private lateinit var payload: Map - @BeforeEach + @Before fun init() { payload = createPayload() timestampProvider = mock(TimestampProvider::class.java) diff --git a/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardIdsTest.kt b/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardIdsTest.kt index 098410bd..f3fe97ec 100644 --- a/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardIdsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardIdsTest.kt @@ -7,17 +7,15 @@ import com.emarsys.core.database.repository.specification.Everything import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.shard.ShardModel import com.emarsys.core.shard.ShardModelRepository +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test - -class FilterByShardIdsTest { +class FilterByShardIdsTest : AnnotationSpec() { private lateinit var context: Context private lateinit var originalShardList: List @@ -25,7 +23,7 @@ class FilterByShardIdsTest { private lateinit var concurrentHadlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun init() { DatabaseTestUtils.deleteCoreDatabase() context = InstrumentationRegistry.getTargetContext().applicationContext diff --git a/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardTypeTest.kt b/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardTypeTest.kt index 7864e494..77effc86 100644 --- a/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardTypeTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/shard/specification/FilterByShardTypeTest.kt @@ -6,17 +6,15 @@ import com.emarsys.core.database.repository.specification.Everything import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.shard.ShardModel import com.emarsys.core.shard.ShardModelRepository +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test - -class FilterByShardTypeTest { +class FilterByShardTypeTest : AnnotationSpec() { companion object { @@ -28,7 +26,7 @@ class FilterByShardTypeTest { private lateinit var repository: ShardModelRepository private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun setUp() { DatabaseTestUtils.deleteCoreDatabase() specification = FilterByShardType(TYPE) diff --git a/core/src/androidTest/java/com/emarsys/core/storage/AbstractStorageTest.kt b/core/src/androidTest/java/com/emarsys/core/storage/AbstractStorageTest.kt index d747a600..601a14d7 100644 --- a/core/src/androidTest/java/com/emarsys/core/storage/AbstractStorageTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/storage/AbstractStorageTest.kt @@ -1,20 +1,17 @@ package com.emarsys.core.storage import android.content.SharedPreferences +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ReflectionTestUtils import com.emarsys.testUtil.mockito.whenever import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito.CALLS_REAL_METHODS import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify -class AbstractStorageTest { +class AbstractStorageTest : AnnotationSpec() { private companion object { const val VALUE = "value" } @@ -23,7 +20,7 @@ class AbstractStorageTest { private lateinit var mockStorage: AbstractStorage - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun setUp() { mockSharedPreferences = mock() diff --git a/core/src/androidTest/java/com/emarsys/core/storage/BooleanStorageTest.kt b/core/src/androidTest/java/com/emarsys/core/storage/BooleanStorageTest.kt index dfa167a7..c0674658 100644 --- a/core/src/androidTest/java/com/emarsys/core/storage/BooleanStorageTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/storage/BooleanStorageTest.kt @@ -1,17 +1,16 @@ package com.emarsys.core.storage import android.content.SharedPreferences +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.assertions.throwables.shouldThrow -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito.anyBoolean import org.mockito.Mockito.anyString import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.mockito.Mockito.verifyNoMoreInteractions -class BooleanStorageTest { +class BooleanStorageTest : AnnotationSpec() { private companion object { const val VALUE = true @@ -24,7 +23,7 @@ class BooleanStorageTest { private lateinit var storageKey: StorageKey - @BeforeEach + @Before fun setUp() { storageKey = mock(StorageKey::class.java).apply { whenever(key).thenReturn(KEY) diff --git a/core/src/androidTest/java/com/emarsys/core/storage/CoreStorageKeyTest.kt b/core/src/androidTest/java/com/emarsys/core/storage/CoreStorageKeyTest.kt index 32fff1f9..0ada8592 100644 --- a/core/src/androidTest/java/com/emarsys/core/storage/CoreStorageKeyTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/storage/CoreStorageKeyTest.kt @@ -1,13 +1,13 @@ package com.emarsys.core.storage +import com.emarsys.testUtil.AnnotationSpec import io.kotest.data.forAll import io.kotest.data.row import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.Test -class CoreStorageKeyTest { +class CoreStorageKeyTest : AnnotationSpec() { @Test diff --git a/core/src/androidTest/java/com/emarsys/core/storage/DefaultKeyValueStoreTest.kt b/core/src/androidTest/java/com/emarsys/core/storage/DefaultKeyValueStoreTest.kt index 2bfd8d94..66ff0029 100644 --- a/core/src/androidTest/java/com/emarsys/core/storage/DefaultKeyValueStoreTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/storage/DefaultKeyValueStoreTest.kt @@ -3,16 +3,14 @@ package com.emarsys.core.storage import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.Assertions -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test +import org.junit.Assert -class DefaultKeyValueStoreTest { +class DefaultKeyValueStoreTest : AnnotationSpec() { companion object { private const val KEY = "key" private const val DELTA = 0.001 @@ -28,7 +26,7 @@ class DefaultKeyValueStoreTest { private lateinit var store: DefaultKeyValueStore private lateinit var prefs: SharedPreferences - @BeforeEach + @Before @SuppressLint("ApplySharedPref") fun init() { prefs = InstrumentationRegistry.getTargetContext() @@ -38,7 +36,7 @@ class DefaultKeyValueStoreTest { store = DefaultKeyValueStore(prefs) } - @AfterEach + @After fun tearDown() { prefs.edit().clear().commit() } @@ -170,13 +168,13 @@ class DefaultKeyValueStoreTest { fun test_put_get_float_shouldStoreValue() { store.putFloat(KEY, 2.4f) store - Assertions.assertEquals(2.4f, store.getFloat(KEY), DELTA.toFloat()) + Assert.assertEquals(2.4f, store.getFloat(KEY), DELTA.toFloat()) } @Test fun test_put_get_double_shouldStoreValue() { store.putDouble(KEY, 0.2) - Assertions.assertEquals(0.2, store.getDouble(KEY), DELTA) + Assert.assertEquals(0.2, store.getDouble(KEY), DELTA) } @Test @@ -187,11 +185,11 @@ class DefaultKeyValueStoreTest { store.putDouble(KEY4, java.lang.Double.POSITIVE_INFINITY) store.putDouble(KEY5, java.lang.Double.NEGATIVE_INFINITY) - Assertions.assertEquals(java.lang.Double.MAX_VALUE, store.getDouble(KEY1), DELTA) - Assertions.assertEquals(java.lang.Double.MIN_VALUE, store.getDouble(KEY2), DELTA) - Assertions.assertEquals(java.lang.Double.NaN, store.getDouble(KEY3), DELTA) - Assertions.assertEquals(java.lang.Double.POSITIVE_INFINITY, store.getDouble(KEY4), DELTA) - Assertions.assertEquals(java.lang.Double.NEGATIVE_INFINITY, store.getDouble(KEY5), DELTA) + Assert.assertEquals(java.lang.Double.MAX_VALUE, store.getDouble(KEY1), DELTA) + Assert.assertEquals(java.lang.Double.MIN_VALUE, store.getDouble(KEY2), DELTA) + Assert.assertEquals(java.lang.Double.NaN, store.getDouble(KEY3), DELTA) + Assert.assertEquals(java.lang.Double.POSITIVE_INFINITY, store.getDouble(KEY4), DELTA) + Assert.assertEquals(java.lang.Double.NEGATIVE_INFINITY, store.getDouble(KEY5), DELTA) } @Test @@ -212,10 +210,10 @@ class DefaultKeyValueStoreTest { store.getLong(KEY) shouldBe 88111 store.putFloat(KEY, 765.23f) - Assertions.assertEquals(765.23f, store.getFloat(KEY), DELTA.toFloat()) + Assert.assertEquals(765.23f, store.getFloat(KEY), DELTA.toFloat()) store.putDouble(KEY, 0.03013) - Assertions.assertEquals(0.03013, store.getDouble(KEY), DELTA) + Assert.assertEquals(0.03013, store.getDouble(KEY), DELTA) store.putBoolean(KEY, true) store.getBoolean(KEY) shouldBe true @@ -237,11 +235,11 @@ class DefaultKeyValueStoreTest { store.putFloat(KEY4, 44.2f) store.remove(KEY4) - Assertions.assertEquals(0.0f, store.getFloat(KEY4), DELTA.toFloat()) + Assert.assertEquals(0.0f, store.getFloat(KEY4), DELTA.toFloat()) store.putDouble(KEY5, 120120.0301) store.remove(KEY5) - Assertions.assertEquals(0.0, store.getDouble(KEY5), DELTA) + Assert.assertEquals(0.0, store.getDouble(KEY5), DELTA) store.putBoolean(KEY6, true) store.remove(KEY6) diff --git a/core/src/androidTest/java/com/emarsys/core/storage/SecureSharedPreferencesProviderTest.kt b/core/src/androidTest/java/com/emarsys/core/storage/SecureSharedPreferencesProviderTest.kt index c0df4afc..4dfc3af2 100644 --- a/core/src/androidTest/java/com/emarsys/core/storage/SecureSharedPreferencesProviderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/storage/SecureSharedPreferencesProviderTest.kt @@ -3,15 +3,13 @@ package com.emarsys.core.storage import android.content.Context import android.content.Context.MODE_PRIVATE import android.content.SharedPreferences +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test - -class SecureSharedPreferencesProviderTest { +class SecureSharedPreferencesProviderTest : AnnotationSpec() { private lateinit var sharedPreferencesProvider: SecureSharedPreferencesProvider @@ -19,7 +17,7 @@ class SecureSharedPreferencesProviderTest { private lateinit var context: Context private lateinit var oldSharedPrefs: SharedPreferences - @BeforeEach + @Before fun setUp() { context = InstrumentationRegistry.getTargetContext().applicationContext oldSharedPrefs = context.getSharedPreferences("test_shared_prefs", MODE_PRIVATE) diff --git a/core/src/androidTest/java/com/emarsys/core/storage/StringStorageTest.kt b/core/src/androidTest/java/com/emarsys/core/storage/StringStorageTest.kt index bcea4ae0..62d734ff 100644 --- a/core/src/androidTest/java/com/emarsys/core/storage/StringStorageTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/storage/StringStorageTest.kt @@ -1,16 +1,15 @@ package com.emarsys.core.storage import android.content.SharedPreferences +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.assertions.throwables.shouldThrow -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito.anyString import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.mockito.Mockito.verifyNoMoreInteractions -class StringStorageTest { +class StringStorageTest : AnnotationSpec() { private companion object { const val VALUE = "value" @@ -23,7 +22,7 @@ class StringStorageTest { private lateinit var storageKey: StorageKey - @BeforeEach + @Before fun setUp() { storageKey = mock(StorageKey::class.java).apply { whenever(key).thenReturn(KEY) diff --git a/core/src/androidTest/java/com/emarsys/core/testUtil/RequestModelTestUtils.kt b/core/src/androidTest/java/com/emarsys/core/testUtil/RequestModelTestUtils.kt index b7ff1893..a78ac99f 100644 --- a/core/src/androidTest/java/com/emarsys/core/testUtil/RequestModelTestUtils.kt +++ b/core/src/androidTest/java/com/emarsys/core/testUtil/RequestModelTestUtils.kt @@ -1,10 +1,10 @@ package com.emarsys.core.testUtil +import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.request.model.RequestMethod +import com.emarsys.core.request.model.RequestMethod.GET import com.emarsys.core.request.model.RequestModel -import com.emarsys.core.provider.timestamp.TimestampProvider -import com.emarsys.core.request.model.RequestMethod.* import com.emarsys.testUtil.TestUrls object RequestModelTestUtils { diff --git a/core/src/androidTest/java/com/emarsys/core/util/AssertTest.kt b/core/src/androidTest/java/com/emarsys/core/util/AssertTest.kt index 81a90a6a..b7ce2555 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/AssertTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/AssertTest.kt @@ -1,12 +1,12 @@ package com.emarsys.core.util +import com.emarsys.testUtil.AnnotationSpec +import io.kotest.assertions.fail import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.fail -class AssertTest { +class AssertTest : AnnotationSpec() { @Test diff --git a/core/src/androidTest/java/com/emarsys/core/util/DatabaseUtilTest.kt b/core/src/androidTest/java/com/emarsys/core/util/DatabaseUtilTest.kt index 2e49a831..3b4de19a 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/DatabaseUtilTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/DatabaseUtilTest.kt @@ -1,11 +1,11 @@ package com.emarsys.core.util +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test -class DatabaseUtilTest { +class DatabaseUtilTest : AnnotationSpec() { @Test diff --git a/core/src/androidTest/java/com/emarsys/core/util/ExceptionExtensionsKtTest.kt b/core/src/androidTest/java/com/emarsys/core/util/ExceptionExtensionsKtTest.kt index b6ed282a..800839af 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/ExceptionExtensionsKtTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/ExceptionExtensionsKtTest.kt @@ -1,9 +1,9 @@ package com.emarsys.core.util +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test -class ExceptionExtensionsKtTest { +class ExceptionExtensionsKtTest : AnnotationSpec() { @Test fun testRootCause_shouldReturn_withTheRootCauseOfTheException() { diff --git a/core/src/androidTest/java/com/emarsys/core/util/FileDownloaderTest.kt b/core/src/androidTest/java/com/emarsys/core/util/FileDownloaderTest.kt index f4c0f85c..74dd3b19 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/FileDownloaderTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/FileDownloaderTest.kt @@ -3,59 +3,62 @@ package com.emarsys.core.util import android.content.Context import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.FileTestUtils import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext +import com.emarsys.testUtil.RetryUtils import com.emarsys.testUtil.TestUrls.LARGE_IMAGE import com.emarsys.testUtil.TestUrls.customResponse +import com.emarsys.testUtil.rules.RetryRule import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe - -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test -import org.junitpioneer.jupiter.RetryingTest - +import org.junit.Rule import java.io.ByteArrayOutputStream import java.io.File import java.io.FileInputStream import java.io.InputStream -import java.util.* +import java.util.Arrays +import java.util.UUID import java.util.concurrent.CountDownLatch -class FileDownloaderTest { +class FileDownloaderTest : AnnotationSpec() { + + @Rule + @JvmField + val retryRule: RetryRule = RetryUtils.retryRule private lateinit var context: Context private lateinit var fileDownloader: FileDownloader - @BeforeEach + @Before fun setUp() { context = getTargetContext() fileDownloader = FileDownloader(context) } @Test - @RetryingTest(3) + fun testDownload_shouldNotReturnNull_whenUrlIsCorrect() { fileDownloader.download(LARGE_IMAGE) shouldNotBe null } @Test - @RetryingTest(3) + fun testDownload_shouldReturnNull_whenSchemeIsNotHttps() { fileDownloader.download("little://cat") shouldBe null } @Test - @RetryingTest(3) + fun testDownload_shouldReturnNull_whenResourceDoesNotExist() { val result = fileDownloader.download(customResponse(404)) result shouldBe null } @Test - @RetryingTest(3) + fun testDownload_returnedPathShouldExist() { val filePath = fileDownloader.download(LARGE_IMAGE) val file = File(filePath!!) @@ -63,7 +66,7 @@ class FileDownloaderTest { } @Test - @RetryingTest(3) + fun testDownload_downloadedAndRemoteFileShouldBeTheSame() { val latch = CountDownLatch(1) val concurrentHandlerHolder: ConcurrentHandlerHolder = @@ -91,7 +94,7 @@ class FileDownloaderTest { } @Test - @RetryingTest(3) + fun testDelete_shouldDeleteTheFile() { val filePath = createTempFile() val file = File(filePath) @@ -108,7 +111,7 @@ class FileDownloaderTest { } @Test - @RetryingTest(3) + fun testWriteReadFileIntoString() { val cacheFolder = context.cacheDir val fileName = UUID.randomUUID().toString() @@ -119,7 +122,7 @@ class FileDownloaderTest { } @Test - @RetryingTest(3) + fun testReadURLIntoString() { fileDownloader.download(LARGE_IMAGE)?.let { val expected = fileDownloader.readFileIntoString(it) diff --git a/core/src/androidTest/java/com/emarsys/core/util/HeaderUtilsInstrumentationTest.kt b/core/src/androidTest/java/com/emarsys/core/util/HeaderUtilsInstrumentationTest.kt index 83867167..16330e65 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/HeaderUtilsInstrumentationTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/HeaderUtilsInstrumentationTest.kt @@ -1,10 +1,10 @@ package com.emarsys.core.util +import com.emarsys.testUtil.AnnotationSpec import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test -class HeaderUtilsInstrumentationTest { +class HeaderUtilsInstrumentationTest : AnnotationSpec() { private val username = "user" @Test diff --git a/core/src/androidTest/java/com/emarsys/core/util/ImageUtilsTest.kt b/core/src/androidTest/java/com/emarsys/core/util/ImageUtilsTest.kt index e4036ef0..575d50ad 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/ImageUtilsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/ImageUtilsTest.kt @@ -6,16 +6,15 @@ import com.emarsys.core.device.LanguageProvider import com.emarsys.core.notification.NotificationManagerHelper import com.emarsys.core.provider.hardwareid.HardwareIdProvider import com.emarsys.core.provider.version.VersionProvider +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext +import com.emarsys.testUtil.RetryUtils import com.emarsys.testUtil.copyInputStreamToFile +import com.emarsys.testUtil.rules.RetryRule import io.kotest.matchers.comparables.shouldBeLessThan import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test -import org.junitpioneer.jupiter.RetryingTest - +import org.junit.Rule import org.mockito.Mockito import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer @@ -23,7 +22,11 @@ import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import java.io.File -class ImageUtilsTest { +class ImageUtilsTest : AnnotationSpec() { + + @Rule + @JvmField + val retryRule: RetryRule = RetryUtils.retryRule private companion object { const val IMAGE_URL = "https://emarsys.com" @@ -36,7 +39,7 @@ class ImageUtilsTest { private lateinit var mockVersionProvider: VersionProvider - @BeforeEach + @Before fun setup() { mockFileDownloader = mock { on { download(any(), any()) } doAnswer { @@ -79,13 +82,13 @@ class ImageUtilsTest { @Test - @RetryingTest(3) + fun testLoadOptimizedBitmap_returnsNull_whenImageUrlIsNull() { ImageUtils.loadOptimizedBitmap(mockFileDownloader, null, deviceInfo) shouldBe null } @Test - @RetryingTest(3) + fun testLoadOptimizedBitmap_withRemoteUrl_CleansUpTempFile() { clearCache() getTargetContext().cacheDir.list()?.size shouldBe 0 @@ -94,7 +97,7 @@ class ImageUtilsTest { } @Test - @RetryingTest(3) + fun testLoadOptimizedBitmap_withLocalFile_ShouldNotCleanUpLocalFile() { clearCache() val fileUrl = mockFileDownloader.download(IMAGE_URL) @@ -110,7 +113,7 @@ class ImageUtilsTest { } @Test - @RetryingTest(3) + fun testLoadOptimizedBitmap_withRemoteUrl() { val bitmap = ImageUtils.loadOptimizedBitmap(mockFileDownloader, IMAGE_URL, deviceInfo) bitmap shouldNotBe null @@ -119,7 +122,7 @@ class ImageUtilsTest { } @Test - @RetryingTest(3) + fun testCalculateInSampleSize_returnedValueShouldBe4_whenRequestedWidthIs1080_widthIs2500() { val options = BitmapFactory.Options().apply { outWidth = 2500 diff --git a/core/src/androidTest/java/com/emarsys/core/util/JsonUtilsTest.kt b/core/src/androidTest/java/com/emarsys/core/util/JsonUtilsTest.kt index 4f0e389e..89afaeb3 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/JsonUtilsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/JsonUtilsTest.kt @@ -1,22 +1,20 @@ package com.emarsys.core.util + import com.emarsys.core.util.JsonUtils.fromList import com.emarsys.core.util.JsonUtils.fromMap import com.emarsys.core.util.JsonUtils.merge import com.emarsys.core.util.JsonUtils.toFlatMap import com.emarsys.core.util.JsonUtils.toFlatMapIncludingNulls +import com.emarsys.testUtil.AnnotationSpec import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import org.json.JSONArray import org.json.JSONException import org.json.JSONObject - - -import org.junit.jupiter.api.Test - import java.util.* -class JsonUtilsTest { +class JsonUtilsTest : AnnotationSpec() { private companion object { const val KEY_1 = "key1" diff --git a/core/src/androidTest/java/com/emarsys/core/util/MapExtensionsKtTest.kt b/core/src/androidTest/java/com/emarsys/core/util/MapExtensionsKtTest.kt index afd700a5..1d437822 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/MapExtensionsKtTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/MapExtensionsKtTest.kt @@ -1,13 +1,14 @@ package com.emarsys.core.util +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test -class MapExtensionsKtTest { +class MapExtensionsKtTest : AnnotationSpec() { @Test fun testGetCaseInsensitive() { - val map: Map = mapOf("KeY0" to "Value0", "KeY1" to "Value1", "key2" to "Value2") + val map: Map = + mapOf("KeY0" to "Value0", "KeY1" to "Value1", "key2" to "Value2") val result = map.getCaseInsensitive("key1") result shouldBe "Value1" diff --git a/core/src/androidTest/java/com/emarsys/core/util/RequestModelUtilsTest.kt b/core/src/androidTest/java/com/emarsys/core/util/RequestModelUtilsTest.kt index 1e01012b..01da1fa3 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/RequestModelUtilsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/RequestModelUtilsTest.kt @@ -3,13 +3,12 @@ package com.emarsys.core.util import com.emarsys.core.request.model.CompositeRequestModel import com.emarsys.core.request.model.RequestMethod import com.emarsys.core.request.model.RequestModel +import com.emarsys.testUtil.AnnotationSpec import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test - -class RequestModelUtilsTest { +class RequestModelUtilsTest : AnnotationSpec() { @Test diff --git a/core/src/androidTest/java/com/emarsys/core/util/SerializationUtilsTest.kt b/core/src/androidTest/java/com/emarsys/core/util/SerializationUtilsTest.kt index 0a2ccede..eaa55f68 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/SerializationUtilsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/SerializationUtilsTest.kt @@ -3,10 +3,10 @@ package com.emarsys.core.util import com.emarsys.core.request.model.RequestMethod import com.emarsys.core.request.model.RequestModel import com.emarsys.core.util.serialization.SerializationUtils +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test -class SerializationUtilsTest { +class SerializationUtilsTest : AnnotationSpec() { @Test fun testSerialization() { val payload = HashMap() diff --git a/core/src/androidTest/java/com/emarsys/core/util/SystemUtilsTest.kt b/core/src/androidTest/java/com/emarsys/core/util/SystemUtilsTest.kt index c821165d..23cf413a 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/SystemUtilsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/SystemUtilsTest.kt @@ -1,11 +1,10 @@ package com.emarsys.core.util +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test - -class SystemUtilsTest { +class SystemUtilsTest : AnnotationSpec() { @Test diff --git a/core/src/androidTest/java/com/emarsys/core/util/TimestampUtilsTest.kt b/core/src/androidTest/java/com/emarsys/core/util/TimestampUtilsTest.kt index a64c41f8..f6bf4baf 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/TimestampUtilsTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/TimestampUtilsTest.kt @@ -5,17 +5,16 @@ import com.emarsys.core.device.LanguageProvider import com.emarsys.core.notification.NotificationManagerHelper import com.emarsys.core.provider.hardwareid.HardwareIdProvider import com.emarsys.core.provider.version.VersionProvider +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import java.text.SimpleDateFormat import java.util.TimeZone -class TimestampUtilsTest { +class TimestampUtilsTest : AnnotationSpec() { companion object { private const val HARDWARE_ID = "hwid" @@ -29,7 +28,7 @@ class TimestampUtilsTest { private lateinit var mockNotificationManagerHelper: NotificationManagerHelper - @BeforeEach + @Before fun setup() { mockHardwareIdProvider = mock { on { provideHardwareId() } doReturn HARDWARE_ID diff --git a/core/src/androidTest/java/com/emarsys/core/util/batch/BatchingShardTriggerTest.kt b/core/src/androidTest/java/com/emarsys/core/util/batch/BatchingShardTriggerTest.kt index 2ae5cde9..0d910483 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/batch/BatchingShardTriggerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/batch/BatchingShardTriggerTest.kt @@ -11,10 +11,9 @@ import com.emarsys.core.shard.specification.FilterByShardIds import com.emarsys.core.util.batch.BatchingShardTrigger.RequestStrategy.PERSISTENT import com.emarsys.core.util.batch.BatchingShardTrigger.RequestStrategy.TRANSIENT import com.emarsys.core.util.predicate.Predicate +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito import org.mockito.kotlin.any import org.mockito.kotlin.doReturn @@ -24,7 +23,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.verifyNoMoreInteractions -class BatchingShardTriggerTest { +class BatchingShardTriggerTest : AnnotationSpec() { private lateinit var mockRepository: Repository private lateinit var mockPredicate: Predicate> @@ -35,7 +34,7 @@ class BatchingShardTriggerTest { private lateinit var mockConnectionWatchDog: ConnectionWatchDog - @BeforeEach + @Before fun setUp() { mockRepository = mock() mockPredicate = mock { diff --git a/core/src/androidTest/java/com/emarsys/core/util/batch/ListChunkerTest.kt b/core/src/androidTest/java/com/emarsys/core/util/batch/ListChunkerTest.kt index df93fd3c..55e4bb98 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/batch/ListChunkerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/batch/ListChunkerTest.kt @@ -1,21 +1,17 @@ package com.emarsys.core.util.batch import com.emarsys.core.shard.ShardModel +import com.emarsys.testUtil.AnnotationSpec import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe - -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito.mock -class ListChunkerTest { +class ListChunkerTest : AnnotationSpec() { private lateinit var chunker: ListChunker - @BeforeEach + @Before fun init() { chunker = ListChunker(1) } diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/LogShardListMergerTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/LogShardListMergerTest.kt index 03244051..859e74cc 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/LogShardListMergerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/LogShardListMergerTest.kt @@ -6,20 +6,16 @@ import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.request.model.RequestMethod import com.emarsys.core.request.model.RequestModel import com.emarsys.core.shard.ShardModel +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.RandomTestUtils import com.emarsys.testUtil.mockito.whenever import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe - -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock -class LogShardListMergerTest { +class LogShardListMergerTest : AnnotationSpec() { private companion object { const val ID = "id" @@ -36,7 +32,7 @@ class LogShardListMergerTest { private lateinit var deviceInfo: DeviceInfo - @BeforeEach + @Before fun setUp() { timestampProvider = mock() whenever(timestampProvider.provideTimestamp()).thenReturn(TIMESTAMP) diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/LoggerTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/LoggerTest.kt index 85423d67..f10b2764 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/LoggerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/LoggerTest.kt @@ -14,12 +14,10 @@ import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.shard.ShardModel import com.emarsys.core.storage.StringStorage import com.emarsys.core.util.log.entry.LogEntry +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.ThreadSpy import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.ArgumentCaptor import org.mockito.kotlin.any import org.mockito.kotlin.capture @@ -33,7 +31,7 @@ import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch -class LoggerTest { +class LoggerTest : AnnotationSpec() { companion object { const val TIMESTAMP = 400L @@ -42,7 +40,6 @@ class LoggerTest { } - private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder private lateinit var shardRepositoryMock: Repository private lateinit var timestampProviderMock: TimestampProvider @@ -52,7 +49,7 @@ class LoggerTest { private lateinit var loggerMock: Logger private lateinit var mockLogLevelStorage: StringStorage - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun init() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() @@ -86,7 +83,7 @@ class LoggerTest { setupCoreComponent(dependencyContainer) } - @AfterEach + @After fun tearDown() { if (CoreComponent.isSetup()) { core().concurrentHandlerHolder.coreLooper.quitSafely() diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/AppEventLogTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/AppEventLogTest.kt index 299816e2..240cb47d 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/AppEventLogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/AppEventLogTest.kt @@ -1,11 +1,10 @@ package com.emarsys.core.util.log.entry +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test - -class AppEventLogTest { +class AppEventLogTest : AnnotationSpec() { @Test diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/CrashLogTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/CrashLogTest.kt index 20ac3219..ef7a1f7d 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/CrashLogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/CrashLogTest.kt @@ -1,18 +1,16 @@ package com.emarsys.core.util.log.entry +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test - -class CrashLogTest { +class CrashLogTest : AnnotationSpec() { private lateinit var crashLog: CrashLog private lateinit var exception: Exception - @BeforeEach + @Before fun init() { exception = ConcurrentModificationException("cause of the exception") crashLog = CrashLog(exception, "testInfo") diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/InAppLogTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/InAppLogTest.kt index 1f4e36cf..45e10b4b 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/InAppLogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/InAppLogTest.kt @@ -4,14 +4,12 @@ package com.emarsys.core.util.log.entry import com.emarsys.core.di.FakeCoreDependencyContainer import com.emarsys.core.di.setupCoreComponent import com.emarsys.core.provider.uuid.UUIDProvider +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock -class InAppLogTest { +class InAppLogTest : AnnotationSpec() { private companion object { const val endTime = 10L const val startTime = 5L diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/LogEntryKtTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/LogEntryKtTest.kt index b15a0e44..abb24e69 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/LogEntryKtTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/LogEntryKtTest.kt @@ -1,12 +1,12 @@ package com.emarsys.core.util.log.entry import com.emarsys.core.util.log.LogLevel +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock -class LogEntryKtTest { +class LogEntryKtTest : AnnotationSpec() { @Test fun testToData() { diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/MethodNotAlllowedTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/MethodNotAlllowedTest.kt index eb2e6cae..f4b1b6c7 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/MethodNotAlllowedTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/MethodNotAlllowedTest.kt @@ -1,11 +1,10 @@ package com.emarsys.core.util.log.entry +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test - -class MethodNotAllowedTest { +class MethodNotAllowedTest : AnnotationSpec() { private companion object { const val testCallerMethodName = "testCallerMethodName" diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/OfflineQueueSizeTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/OfflineQueueSizeTest.kt index 81645479..c14ed7f2 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/OfflineQueueSizeTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/OfflineQueueSizeTest.kt @@ -1,11 +1,10 @@ package com.emarsys.core.util.log.entry +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test - -class OfflineQueueSizeTest { +class OfflineQueueSizeTest : AnnotationSpec() { @Test diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/RequestLogTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/RequestLogTest.kt index 54f8429c..5cbeeef6 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/RequestLogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/RequestLogTest.kt @@ -2,17 +2,14 @@ package com.emarsys.core.util.log.entry import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import java.net.URL -class RequestLogTest { +class RequestLogTest : AnnotationSpec() { private companion object { const val TOPIC = "log_request" const val IN_DATABASE_TIME_END = 3L @@ -23,7 +20,7 @@ class RequestLogTest { private lateinit var requestLog: RequestLog - @BeforeEach + @Before fun setUp() { mockRequestModel = mock { on { url }.doReturn(URL("https://emarsys.com")) diff --git a/core/src/androidTest/java/com/emarsys/core/util/log/entry/StatusLogTest.kt b/core/src/androidTest/java/com/emarsys/core/util/log/entry/StatusLogTest.kt index e91b5393..15c0a460 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/log/entry/StatusLogTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/log/entry/StatusLogTest.kt @@ -1,11 +1,10 @@ package com.emarsys.core.util.log.entry +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test - -class StatusLogTest { +class StatusLogTest : AnnotationSpec() { private companion object { const val testCallerMethodName = "testCallerMethodName" val testParameters = mapOf( @@ -13,11 +12,11 @@ class StatusLogTest { "parameter2" to "value2" ) val testStatus = mapOf( - "key1" to "value1", - "key2" to mapOf( - "statusMapKey1" to "statusValue1", - "statusMapKey2" to "statusValue2" - ) + "key1" to "value1", + "key2" to mapOf( + "statusMapKey1" to "statusValue1", + "statusMapKey2" to "statusValue2" + ) ) } diff --git a/core/src/androidTest/java/com/emarsys/core/util/predicate/ListSizeAtLeastTest.kt b/core/src/androidTest/java/com/emarsys/core/util/predicate/ListSizeAtLeastTest.kt index 7d97114a..873c1fed 100644 --- a/core/src/androidTest/java/com/emarsys/core/util/predicate/ListSizeAtLeastTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/util/predicate/ListSizeAtLeastTest.kt @@ -1,17 +1,15 @@ package com.emarsys.core.util.predicate +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test - -class ListSizeAtLeastTest { +class ListSizeAtLeastTest : AnnotationSpec() { private lateinit var predicate: ListSizeAtLeast - @BeforeEach + @Before fun init() { predicate = ListSizeAtLeast(5) } diff --git a/core/src/androidTest/java/com/emarsys/core/validate/JsonObjectValidatorTest.kt b/core/src/androidTest/java/com/emarsys/core/validate/JsonObjectValidatorTest.kt index 12308bff..2d2bb6eb 100644 --- a/core/src/androidTest/java/com/emarsys/core/validate/JsonObjectValidatorTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/validate/JsonObjectValidatorTest.kt @@ -1,23 +1,19 @@ package com.emarsys.core.validate +import com.emarsys.testUtil.AnnotationSpec import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.kotest.matchers.types.shouldBeSameInstanceAs import org.json.JSONObject - -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito.mock -class JsonObjectValidatorTest { +class JsonObjectValidatorTest : AnnotationSpec() { lateinit var json: JSONObject - @BeforeEach + @Before fun init() { json = JSONObject() .put("key1", "value1") diff --git a/core/src/androidTest/java/com/emarsys/core/worker/CoreCompletionHandlerMiddlewareTest.kt b/core/src/androidTest/java/com/emarsys/core/worker/CoreCompletionHandlerMiddlewareTest.kt index 235716f2..18e6441b 100644 --- a/core/src/androidTest/java/com/emarsys/core/worker/CoreCompletionHandlerMiddlewareTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/worker/CoreCompletionHandlerMiddlewareTest.kt @@ -14,12 +14,11 @@ import com.emarsys.core.request.model.RequestMethod import com.emarsys.core.request.model.RequestModel import com.emarsys.core.request.model.specification.FilterByRequestIds import com.emarsys.core.response.ResponseModel +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.ThreadSpy import io.kotest.matchers.ints.shouldBeLessThanOrEqual import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.ArgumentCaptor import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.capture @@ -33,7 +32,7 @@ import org.mockito.kotlin.verifyNoMoreInteractions import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch -class CoreCompletionHandlerMiddlewareTest { +class CoreCompletionHandlerMiddlewareTest : AnnotationSpec() { private lateinit var coreCompletionHandler: CoreCompletionHandler private lateinit var requestRepository: Repository private lateinit var mockWorker: Worker @@ -44,7 +43,7 @@ class CoreCompletionHandlerMiddlewareTest { private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun setup() { expectedId = "expectedId" mockWorker = mock() diff --git a/core/src/androidTest/java/com/emarsys/core/worker/DefaultWorkerTest.kt b/core/src/androidTest/java/com/emarsys/core/worker/DefaultWorkerTest.kt index e86b7135..61e82011 100644 --- a/core/src/androidTest/java/com/emarsys/core/worker/DefaultWorkerTest.kt +++ b/core/src/androidTest/java/com/emarsys/core/worker/DefaultWorkerTest.kt @@ -13,11 +13,10 @@ import com.emarsys.core.request.factory.CompletionHandlerProxyProvider import com.emarsys.core.request.model.RequestMethod import com.emarsys.core.request.model.RequestModel import com.emarsys.core.testUtil.RequestModelTestUtils.createRequestModel +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils.deleteCoreDatabase import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.doNothing @@ -30,7 +29,7 @@ import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch -class DefaultWorkerTest { +class DefaultWorkerTest : AnnotationSpec() { companion object { const val URL = "https://www.google.com" } @@ -48,7 +47,7 @@ class DefaultWorkerTest { private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun setup() { deleteCoreDatabase() watchDogMock = mock() diff --git a/emarsys-e2e-test/build.gradle.kts b/emarsys-e2e-test/build.gradle.kts index 7182a6cf..ec9889e7 100644 --- a/emarsys-e2e-test/build.gradle.kts +++ b/emarsys-e2e-test/build.gradle.kts @@ -23,15 +23,21 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArguments["runnerBuilder"] = - "de.mannodermaus.junit5.AndroidJUnit5Builder" } compileOptions { isCoreLibraryDesugaringEnabled = true } packaging { resources { - excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + excludes += arrayOf( + "README.txt", + "META-INF/LICENSE.md", + "META-INF/LICENSE-notice.md", + "**/attach_hotspot_windows.dll", + "META-INF/AL2.0", + "META-INF/LGPL2.1", + "META-INF/licenses/ASM" + ) } } } diff --git a/emarsys-e2e-test/src/androidTest/java/com/emarsys/EmarsysE2ETests.kt b/emarsys-e2e-test/src/androidTest/java/com/emarsys/EmarsysE2ETests.kt index 1fa25f2e..23403c7d 100644 --- a/emarsys-e2e-test/src/androidTest/java/com/emarsys/EmarsysE2ETests.kt +++ b/emarsys-e2e-test/src/androidTest/java/com/emarsys/EmarsysE2ETests.kt @@ -1,5 +1,6 @@ package com.emarsys + import android.app.Application import android.location.Location import android.location.LocationManager @@ -11,26 +12,30 @@ import com.emarsys.di.emarsys import com.emarsys.mobileengage.api.geofence.Trigger import com.emarsys.mobileengage.api.geofence.TriggerType import com.emarsys.mobileengage.api.inbox.Message -import com.emarsys.testUtil.* -import com.emarsys.testUtil.rules.ConnectionExtension -import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import com.emarsys.testUtil.AnnotationSpec +import com.emarsys.testUtil.E2ETestUtils +import com.emarsys.testUtil.InstrumentationRegistry +import com.emarsys.testUtil.ReflectionTestUtils +import com.emarsys.testUtil.RetryUtils +import com.emarsys.testUtil.rules.DuplicatedThreadRule +import com.emarsys.testUtil.rules.RetryRule import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import org.json.JSONObject -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.Disabled - -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith -import org.junit.jupiter.api.extension.RegisterExtension -import org.junitpioneer.jupiter.RetryingTest - +import org.junit.Rule import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import com.emarsys.mobileengage.api.geofence.Geofence as MEGeofence -@ExtendWith(DuplicatedThreadExtension::class) -class EmarsysE2ETests { +class EmarsysE2ETests : AnnotationSpec() { + + @Rule + @JvmField + val retryRule: RetryRule = RetryUtils.retryRule + + @Rule + @JvmField + val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") companion object { private const val OLD_APPLICATION_CODE = "14C19-A121F" @@ -44,17 +49,13 @@ class EmarsysE2ETests { private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @JvmField - @RegisterExtension - var connectionExtension: ConnectionExtension = ConnectionExtension(application) - - @AfterEach + @After fun tearDown() { E2ETestUtils.tearDownEmarsys(application) } @Test - @RetryingTest(3) + fun testChangeApplicationCode() { setup(OLD_APPLICATION_CODE) @@ -73,7 +74,7 @@ class EmarsysE2ETests { } @Test - @RetryingTest(3) + fun testChangeApplicationCodeFromNull() { setup(null) @@ -92,7 +93,7 @@ class EmarsysE2ETests { } @Test - @RetryingTest(3) + fun testChangeApplicationCodeToNull() { var disabled = true setup(APPLICATION_CODE) @@ -116,7 +117,7 @@ class EmarsysE2ETests { } @Test - @RetryingTest(3) + fun testInbox_addTag_removeTag() { setup(APPLICATION_CODE) @@ -160,8 +161,7 @@ class EmarsysE2ETests { } @Test - @Disabled("Test is too flaky to run on pipeline") - @RetryingTest(3) + @Ignore fun testGeofence() { setup(APPLICATION_CODE) RetryUtil.retry { diff --git a/emarsys-firebase/build.gradle.kts b/emarsys-firebase/build.gradle.kts index 04aa81ed..6fe6968b 100644 --- a/emarsys-firebase/build.gradle.kts +++ b/emarsys-firebase/build.gradle.kts @@ -25,15 +25,21 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArguments["runnerBuilder"] = - "de.mannodermaus.junit5.AndroidJUnit5Builder" } compileOptions { isCoreLibraryDesugaringEnabled = true } packaging { resources { - excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + excludes += arrayOf( + "README.txt", + "META-INF/LICENSE.md", + "META-INF/LICENSE-notice.md", + "**/attach_hotspot_windows.dll", + "META-INF/AL2.0", + "META-INF/LGPL2.1", + "META-INF/licenses/ASM" + ) } } } diff --git a/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceTest.kt b/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceTest.kt index 990f81de..454f491d 100644 --- a/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceTest.kt +++ b/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceTest.kt @@ -1,5 +1,6 @@ package com.emarsys.service + import android.app.Application import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.device.DeviceInfo @@ -9,12 +10,10 @@ import com.emarsys.fake.FakeFirebaseDependencyContainer import com.emarsys.mobileengage.di.setupMobileEngageComponent import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.push.PushInternal +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.FeatureTestUtils import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.ReflectionTestUtils -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -24,8 +23,7 @@ import org.mockito.kotlin.times import org.mockito.kotlin.verify -class EmarsysFirebaseMessagingServiceTest { - +class EmarsysFirebaseMessagingServiceTest : AnnotationSpec() { private val application: Application @@ -37,7 +35,7 @@ class EmarsysFirebaseMessagingServiceTest { private lateinit var spyCoreHandler: SdkHandler private lateinit var emarsysFirebaseMessagingService: EmarsysFirebaseMessagingService - @BeforeEach + @Before fun setUp() { emarsysFirebaseMessagingService = EmarsysFirebaseMessagingService() mockPushInternal = mock() @@ -51,7 +49,7 @@ class EmarsysFirebaseMessagingServiceTest { ) } - @AfterEach + @After fun tearDown() { tearDownMobileEngageComponent() FeatureTestUtils.resetFeatures() diff --git a/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceUtilsTest.kt b/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceUtilsTest.kt index cbeb81ed..9cbbbbe2 100644 --- a/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceUtilsTest.kt +++ b/emarsys-firebase/src/androidTest/java/com/emarsys/service/EmarsysFirebaseMessagingServiceUtilsTest.kt @@ -4,16 +4,15 @@ import android.content.Context import android.os.Bundle import com.emarsys.fake.FakeFirebaseDependencyContainer import com.emarsys.mobileengage.di.setupMobileEngageComponent +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry import com.google.firebase.messaging.RemoteMessage import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -class EmarsysFirebaseMessagingServiceUtilsTest { +class EmarsysFirebaseMessagingServiceUtilsTest : AnnotationSpec() { private lateinit var context: Context - @BeforeEach + @Before fun init() { context = InstrumentationRegistry.getTargetContext() setupMobileEngageComponent( diff --git a/emarsys-huawei/build.gradle.kts b/emarsys-huawei/build.gradle.kts index 42152171..acbe2feb 100644 --- a/emarsys-huawei/build.gradle.kts +++ b/emarsys-huawei/build.gradle.kts @@ -26,15 +26,21 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArguments["runnerBuilder"] = - "de.mannodermaus.junit5.AndroidJUnit5Builder" } compileOptions { isCoreLibraryDesugaringEnabled = true } packaging { resources { - excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + excludes += arrayOf( + "README.txt", + "META-INF/LICENSE.md", + "META-INF/LICENSE-notice.md", + "**/attach_hotspot_windows.dll", + "META-INF/AL2.0", + "META-INF/LGPL2.1", + "META-INF/licenses/ASM" + ) } } } diff --git a/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceTest.kt b/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceTest.kt index 337f1d54..e6651b09 100644 --- a/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceTest.kt +++ b/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceTest.kt @@ -1,5 +1,6 @@ package com.emarsys.service + import android.app.Application import android.os.Looper import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory @@ -10,12 +11,10 @@ import com.emarsys.fake.FakeHuaweiDependencyContainer import com.emarsys.mobileengage.di.setupMobileEngageComponent import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.push.PushInternal +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.FeatureTestUtils import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.ReflectionTestUtils -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -24,7 +23,7 @@ import org.mockito.kotlin.timeout import org.mockito.kotlin.times import org.mockito.kotlin.verify -class EmarsysHuaweiMessagingServiceTest { +class EmarsysHuaweiMessagingServiceTest : AnnotationSpec() { private val application: Application @@ -36,7 +35,7 @@ class EmarsysHuaweiMessagingServiceTest { private lateinit var emarsysHuaweiMessagingService: EmarsysHuaweiMessagingService private lateinit var spyCoreHandler: SdkHandler - @BeforeEach + @Before fun setUp() { mockPushInternal = mock() @@ -53,7 +52,7 @@ class EmarsysHuaweiMessagingServiceTest { emarsysHuaweiMessagingService = EmarsysHuaweiMessagingService() } - @AfterEach + @After fun tearDown() { tearDownMobileEngageComponent() FeatureTestUtils.resetFeatures() diff --git a/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceUtilsTest.kt b/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceUtilsTest.kt index c6c32a60..14539850 100644 --- a/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceUtilsTest.kt +++ b/emarsys-huawei/src/androidTest/java/com/emarsys/service/EmarsysHuaweiMessagingServiceUtilsTest.kt @@ -4,16 +4,15 @@ import android.content.Context import android.os.Bundle import com.emarsys.fake.FakeHuaweiDependencyContainer import com.emarsys.mobileengage.di.setupMobileEngageComponent +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry import com.huawei.hms.push.RemoteMessage import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -class EmarsysHuaweiMessagingServiceUtilsTest { +class EmarsysHuaweiMessagingServiceUtilsTest : AnnotationSpec() { private lateinit var context: Context - @BeforeEach + @Before fun init() { context = InstrumentationRegistry.getTargetContext() setupMobileEngageComponent( diff --git a/emarsys-sdk/build.gradle.kts b/emarsys-sdk/build.gradle.kts index 59c15d51..607a8cbc 100644 --- a/emarsys-sdk/build.gradle.kts +++ b/emarsys-sdk/build.gradle.kts @@ -29,15 +29,21 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArguments["runnerBuilder"] = - "de.mannodermaus.junit5.AndroidJUnit5Builder" } compileOptions { isCoreLibraryDesugaringEnabled = true } packaging { resources { - excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + excludes += arrayOf( + "README.txt", + "META-INF/LICENSE.md", + "META-INF/LICENSE-notice.md", + "**/attach_hotspot_windows.dll", + "META-INF/AL2.0", + "META-INF/LGPL2.1", + "META-INF/licenses/ASM" + ) } } } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/DefaultInboxIntegrationTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/DefaultInboxIntegrationTest.kt index 939683c3..8e4e11be 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/DefaultInboxIntegrationTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/DefaultInboxIntegrationTest.kt @@ -1,5 +1,6 @@ package com.emarsys + import android.app.Application import com.emarsys.config.EmarsysConfig import com.emarsys.core.device.DeviceInfo @@ -9,26 +10,32 @@ import com.emarsys.core.provider.hardwareid.HardwareIdProvider import com.emarsys.core.provider.version.VersionProvider import com.emarsys.di.DefaultEmarsysComponent import com.emarsys.di.DefaultEmarsysDependencies +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.IntegrationTestUtils +import com.emarsys.testUtil.KotestRunnerAndroid import com.emarsys.testUtil.mockito.whenever -import com.emarsys.testUtil.rules.ConnectionExtension -import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import com.emarsys.testUtil.rules.ConnectionRule +import com.emarsys.testUtil.rules.DuplicatedThreadRule import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith -import org.junit.jupiter.api.extension.RegisterExtension +import org.junit.Rule +import org.junit.runner.RunWith import org.mockito.ArgumentMatchers.any import org.mockito.Mockito.mock import java.util.concurrent.CountDownLatch -@ExtendWith(DuplicatedThreadExtension::class) -class DefaultInboxIntegrationTest { +@RunWith(KotestRunnerAndroid::class) +class DefaultInboxIntegrationTest : AnnotationSpec() { + @Rule + @JvmField + val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") + + @Rule + @JvmField + val connectionRule = ConnectionRule(application) companion object { private const val APP_ID = "14C19-A121F" @@ -45,11 +52,8 @@ class DefaultInboxIntegrationTest { private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @JvmField - @RegisterExtension - var connectionExtension: ConnectionExtension = ConnectionExtension(application) - @BeforeEach + @Before fun setup() { DatabaseTestUtils.deleteCoreDatabase() @@ -86,7 +90,7 @@ class DefaultInboxIntegrationTest { IntegrationTestUtils.doLogin(2575) } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys(application) } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/EmarsysTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/EmarsysTest.kt index b43de131..daa1d8c0 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/EmarsysTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/EmarsysTest.kt @@ -34,7 +34,11 @@ import com.emarsys.core.request.RequestManager import com.emarsys.core.response.ResponseHandlersProcessor import com.emarsys.core.storage.StringStorage import com.emarsys.deeplink.DeepLinkApi -import com.emarsys.di.* +import com.emarsys.di.DefaultEmarsysComponent +import com.emarsys.di.FakeDependencyContainer +import com.emarsys.di.emarsys +import com.emarsys.di.isEmarsysComponentSetup +import com.emarsys.di.setupEmarsysComponent import com.emarsys.eventservice.EventServiceApi import com.emarsys.inapp.InAppApi import com.emarsys.inbox.MessageInboxApi @@ -49,7 +53,14 @@ import com.emarsys.mobileengage.event.EventServiceInternal import com.emarsys.mobileengage.geofence.FetchGeofencesAction import com.emarsys.mobileengage.iam.AppStartAction import com.emarsys.mobileengage.iam.model.requestRepositoryProxy.RequestRepositoryProxy -import com.emarsys.mobileengage.responsehandler.* +import com.emarsys.mobileengage.responsehandler.ClientInfoResponseHandler +import com.emarsys.mobileengage.responsehandler.DeviceEventStateResponseHandler +import com.emarsys.mobileengage.responsehandler.InAppCleanUpResponseHandler +import com.emarsys.mobileengage.responsehandler.InAppCleanUpResponseHandlerV4 +import com.emarsys.mobileengage.responsehandler.InAppMessageResponseHandler +import com.emarsys.mobileengage.responsehandler.MobileEngageClientStateResponseHandler +import com.emarsys.mobileengage.responsehandler.MobileEngageTokenResponseHandler +import com.emarsys.mobileengage.responsehandler.OnEventActionResponseHandler import com.emarsys.predict.PredictApi import com.emarsys.predict.PredictRestrictedApi import com.emarsys.predict.api.model.Logic @@ -58,23 +69,40 @@ import com.emarsys.predict.api.model.RecommendationFilter import com.emarsys.predict.response.VisitorIdResponseHandler import com.emarsys.predict.response.XPResponseHandler import com.emarsys.push.PushApi +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.CollectionTestUtils.getElementByType import com.emarsys.testUtil.CollectionTestUtils.numberOfElementsIn import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.IntegrationTestUtils import com.emarsys.testUtil.ReflectionTestUtils.getInstanceField -import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import com.emarsys.testUtil.rules.ConnectionRule +import com.emarsys.testUtil.rules.DuplicatedThreadRule import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith -import org.mockito.kotlin.* +import org.junit.Rule +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.inOrder +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.spy +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.verifyNoMoreInteractions +import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch -@ExtendWith(DuplicatedThreadExtension::class) -class EmarsysTest { +class EmarsysTest : AnnotationSpec() { + @Rule + @JvmField + val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") + + + @Rule + @JvmField + val connectionRule = ConnectionRule(getTargetContext().applicationContext as Application) + companion object { private const val APPLICATION_CODE = "EMS11-C3FD3" private const val CONTACT_FIELD_ID = 3 @@ -130,7 +158,7 @@ class EmarsysTest { private lateinit var latch: CountDownLatch private lateinit var predictResultListenerCallback: (Try>) -> Unit - @BeforeEach + @Before fun setUp() { application = spy(getTargetContext().applicationContext as Application) completionListener = mock() @@ -250,7 +278,7 @@ class EmarsysTest { latch = CountDownLatch(1) } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/InAppTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/InAppTest.kt index 09acc3e8..3cd79759 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/InAppTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/InAppTest.kt @@ -11,23 +11,21 @@ import com.emarsys.inapp.InApp import com.emarsys.mobileengage.api.event.EventHandler import com.emarsys.mobileengage.di.mobileEngage import com.emarsys.mobileengage.iam.InAppInternal +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.whenever -class InAppTest { +class InAppTest : AnnotationSpec() { private lateinit var inApp: InApp private lateinit var mockInAppInternal: InAppInternal private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @BeforeEach + @Before fun setUp() { mockInAppInternal = mock() val dependencyContainer = FakeDependencyContainer(inAppInternal = mockInAppInternal) @@ -36,7 +34,7 @@ class InAppTest { inApp = InApp() } - @AfterEach + @After fun tearDown() { application.unregisterActivityLifecycleCallbacks( mobileEngage().activityLifecycleWatchdog) diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/InappNotificationIntegrationTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/InappNotificationIntegrationTest.kt index 1c35abba..fee12740 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/InappNotificationIntegrationTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/InappNotificationIntegrationTest.kt @@ -1,5 +1,6 @@ package com.emarsys +import android.app.Activity import android.app.Application import android.content.Context import android.content.Intent @@ -7,6 +8,7 @@ import com.emarsys.config.EmarsysConfig import com.emarsys.core.activity.ActivityLifecycleActionRegistry import com.emarsys.core.activity.ActivityLifecycleWatchdog import com.emarsys.core.app.AppLifecycleObserver +import com.emarsys.core.provider.activity.CurrentActivityProvider import com.emarsys.core.util.FileDownloader import com.emarsys.di.DefaultEmarsysComponent import com.emarsys.di.DefaultEmarsysDependencies @@ -15,13 +17,11 @@ import com.emarsys.mobileengage.iam.OverlayInAppPresenter import com.emarsys.mobileengage.service.IntentUtils import com.emarsys.mobileengage.service.NotificationData import com.emarsys.mobileengage.service.NotificationOperation +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ConnectionTestUtils import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.IntegrationTestUtils -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.eq import org.mockito.kotlin.mock @@ -29,7 +29,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch -class InappNotificationIntegrationTest { +class InappNotificationIntegrationTest : AnnotationSpec() { private companion object { const val APP_ID = "14C19-A121F" @@ -39,12 +39,13 @@ class InappNotificationIntegrationTest { private lateinit var completionListenerLatch: CountDownLatch private lateinit var baseConfig: EmarsysConfig private lateinit var mockInappPresenterOverlay: OverlayInAppPresenter + private lateinit var mockCurrentActivityProvider: CurrentActivityProvider private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @BeforeEach + @Before fun setup() { completionListenerLatch = CountDownLatch(1) @@ -75,12 +76,17 @@ class InappNotificationIntegrationTest { ).thenAnswer { completionListenerLatch.countDown() } + mockCurrentActivityProvider = mock() + val mockActivity = mock() + whenever(mockCurrentActivityProvider.get()).thenReturn(mockActivity) DefaultEmarsysDependencies(baseConfig, object : DefaultEmarsysComponent(baseConfig) { override val overlayInAppPresenter: OverlayInAppPresenter get() = mockInappPresenterOverlay override val activityLifecycleWatchdog: ActivityLifecycleWatchdog get() = mock() + override val currentActivityProvider: CurrentActivityProvider + get() = mockCurrentActivityProvider override val activityLifecycleActionRegistry: ActivityLifecycleActionRegistry get() = mock() override val appLifecycleObserver: AppLifecycleObserver @@ -96,7 +102,7 @@ class InappNotificationIntegrationTest { IntegrationTestUtils.doLogin() } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys(application) } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageIntegrationTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageIntegrationTest.kt index 3210ce42..11e8efb1 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageIntegrationTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageIntegrationTest.kt @@ -1,5 +1,6 @@ package com.emarsys + import android.app.Activity import android.app.Application import android.content.Context @@ -18,25 +19,31 @@ import com.emarsys.di.DefaultEmarsysComponent import com.emarsys.di.DefaultEmarsysDependencies import com.emarsys.di.emarsys import com.emarsys.mobileengage.push.PushTokenProvider -import com.emarsys.testUtil.* +import com.emarsys.testUtil.AnnotationSpec +import com.emarsys.testUtil.ConnectionTestUtils +import com.emarsys.testUtil.DatabaseTestUtils +import com.emarsys.testUtil.InstrumentationRegistry +import com.emarsys.testUtil.IntegrationTestUtils +import com.emarsys.testUtil.RetryUtils import com.emarsys.testUtil.mockito.whenever -import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import com.emarsys.testUtil.rules.DuplicatedThreadRule +import com.emarsys.testUtil.rules.RetryRule import io.kotest.matchers.ints.shouldBeInRange import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe - -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith -import org.junitpioneer.jupiter.RetryingTest - +import org.junit.Rule import org.mockito.ArgumentMatchers import org.mockito.Mockito.mock import java.util.concurrent.CountDownLatch -@ExtendWith(DuplicatedThreadExtension::class) -class MobileEngageIntegrationTest { +class MobileEngageIntegrationTest : AnnotationSpec() { + @Rule + @JvmField + val retryRule: RetryRule = RetryUtils.retryRule + + @Rule + @JvmField + val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") private companion object { private const val APP_ID = "14C19-A121F" @@ -56,7 +63,8 @@ class MobileEngageIntegrationTest { private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @BeforeEach + + @Before fun setup() { DatabaseTestUtils.deleteCoreDatabase() @@ -118,7 +126,7 @@ class MobileEngageIntegrationTest { completionHandlerLatch = CountDownLatch(1) } - @AfterEach + @After fun tearDown() { try { IntegrationTestUtils.tearDownEmarsys(application) @@ -129,7 +137,7 @@ class MobileEngageIntegrationTest { } @Test - @RetryingTest(3) + fun testSetContact() { Emarsys.setContact( CONTACT_FIELD_ID, @@ -139,7 +147,7 @@ class MobileEngageIntegrationTest { } @Test - @RetryingTest(3) + fun testClearContact() { Emarsys.clearContact( this::eventuallyStoreResult @@ -147,7 +155,7 @@ class MobileEngageIntegrationTest { } @Test - @RetryingTest(3) + fun testTrackCustomEvent_V3_noAttributes() { Emarsys.trackCustomEvent( "integrationTestCustomEvent", @@ -157,7 +165,7 @@ class MobileEngageIntegrationTest { } @Test - @RetryingTest(3) + fun testTrackCustomEvent_V3_withAttributes() { Emarsys.trackCustomEvent( "integrationTestCustomEvent", @@ -167,7 +175,7 @@ class MobileEngageIntegrationTest { } @Test - @RetryingTest(3) + fun testTrackInternalCustomEvent_V3_noAttributes() { val eventServiceInternal = emarsys().eventServiceInternal @@ -179,7 +187,7 @@ class MobileEngageIntegrationTest { } @Test - @RetryingTest(3) + fun testTrackInternalCustomEvent_V3_withAttributes() { val eventServiceInternal = emarsys().eventServiceInternal @@ -191,7 +199,7 @@ class MobileEngageIntegrationTest { } @Test - @RetryingTest(3) + fun testSetPushToken() { Emarsys.push.setPushToken( "integration_test_push_token", @@ -200,7 +208,7 @@ class MobileEngageIntegrationTest { } @Test - @RetryingTest(3) + fun testRemovePushToken() { Emarsys.push.clearPushToken( this::eventuallyStoreResult @@ -208,7 +216,7 @@ class MobileEngageIntegrationTest { } @Test - @RetryingTest(3) + fun testDeepLinkOpen() { Thread.sleep(1000) val activity = mock(Activity::class.java) @@ -229,7 +237,7 @@ class MobileEngageIntegrationTest { } @Test - @RetryingTest(3) + fun testTrackDeviceInfo() { val clientServiceInternal = emarsys().clientServiceInternal @@ -238,7 +246,7 @@ class MobileEngageIntegrationTest { } @Test - @RetryingTest(3) + fun testConfig_changeApplicationCode() { val originalApplicationCode = Emarsys.config.applicationCode Emarsys.config.changeApplicationCode(OTHER_APP_ID, this::eventuallyStoreResult) @@ -248,7 +256,7 @@ class MobileEngageIntegrationTest { } @Test - @RetryingTest(3) + fun testConfig_changeApplicationCode_nilToSomething() { val setupLatch = CountDownLatch(1) emarsys().concurrentHandlerHolder.coreHandler.post { diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageRefreshContactTokenIntegrationTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageRefreshContactTokenIntegrationTest.kt index 8ffdb5a0..b0afc03b 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageRefreshContactTokenIntegrationTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/MobileEngageRefreshContactTokenIntegrationTest.kt @@ -14,29 +14,32 @@ import com.emarsys.core.storage.Storage import com.emarsys.di.DefaultEmarsysComponent import com.emarsys.di.DefaultEmarsysDependencies import com.emarsys.di.emarsys +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ConnectionTestUtils import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.FeatureTestUtils import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.IntegrationTestUtils +import com.emarsys.testUtil.RetryUtils import com.emarsys.testUtil.mockito.whenever -import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import com.emarsys.testUtil.rules.DuplicatedThreadRule +import com.emarsys.testUtil.rules.RetryRule import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith -import org.junitpioneer.jupiter.RetryingTest - +import org.junit.Rule import org.mockito.ArgumentMatchers import org.mockito.Mockito import java.util.concurrent.CountDownLatch -@ExtendWith(DuplicatedThreadExtension::class) +class MobileEngageRefreshContactTokenIntegrationTest : AnnotationSpec() { -class MobileEngageRefreshContactTokenIntegrationTest { + @Rule + @JvmField + val retryRule: RetryRule = RetryUtils.retryRule + + @Rule + @JvmField + val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") companion object { private const val APP_ID = "14C19-A121F" @@ -52,7 +55,7 @@ class MobileEngageRefreshContactTokenIntegrationTest { private val application: Application get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @BeforeEach + @Before fun setup() { DatabaseTestUtils.deleteCoreDatabase() @@ -103,13 +106,13 @@ class MobileEngageRefreshContactTokenIntegrationTest { completionListenerLatch = CountDownLatch(1) } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys(application) } @Test - @RetryingTest(3) + fun testRefreshContactToken_shouldUpdateContactToken_whenOutDated() { contactTokenStorage.remove() contactTokenStorage.set("tokenForIntegrationTest") diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/PredictIntegrationTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/PredictIntegrationTest.kt index 145fb282..1f1b1af9 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/PredictIntegrationTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/PredictIntegrationTest.kt @@ -21,31 +21,34 @@ import com.emarsys.predict.api.model.Product import com.emarsys.predict.api.model.RecommendationFilter import com.emarsys.predict.api.model.RecommendationLogic import com.emarsys.predict.util.CartItemUtils +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ConnectionTestUtils import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.FeatureTestUtils import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.IntegrationTestUtils import com.emarsys.testUtil.mockito.whenever -import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import com.emarsys.testUtil.rules.ConnectionRule +import com.emarsys.testUtil.rules.DuplicatedThreadRule import io.kotest.matchers.comparables.shouldBeGreaterThan import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith - +import org.junit.Rule import org.mockito.ArgumentMatchers import org.mockito.Mockito.mock import java.net.URLDecoder import java.util.concurrent.CountDownLatch import kotlin.reflect.KMutableProperty0 -@ExtendWith(DuplicatedThreadExtension::class) -class PredictIntegrationTest { +class PredictIntegrationTest : AnnotationSpec() { + @Rule + @JvmField + val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") + + @Rule + @JvmField + val connectionRule = ConnectionRule(application) companion object { private const val CONTACT_FIELD_ID = 3 @@ -71,7 +74,7 @@ class PredictIntegrationTest { get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @BeforeEach + @Before fun setup() { DatabaseTestUtils.deleteCoreDatabase() @@ -96,7 +99,10 @@ class PredictIntegrationTest { completionHandler = object : DefaultCoreCompletionHandler(mutableMapOf()) { override fun onSuccess(id: String, responseModel: ResponseModel) { super.onSuccess(id, responseModel) - if (responseModel.isPredictRequest and this@PredictIntegrationTest.responseModelMatches(responseModel)) { + if (responseModel.isPredictRequest and this@PredictIntegrationTest.responseModelMatches( + responseModel + ) + ) { this@PredictIntegrationTest.responseModel = responseModel latch.countDown() } @@ -157,7 +163,7 @@ class PredictIntegrationTest { } } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys(application) } @@ -287,8 +293,10 @@ class PredictIntegrationTest { testTrackSearchTerm() latch = CountDownLatch(1) - Emarsys.predict.recommendProducts(RecommendationLogic.search(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + Emarsys.predict.recommendProducts( + RecommendationLogic.search(), + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter) + ) eventuallyAssertForTriedRecommendedProducts() } @@ -300,8 +308,10 @@ class PredictIntegrationTest { PredictCartItem(ITEM2, 2.2, 20.0), PredictCartItem(ITEM3, 3.3, 30.0) ) - Emarsys.predict.recommendProducts(RecommendationLogic.cart(cartItems), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + Emarsys.predict.recommendProducts( + RecommendationLogic.cart(cartItems), + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter) + ) eventuallyAssertForTriedRecommendedProducts() } @@ -311,8 +321,10 @@ class PredictIntegrationTest { testTrackCart() latch = CountDownLatch(1) - Emarsys.predict.recommendProducts(RecommendationLogic.cart(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + Emarsys.predict.recommendProducts( + RecommendationLogic.cart(), + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter) + ) eventuallyAssertForTriedRecommendedProducts() } @@ -332,16 +344,20 @@ class PredictIntegrationTest { testTrackItemView() latch = CountDownLatch(1) - Emarsys.predict.recommendProducts(RecommendationLogic.related(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + Emarsys.predict.recommendProducts( + RecommendationLogic.related(), + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter) + ) eventuallyAssertForTriedRecommendedProducts() } @Test fun testRecommendProducts_withoutRelated() { - Emarsys.predict.recommendProducts(RecommendationLogic.related(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)).eventuallyAssert { + Emarsys.predict.recommendProducts( + RecommendationLogic.related(), + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter) + ).eventuallyAssert { triedRecommendedProducts.errorCause shouldBe null triedRecommendedProducts.result shouldNotBe null triedRecommendedProducts.result!!.size shouldBe 0 @@ -363,8 +379,10 @@ class PredictIntegrationTest { testTrackCategoryView() latch = CountDownLatch(1) - Emarsys.predict.recommendProducts(RecommendationLogic.category(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + Emarsys.predict.recommendProducts( + RecommendationLogic.category(), + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter) + ) eventuallyAssertForTriedRecommendedProducts() } @@ -384,8 +402,10 @@ class PredictIntegrationTest { testTrackItemView() latch = CountDownLatch(1) - Emarsys.predict.recommendProducts(RecommendationLogic.alsoBought(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + Emarsys.predict.recommendProducts( + RecommendationLogic.alsoBought(), + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter) + ) eventuallyAssertForTriedRecommendedProducts() } @@ -395,8 +415,10 @@ class PredictIntegrationTest { testTrackCategoryView() latch = CountDownLatch(1) - Emarsys.predict.recommendProducts(RecommendationLogic.popular(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + Emarsys.predict.recommendProducts( + RecommendationLogic.popular(), + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter) + ) eventuallyAssertForTriedRecommendedProducts() } @@ -406,8 +428,10 @@ class PredictIntegrationTest { testTrackItemView() latch = CountDownLatch(1) - Emarsys.predict.recommendProducts(RecommendationLogic.personal(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + Emarsys.predict.recommendProducts( + RecommendationLogic.personal(), + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter) + ) eventuallyAssertForTriedRecommendedProducts() } @@ -417,8 +441,10 @@ class PredictIntegrationTest { testTrackItemView() latch = CountDownLatch(1) - Emarsys.predict.recommendProducts(RecommendationLogic.personal(listOf("1", "2", "3")), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + Emarsys.predict.recommendProducts( + RecommendationLogic.personal(listOf("1", "2", "3")), + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter) + ) eventuallyAssertForTriedRecommendedProducts() } @@ -428,8 +454,10 @@ class PredictIntegrationTest { testTrackItemView() latch = CountDownLatch(1) - Emarsys.predict.recommendProducts(RecommendationLogic.home(), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + Emarsys.predict.recommendProducts( + RecommendationLogic.home(), + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter) + ) eventuallyAssertForTriedRecommendedProducts() } @@ -439,8 +467,10 @@ class PredictIntegrationTest { testTrackItemView() latch = CountDownLatch(1) - Emarsys.predict.recommendProducts(RecommendationLogic.home(listOf("1", "2", "3")), - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + Emarsys.predict.recommendProducts( + RecommendationLogic.home(listOf("1", "2", "3")), + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter) + ) eventuallyAssertForTriedRecommendedProducts() } @@ -450,8 +480,10 @@ class PredictIntegrationTest { testTrackItemView() latch = CountDownLatch(1) - Emarsys.predict.recommendProducts(RecommendationLogic.home(listOf("1", "2", "3")), "hu", - eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter)) + Emarsys.predict.recommendProducts( + RecommendationLogic.home(listOf("1", "2", "3")), "hu", + eventuallyStoreResultInProperty(this::triedRecommendedProducts.setter) + ) eventuallyAssertForTriedRecommendedProducts() } @@ -517,7 +549,8 @@ class PredictIntegrationTest { } private val ResponseModel.isPredictRequest - get() = this.requestModel.url.toString().startsWith("https://recommender.scarabresearch.com/merchants/$MERCHANT_ID?") + get() = this.requestModel.url.toString() + .startsWith("https://recommender.scarabresearch.com/merchants/$MERCHANT_ID?") private val ResponseModel.baseUrl get() = URLDecoder.decode(this.requestModel.url.toString(), "UTF-8") diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/PredictTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/PredictTest.kt index 48a592c9..951ed46e 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/PredictTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/PredictTest.kt @@ -14,20 +14,18 @@ import com.emarsys.predict.api.model.CartItem import com.emarsys.predict.api.model.Logic import com.emarsys.predict.api.model.Product import com.emarsys.predict.api.model.RecommendationFilter +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.RandomTestUtils.randomNumberString import com.emarsys.testUtil.RandomTestUtils.randomString import com.emarsys.testUtil.mockito.anyNotNull import io.kotest.assertions.throwables.shouldThrow -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito import org.mockito.kotlin.eq import org.mockito.kotlin.isNull import org.mockito.kotlin.mock import org.mockito.kotlin.verify -class PredictTest { +class PredictTest : AnnotationSpec() { companion object { const val AVAILABILITY_ZONE = "HU" } @@ -40,7 +38,7 @@ class PredictTest { private lateinit var resultListenerCallback: (Try>) -> Unit - @BeforeEach + @Before fun setUp() { mockPredictInternal = mock() resultListenerCallback = mock() @@ -56,7 +54,7 @@ class PredictTest { mockRecommendationFilters = listOf(mockRecommendationFilter) } - @AfterEach + @After fun tearDown() { try { val handler = emarsys().concurrentHandlerHolder diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/PushTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/PushTest.kt index 3721af34..c29b70cc 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/PushTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/PushTest.kt @@ -7,14 +7,12 @@ import com.emarsys.mobileengage.api.event.EventHandler import com.emarsys.mobileengage.api.push.NotificationInformationListener import com.emarsys.mobileengage.push.PushInternal import com.emarsys.push.Push +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.IntegrationTestUtils -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito import org.mockito.kotlin.mock -class PushTest { +class PushTest : AnnotationSpec() { private lateinit var mockPushInternal: PushInternal private lateinit var mockCompletionListener: CompletionListener private lateinit var mockEventHandler: EventHandler @@ -22,7 +20,7 @@ class PushTest { private lateinit var push: Push - @BeforeEach + @Before fun setUp() { mockPushInternal = mock() mockCompletionListener = mock() @@ -35,7 +33,7 @@ class PushTest { push = Push() } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/RemoteConfigIntegrationTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/RemoteConfigIntegrationTest.kt index d168421b..6c2fbe5b 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/RemoteConfigIntegrationTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/RemoteConfigIntegrationTest.kt @@ -4,18 +4,26 @@ package com.emarsys import android.app.Application import com.emarsys.config.EmarsysConfig import com.emarsys.di.emarsys -import com.emarsys.testUtil.* -import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import com.emarsys.testUtil.AnnotationSpec +import com.emarsys.testUtil.ConnectionTestUtils +import com.emarsys.testUtil.DatabaseTestUtils +import com.emarsys.testUtil.InstrumentationRegistry +import com.emarsys.testUtil.IntegrationTestUtils +import com.emarsys.testUtil.rules.ConnectionRule +import com.emarsys.testUtil.rules.DuplicatedThreadRule import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith +import org.junit.Rule import java.util.concurrent.CountDownLatch -@ExtendWith(DuplicatedThreadExtension::class) -class RemoteConfigIntegrationTest { +class RemoteConfigIntegrationTest : AnnotationSpec() { + @Rule + @JvmField + val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") + + @Rule + @JvmField + val connectionRule = ConnectionRule(application) private companion object { private const val APP_ID = "EMS1F-17E15" @@ -28,7 +36,7 @@ class RemoteConfigIntegrationTest { get() = InstrumentationRegistry.getTargetContext().applicationContext as Application - @BeforeEach + @Before fun setup() { DatabaseTestUtils.deleteCoreDatabase() @@ -44,7 +52,7 @@ class RemoteConfigIntegrationTest { latch = CountDownLatch(1) } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys(application) } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigLoaderTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigLoaderTest.kt index b4464e0f..89559f32 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigLoaderTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigLoaderTest.kt @@ -2,16 +2,15 @@ package com.emarsys.config import android.app.Application import android.content.SharedPreferences +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doReturn import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.whenever -class ConfigLoaderTest { +class ConfigLoaderTest : AnnotationSpec() { companion object { private const val SHARED_PREF_NAME = "testPrefName" const val APP_CODE = "testAppCode" @@ -24,7 +23,7 @@ class ConfigLoaderTest { private lateinit var mockSharedPreferences: SharedPreferences private lateinit var mockApplication : Application - @BeforeEach + @Before fun setUp() { mockSharedPreferences = mock() mockApplication = mock { diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigTest.kt index aa64b323..6ed8cca4 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/config/ConfigTest.kt @@ -1,25 +1,26 @@ package com.emarsys.config + import com.emarsys.core.api.notification.NotificationSettings import com.emarsys.core.api.result.CompletionListener import com.emarsys.core.endpoint.ServiceEndpointProvider import com.emarsys.di.FakeDependencyContainer import com.emarsys.di.setupEmarsysComponent +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.IntegrationTestUtils import com.emarsys.testUtil.mockito.whenever -import com.emarsys.testUtil.rules.DuplicatedThreadExtension +import com.emarsys.testUtil.rules.DuplicatedThreadRule import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith +import org.junit.Rule import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.mockito.kotlin.doReturn -@ExtendWith(DuplicatedThreadExtension::class) -class ConfigTest { +class ConfigTest : AnnotationSpec() { + @Rule + @JvmField + val duplicateThreadRule = DuplicatedThreadRule("CoreSDKHandlerThread") companion object { private const val CLIENT_HOST = "https://me-client.eservice.emarsys.net" @@ -30,7 +31,7 @@ class ConfigTest { lateinit var config: Config lateinit var mockConfigInternal: ConfigInternal - @BeforeEach + @Before fun setUp() { mockConfigInternal = mock(ConfigInternal::class.java) val mockClientServiceProvider: ServiceEndpointProvider = org.mockito.kotlin.mock { @@ -54,7 +55,7 @@ class ConfigTest { } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } @@ -76,7 +77,10 @@ class ConfigTest { config.changeApplicationCode("testApplicationCode", mockCompletionListener) - verify(mockConfigInternal).changeApplicationCode("testApplicationCode", mockCompletionListener) + verify(mockConfigInternal).changeApplicationCode( + "testApplicationCode", + mockCompletionListener + ) } @Test diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/config/EmarsysConfigTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/config/EmarsysConfigTest.kt index c47ed96b..5d04b30c 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/config/EmarsysConfigTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/config/EmarsysConfigTest.kt @@ -1,5 +1,6 @@ package com.emarsys.config + import android.app.Application import com.emarsys.common.feature.InnerFeature import com.emarsys.core.api.experimental.FlipperFeature @@ -7,18 +8,16 @@ import com.emarsys.core.endpoint.ServiceEndpointProvider import com.emarsys.di.FakeDependencyContainer import com.emarsys.di.setupEmarsysComponent import com.emarsys.mobileengage.api.event.EventHandler +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.FeatureTestUtils import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.IntegrationTestUtils import io.kotest.assertions.fail import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock -class EmarsysConfigTest { +class EmarsysConfigTest : AnnotationSpec() { companion object { private const val APP_ID = "appID" private const val MERCHANT_ID = "MERCHANT_ID" @@ -36,7 +35,7 @@ class EmarsysConfigTest { private var automaticPushTokenSending = false - @BeforeEach + @Before fun setUp() { FeatureTestUtils.resetFeatures() val mockClientServiceProvider: ServiceEndpointProvider = mock { @@ -67,7 +66,7 @@ class EmarsysConfigTest { ) } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys(application) } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/deeplink/DeepLinkTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/deeplink/DeepLinkTest.kt index 812f80f4..23496b18 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/deeplink/DeepLinkTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/deeplink/DeepLinkTest.kt @@ -1,26 +1,25 @@ package com.emarsys.deeplink + import android.app.Activity import android.content.Intent import com.emarsys.core.api.result.CompletionListener import com.emarsys.di.FakeDependencyContainer import com.emarsys.di.setupEmarsysComponent import com.emarsys.mobileengage.deeplink.DeepLinkInternal +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.IntegrationTestUtils -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify -class DeepLinkTest { +class DeepLinkTest : AnnotationSpec() { private lateinit var mockActivity: Activity private lateinit var mockCompletionListener: CompletionListener private lateinit var mockDeepLinkInternal: DeepLinkInternal private lateinit var deeplinkApi: DeepLink - @BeforeEach + @Before fun setUp() { mockActivity = mock() mockCompletionListener = mock() @@ -31,7 +30,7 @@ class DeepLinkTest { deepLinkInternal = mockDeepLinkInternal)) } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/di/EmarsysDependencyInjectionTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/di/EmarsysDependencyInjectionTest.kt index dcdb751a..a2cf3c6a 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/di/EmarsysDependencyInjectionTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/di/EmarsysDependencyInjectionTest.kt @@ -1,15 +1,14 @@ package com.emarsys.di import com.emarsys.geofence.Geofence +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.IntegrationTestUtils import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock -class EmarsysDependencyInjectionTest { +class EmarsysDependencyInjectionTest : AnnotationSpec() { - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/eventservice/EventServiceTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/eventservice/EventServiceTest.kt index 30100bd7..91a2dd21 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/eventservice/EventServiceTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/eventservice/EventServiceTest.kt @@ -1,17 +1,16 @@ package com.emarsys.eventservice + import com.emarsys.core.api.result.CompletionListener import com.emarsys.di.FakeDependencyContainer import com.emarsys.di.setupEmarsysComponent import com.emarsys.mobileengage.event.EventServiceInternal +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.IntegrationTestUtils -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify -class EventServiceTest { +class EventServiceTest : AnnotationSpec() { companion object { private const val EVENT_NAME = "testEventName" private val EVENT_ATTRIBUTES = mapOf( @@ -25,7 +24,7 @@ class EventServiceTest { private lateinit var eventServiceApi: EventServiceApi - @BeforeEach + @Before fun setUp() { mockCompletionListener = mock() mockEventServiceInternal = mock() @@ -34,7 +33,7 @@ class EventServiceTest { setupEmarsysComponent(FakeDependencyContainer(eventServiceInternal = mockEventServiceInternal)) } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/geofence/GeofenceTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/geofence/GeofenceTest.kt index aecf297a..9179b1d5 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/geofence/GeofenceTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/geofence/GeofenceTest.kt @@ -1,25 +1,24 @@ package com.emarsys.geofence + import com.emarsys.core.api.result.CompletionListener import com.emarsys.di.FakeDependencyContainer import com.emarsys.di.setupEmarsysComponent import com.emarsys.mobileengage.api.event.EventHandler import com.emarsys.mobileengage.geofence.GeofenceInternal +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.IntegrationTestUtils -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.verify -class GeofenceTest { +class GeofenceTest : AnnotationSpec() { private lateinit var geofenceProxy: GeofenceApi private lateinit var mockGeofenceInternal: GeofenceInternal - @BeforeEach + @Before fun setUp() { mockGeofenceInternal = mock() val dependencyContainer = FakeDependencyContainer(geofenceInternal = mockGeofenceInternal) @@ -29,7 +28,7 @@ class GeofenceTest { geofenceProxy = Geofence() } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/inapp/ui/InlineInAppViewTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/inapp/ui/InlineInAppViewTest.kt index 0cc7203c..51329d0d 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/inapp/ui/InlineInAppViewTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/inapp/ui/InlineInAppViewTest.kt @@ -1,5 +1,6 @@ package com.emarsys.inapp.ui + import androidx.test.core.app.ActivityScenario import com.emarsys.core.CoreCompletionHandler import com.emarsys.core.api.ResponseErrorException @@ -20,15 +21,13 @@ import com.emarsys.mobileengage.iam.model.InAppMetaData import com.emarsys.mobileengage.iam.webview.IamWebView import com.emarsys.mobileengage.iam.webview.IamWebViewFactory import com.emarsys.mobileengage.request.MobileEngageRequestModelFactory +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ExtensionTestUtils.runOnMain import com.emarsys.testUtil.IntegrationTestUtils import com.emarsys.testUtil.fake.FakeActivity import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import org.json.JSONObject -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito.spy import org.mockito.kotlin.any import org.mockito.kotlin.doReturn @@ -39,7 +38,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch -class InlineInAppViewTest { +class InlineInAppViewTest : AnnotationSpec() { private companion object { const val VIEW_ID = "testViewId" const val OTHER_VIEW_ID = "testViewId2" @@ -60,7 +59,7 @@ class InlineInAppViewTest { private lateinit var scenario: ActivityScenario - @BeforeEach + @Before fun setUp() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() @@ -106,7 +105,7 @@ class InlineInAppViewTest { runOnMain {} } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys() scenario.close() diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/inbox/MessageInboxTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/inbox/MessageInboxTest.kt index ebe2479a..a2a28e3a 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/inbox/MessageInboxTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/inbox/MessageInboxTest.kt @@ -1,5 +1,6 @@ package com.emarsys.inbox + import com.emarsys.core.api.result.CompletionListener import com.emarsys.core.api.result.ResultListener import com.emarsys.core.api.result.Try @@ -7,16 +8,14 @@ import com.emarsys.di.FakeDependencyContainer import com.emarsys.di.setupEmarsysComponent import com.emarsys.mobileengage.api.inbox.InboxResult import com.emarsys.mobileengage.inbox.MessageInboxInternal +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.IntegrationTestUtils -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.verify -class MessageInboxTest { +class MessageInboxTest : AnnotationSpec() { private companion object { private const val TAG = "READ" private const val MESSAGE_ID = Integer.MAX_VALUE.toString() @@ -25,7 +24,7 @@ class MessageInboxTest { private lateinit var inbox: MessageInboxApi private lateinit var mockInboxInternal: MessageInboxInternal - @BeforeEach + @Before fun setUp() { mockInboxInternal = mock() val dependencyContainer = FakeDependencyContainer(messageInboxInternal = mockInboxInternal) @@ -34,7 +33,7 @@ class MessageInboxTest { inbox = MessageInbox() } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/MobileEngageTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/MobileEngageTest.kt index 59083bc3..d540c263 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/MobileEngageTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/MobileEngageTest.kt @@ -1,27 +1,27 @@ package com.emarsys.mobileengage + import com.emarsys.core.api.result.CompletionListener import com.emarsys.di.FakeDependencyContainer import com.emarsys.di.setupEmarsysComponent +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.IntegrationTestUtils -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify -class MobileEngageTest { +class MobileEngageTest : AnnotationSpec() { companion object { private const val CONTACT_FIELD_ID = 999 private const val CONTACT_FIELD_VALUE = "testContactFieldValue" private const val CONTACT_ID_TOKEN = "idTOKENTOKENTOKENidTOKEN" } + private lateinit var mockMobileEngageInternal: MobileEngageInternal private lateinit var mockCompletionListener: CompletionListener private lateinit var mobileEngageApi: MobileEngage - @BeforeEach + @Before fun setUp() { mockMobileEngageInternal = mock() mockCompletionListener = mock() @@ -30,7 +30,7 @@ class MobileEngageTest { setupEmarsysComponent(FakeDependencyContainer(mobileEngageInternal = mockMobileEngageInternal)) } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/service/mapper/RemoteMessageMapperFactoryTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/service/mapper/RemoteMessageMapperFactoryTest.kt index 12b90045..290a1a25 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/service/mapper/RemoteMessageMapperFactoryTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/mobileengage/service/mapper/RemoteMessageMapperFactoryTest.kt @@ -3,20 +3,19 @@ package com.emarsys.mobileengage.service.mapper import android.content.Context import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.resource.MetaDataReader +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock -class RemoteMessageMapperFactoryTest { +class RemoteMessageMapperFactoryTest : AnnotationSpec() { private lateinit var mockMetaDataReader: MetaDataReader private lateinit var context: Context private lateinit var mockUuidProvider: UUIDProvider private lateinit var remoteMessageMapperFactory: RemoteMessageMapperFactory - @BeforeEach + @Before fun init() { mockMetaDataReader = mock() context = InstrumentationRegistry.getTargetContext() diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/oneventaction/OnEventActionTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/oneventaction/OnEventActionTest.kt index d1e0f22a..5eb606c5 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/oneventaction/OnEventActionTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/oneventaction/OnEventActionTest.kt @@ -1,27 +1,26 @@ package com.emarsys.oneventaction + import android.content.Context import com.emarsys.di.FakeDependencyContainer import com.emarsys.di.setupEmarsysComponent import com.emarsys.mobileengage.api.event.EventHandler import com.emarsys.mobileengage.event.CacheableEventHandler +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.IntegrationTestUtils import org.json.JSONObject -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.verify -class OnEventActionTest { +class OnEventActionTest : AnnotationSpec() { private lateinit var mockEventHandler: EventHandler private lateinit var onEventAction: OnEventAction private lateinit var mockOnEventActionCacheableEventHandler: CacheableEventHandler - @BeforeEach + @Before fun setUp() { mockEventHandler = mock() mockOnEventActionCacheableEventHandler = mock() @@ -33,7 +32,7 @@ class OnEventActionTest { onEventAction = OnEventAction() } - @AfterEach + @After fun tearDown() { IntegrationTestUtils.tearDownEmarsys() } diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/predict/PredictRestrictedTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/predict/PredictRestrictedTest.kt index c8a7dec1..db42a4ae 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/predict/PredictRestrictedTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/predict/PredictRestrictedTest.kt @@ -5,13 +5,13 @@ import com.emarsys.di.FakeDependencyContainer import com.emarsys.di.emarsys import com.emarsys.di.setupEmarsysComponent import com.emarsys.di.tearDownEmarsysComponent -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test + + +import com.emarsys.testUtil.AnnotationSpec import org.mockito.Mockito import org.mockito.kotlin.mock -class PredictRestrictedTest { +class PredictRestrictedTest : AnnotationSpec() { private companion object { const val CONTACT_FIELD_ID = 999 } @@ -20,7 +20,7 @@ class PredictRestrictedTest { private lateinit var predictRestricted: PredictRestricted - @BeforeEach + @Before fun setUp() { mockPredictInternal = mock() @@ -30,7 +30,7 @@ class PredictRestrictedTest { predictRestricted = PredictRestricted() } - @AfterEach + @After fun tearDown() { try { emarsys().concurrentHandlerHolder.coreLooper.quit() diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/provider/SharedHardwareIdentificationContentProviderTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/provider/SharedHardwareIdentificationContentProviderTest.kt index fc638539..61f29906 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/provider/SharedHardwareIdentificationContentProviderTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/provider/SharedHardwareIdentificationContentProviderTest.kt @@ -5,14 +5,13 @@ import android.database.Cursor import android.net.Uri import com.emarsys.core.database.CoreSQLiteDatabase import com.emarsys.core.database.helper.CoreDbHelper +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ReflectionTestUtils import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -class SharedHardwareIdentificationContentProviderTest { +class SharedHardwareIdentificationContentProviderTest : AnnotationSpec() { private companion object { const val ENCRYPTED_HARDWARE_ID = "encrypted_hardware_id" @@ -25,7 +24,7 @@ class SharedHardwareIdentificationContentProviderTest { private lateinit var mockCursor: Cursor private lateinit var provider: SharedHardwareIdentificationContentProvider - @BeforeEach + @Before fun setUp() { mockCursor = mockk { every { getString(0) } returns ENCRYPTED_HARDWARE_ID diff --git a/emarsys/build.gradle.kts b/emarsys/build.gradle.kts index 11d1e7f0..0ff6eec1 100644 --- a/emarsys/build.gradle.kts +++ b/emarsys/build.gradle.kts @@ -27,15 +27,21 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArguments["runnerBuilder"] = - "de.mannodermaus.junit5.AndroidJUnit5Builder" } compileOptions { isCoreLibraryDesugaringEnabled = true } packaging { resources { - excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + excludes += arrayOf( + "README.txt", + "META-INF/LICENSE.md", + "META-INF/LICENSE-notice.md", + "**/attach_hotspot_windows.dll", + "META-INF/AL2.0", + "META-INF/LGPL2.1", + "META-INF/licenses/ASM" + ) } } } diff --git a/emarsys/src/androidTest/java/com/emarsys/EmarsysRequestModelFactoryTest.kt b/emarsys/src/androidTest/java/com/emarsys/EmarsysRequestModelFactoryTest.kt index 8cd34c7c..86c012a1 100644 --- a/emarsys/src/androidTest/java/com/emarsys/EmarsysRequestModelFactoryTest.kt +++ b/emarsys/src/androidTest/java/com/emarsys/EmarsysRequestModelFactoryTest.kt @@ -6,15 +6,13 @@ import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.request.model.RequestMethod import com.emarsys.core.request.model.RequestModel import com.emarsys.mobileengage.MobileEngageRequestContext -import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test +import com.emarsys.testUtil.AnnotationSpec +import io.kotest.matchers.shouldBe import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock -class EmarsysRequestModelFactoryTest { +class EmarsysRequestModelFactoryTest : AnnotationSpec() { companion object { const val HARDWARE_ID = "hardware_id" @@ -30,7 +28,7 @@ class EmarsysRequestModelFactoryTest { private lateinit var mockMobileEngageRequestContext: MobileEngageRequestContext - @BeforeEach + @Before fun setUp() { mockTimeStampProvider = mock { on { provideTimestamp() } doReturn TIMESTAMP diff --git a/emarsys/src/androidTest/java/com/emarsys/config/DefaultConfigInternalTest.kt b/emarsys/src/androidTest/java/com/emarsys/config/DefaultConfigInternalTest.kt index 09a0af14..10a1ea61 100644 --- a/emarsys/src/androidTest/java/com/emarsys/config/DefaultConfigInternalTest.kt +++ b/emarsys/src/androidTest/java/com/emarsys/config/DefaultConfigInternalTest.kt @@ -1,5 +1,6 @@ package com.emarsys.config + import com.emarsys.EmarsysRequestModelFactory import com.emarsys.common.feature.InnerFeature import com.emarsys.config.model.RemoteConfig @@ -33,13 +34,11 @@ import com.emarsys.mobileengage.client.ClientServiceInternal import com.emarsys.mobileengage.push.PushInternal import com.emarsys.predict.PredictInternal import com.emarsys.predict.request.PredictRequestContext +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ExtensionTestUtils.tryCast import com.emarsys.testUtil.FeatureTestUtils import com.emarsys.testUtil.mockito.ThreadSpy import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doAnswer @@ -56,7 +55,7 @@ import org.mockito.kotlin.verifyNoMoreInteractions import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch -class DefaultConfigInternalTest { +class DefaultConfigInternalTest : AnnotationSpec() { private companion object { const val APPLICATION_CODE = "applicationCode" const val MERCHANT_ID = "merchantId" @@ -98,7 +97,7 @@ class DefaultConfigInternalTest { private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun setUp() { FeatureTestUtils.resetFeatures() @@ -187,7 +186,7 @@ class DefaultConfigInternalTest { ) } - @AfterEach + @After fun tearDown() { FeatureTestUtils.resetFeatures() } diff --git a/emarsys/src/androidTest/java/com/emarsys/config/FetchRemoteConfigActionTest.kt b/emarsys/src/androidTest/java/com/emarsys/config/FetchRemoteConfigActionTest.kt index ebd3be39..8c670a36 100644 --- a/emarsys/src/androidTest/java/com/emarsys/config/FetchRemoteConfigActionTest.kt +++ b/emarsys/src/androidTest/java/com/emarsys/config/FetchRemoteConfigActionTest.kt @@ -4,23 +4,23 @@ import com.emarsys.core.api.result.CompletionListener import com.emarsys.fake.FakeEmarsysDependencyContainer import com.emarsys.mobileengage.di.setupMobileEngageComponent import com.emarsys.mobileengage.di.tearDownMobileEngageComponent -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test + + +import com.emarsys.testUtil.AnnotationSpec import org.mockito.Mockito.verify import org.mockito.kotlin.mock import org.mockito.kotlin.timeout import org.mockito.kotlin.times import org.mockito.kotlin.whenever -class FetchRemoteConfigActionTest { +class FetchRemoteConfigActionTest : AnnotationSpec() { private lateinit var fetchAction: FetchRemoteConfigAction private lateinit var mockConfigInternal: ConfigInternal private lateinit var mockCompletionListener: CompletionListener - @BeforeEach + @Before fun setup() { mockConfigInternal = mock() mockCompletionListener = mock() @@ -31,7 +31,7 @@ class FetchRemoteConfigActionTest { FetchRemoteConfigAction(mockConfigInternal, completionListener = mockCompletionListener) } - @AfterEach + @After fun tearDown() { tearDownMobileEngageComponent() } diff --git a/emarsys/src/androidTest/java/com/emarsys/config/RemoteConfigResponseMapperTest.kt b/emarsys/src/androidTest/java/com/emarsys/config/RemoteConfigResponseMapperTest.kt index cfd3ca50..057e9192 100644 --- a/emarsys/src/androidTest/java/com/emarsys/config/RemoteConfigResponseMapperTest.kt +++ b/emarsys/src/androidTest/java/com/emarsys/config/RemoteConfigResponseMapperTest.kt @@ -1,22 +1,20 @@ package com.emarsys.config + import com.emarsys.common.feature.InnerFeature import com.emarsys.config.model.RemoteConfig import com.emarsys.core.provider.hardwareid.HardwareIdProvider import com.emarsys.core.provider.random.RandomProvider import com.emarsys.core.response.ResponseModel import com.emarsys.core.util.log.LogLevel +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito.mock import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock -class RemoteConfigResponseMapperTest { +class RemoteConfigResponseMapperTest : AnnotationSpec() { private lateinit var mockResponseModel: ResponseModel @@ -25,7 +23,7 @@ class RemoteConfigResponseMapperTest { private lateinit var remoteConfigResponseMapper: RemoteConfigResponseMapper - @BeforeEach + @Before fun setup() { mockResponseModel = mock(ResponseModel::class.java) mockRandomProvider = mock(RandomProvider::class.java) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 14463451..b392166a 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -104,6 +104,7 @@ androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "androidx io-coil = { module = "io.coil-kt:coil-compose", version.ref = "io-coil" } io-coil-compose = { module = "io.coil-kt:coil", version.ref = "io-coil" } junit = { group = "junit", name = "junit", version.ref = "junit" } +kotest-runner-junit4 = { module = "io.kotest:kotest-runner-junit4", version.ref = "kotest" } kotest-assertions-core = { module = "io.kotest:kotest-assertions-core", version.ref = "kotest" } kotest-framework-engine = { module = "io.kotest:kotest-framework-engine", version.ref = "kotest" } mockk-android = { module = "io.mockk:mockk-android", version.ref = "mockk" } diff --git a/mobile-engage-api/build.gradle.kts b/mobile-engage-api/build.gradle.kts index e094252d..5438e861 100644 --- a/mobile-engage-api/build.gradle.kts +++ b/mobile-engage-api/build.gradle.kts @@ -23,15 +23,21 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArguments["runnerBuilder"] = - "de.mannodermaus.junit5.AndroidJUnit5Builder" } compileOptions { isCoreLibraryDesugaringEnabled = true } packaging { resources { - excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + excludes += arrayOf( + "README.txt", + "META-INF/LICENSE.md", + "META-INF/LICENSE-notice.md", + "**/attach_hotspot_windows.dll", + "META-INF/AL2.0", + "META-INF/LGPL2.1", + "META-INF/licenses/ASM" + ) } } } diff --git a/mobile-engage-api/src/androidTest/java/com/emarsys/mobileengage/api/MEApiTest.kt b/mobile-engage-api/src/androidTest/java/com/emarsys/mobileengage/api/MEApiTest.kt index c5f18a4b..7a340f3b 100644 --- a/mobile-engage-api/src/androidTest/java/com/emarsys/mobileengage/api/MEApiTest.kt +++ b/mobile-engage-api/src/androidTest/java/com/emarsys/mobileengage/api/MEApiTest.kt @@ -1,10 +1,10 @@ package com.emarsys.mobileengage.api -import org.junit.jupiter.api.Test +import com.emarsys.testUtil.AnnotationSpec -class MEApiTest { +class MEApiTest : AnnotationSpec() { @Test diff --git a/mobile-engage/build.gradle.kts b/mobile-engage/build.gradle.kts index fde89e99..7602e257 100644 --- a/mobile-engage/build.gradle.kts +++ b/mobile-engage/build.gradle.kts @@ -27,8 +27,6 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArguments["runnerBuilder"] = - "de.mannodermaus.junit5.AndroidJUnit5Builder" } compileOptions { isCoreLibraryDesugaringEnabled = true @@ -36,7 +34,15 @@ android { packaging { resources { - excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + excludes += arrayOf( + "README.txt", + "META-INF/LICENSE.md", + "META-INF/LICENSE-notice.md", + "**/attach_hotspot_windows.dll", + "META-INF/AL2.0", + "META-INF/LGPL2.1", + "META-INF/licenses/ASM" + ) } } } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/DefaultMobileEngageInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/DefaultMobileEngageInternalTest.kt index 914b156a..c7df9451 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/DefaultMobileEngageInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/DefaultMobileEngageInternalTest.kt @@ -12,8 +12,8 @@ import com.emarsys.mobileengage.push.PushInternal import com.emarsys.mobileengage.request.MobileEngageRequestModelFactory import com.emarsys.mobileengage.session.MobileEngageSession import com.emarsys.mobileengage.session.SessionIdHolder -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test + +import com.emarsys.testUtil.AnnotationSpec import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer import org.mockito.kotlin.eq @@ -29,7 +29,7 @@ import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit -class DefaultMobileEngageInternalTest { +class DefaultMobileEngageInternalTest : AnnotationSpec() { private companion object { const val CONTACT_FIELD_ID = 999 @@ -75,7 +75,7 @@ class DefaultMobileEngageInternalTest { private lateinit var mockSessionIdHolder: SessionIdHolder - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun setUp() { mockEventServiceInternal = mock() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/MobileEngageRequestContextTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/MobileEngageRequestContextTest.kt index 9ec37f05..c8dc7241 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/MobileEngageRequestContextTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/MobileEngageRequestContextTest.kt @@ -1,15 +1,14 @@ package com.emarsys.mobileengage +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock -class MobileEngageRequestContextTest { +class MobileEngageRequestContextTest : AnnotationSpec() { private lateinit var requestContext: MobileEngageRequestContext - @BeforeEach + @Before fun setUp() { requestContext = MobileEngageRequestContext( diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/client/DefaultClientServiceInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/client/DefaultClientServiceInternalTest.kt index 9f482178..f12933f2 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/client/DefaultClientServiceInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/client/DefaultClientServiceInternalTest.kt @@ -1,17 +1,15 @@ package com.emarsys.mobileengage.client + import com.emarsys.core.request.RequestManager import com.emarsys.core.request.model.RequestModel import com.emarsys.mobileengage.request.MobileEngageRequestModelFactory +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito import org.mockito.Mockito.verify -class DefaultClientServiceInternalTest { +class DefaultClientServiceInternalTest : AnnotationSpec() { private lateinit var mockRequestModelFactory: MobileEngageRequestModelFactory private lateinit var mockRequestModel: RequestModel @@ -19,7 +17,7 @@ class DefaultClientServiceInternalTest { private lateinit var clientServiceInternal: ClientServiceInternal - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun setUp() { mockRequestModel = Mockito.mock(RequestModel::class.java) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DeepLinkActionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DeepLinkActionTest.kt index a82e9d40..f3abf13b 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DeepLinkActionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DeepLinkActionTest.kt @@ -6,16 +6,16 @@ import com.emarsys.mobileengage.di.setupMobileEngageComponent import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.util.waitForTask -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test + + +import com.emarsys.testUtil.AnnotationSpec import org.mockito.Mockito import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever -class DeepLinkActionTest { +class DeepLinkActionTest : AnnotationSpec() { companion object { init { Mockito.mock(Intent::class.java) @@ -27,7 +27,7 @@ class DeepLinkActionTest { private lateinit var action: DeepLinkAction - @BeforeEach + @Before fun setUp() { setupMobileEngageComponent(FakeMobileEngageDependencyContainer()) @@ -36,7 +36,7 @@ class DeepLinkActionTest { action = DeepLinkAction(deepLinkInternal) } - @AfterEach + @After fun tearDown() { tearDownMobileEngageComponent() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternalTest.kt index 444f78d5..f2057aa5 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/deeplink/DefaultDeepLinkInternalTest.kt @@ -14,9 +14,8 @@ import com.emarsys.core.request.model.RequestModel import com.emarsys.core.storage.StringStorage import com.emarsys.mobileengage.MobileEngageRequestContext import com.emarsys.mobileengage.session.SessionIdHolder +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.ArgumentMatchers.eq import org.mockito.Mockito import org.mockito.Mockito.mock @@ -27,7 +26,7 @@ import org.mockito.kotlin.isNull import org.mockito.kotlin.verify import org.mockito.kotlin.whenever -class DefaultDeepLinkInternalTest { +class DefaultDeepLinkInternalTest : AnnotationSpec() { private lateinit var mockActivity: Activity private lateinit var deepLinkInternal: DeepLinkInternal private lateinit var mockManager: RequestManager @@ -37,7 +36,7 @@ class DefaultDeepLinkInternalTest { private lateinit var mockDeviceInfo: DeviceInfo private lateinit var mockDeepLinkServiceProvider: ServiceEndpointProvider - @BeforeEach + @Before fun init() { mockActivity = mock(Activity::class.java, Mockito.RETURNS_DEEP_STUBS) mockManager = mock(RequestManager::class.java) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/device/DeviceInfoStartActionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/device/DeviceInfoStartActionTest.kt index 607d8eb4..88b4c545 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/device/DeviceInfoStartActionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/device/DeviceInfoStartActionTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.device + import com.emarsys.core.device.DeviceInfo import com.emarsys.core.storage.Storage import com.emarsys.mobileengage.client.ClientServiceInternal @@ -7,16 +8,14 @@ import com.emarsys.mobileengage.di.setupMobileEngageComponent import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.util.waitForTask +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.SharedPrefsUtils import com.emarsys.testUtil.mockito.whenever -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions -class DeviceInfoStartActionTest { +class DeviceInfoStartActionTest : AnnotationSpec() { private lateinit var deviceInfoPayloadStorage: Storage private lateinit var mockClientServiceInternal: ClientServiceInternal @@ -24,7 +23,7 @@ class DeviceInfoStartActionTest { private lateinit var mockDeviceInfo: DeviceInfo - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun setUp() { deviceInfoPayloadStorage = mock() @@ -41,7 +40,7 @@ class DeviceInfoStartActionTest { } - @AfterEach + @After fun tearDown() { SharedPrefsUtils.clearSharedPrefs("emarsys_secure_shared_preferences") tearDownMobileEngageComponent() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/CacheableEventHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/CacheableEventHandlerTest.kt index 5916e9ab..a72f7094 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/CacheableEventHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/CacheableEventHandlerTest.kt @@ -3,21 +3,20 @@ package com.emarsys.mobileengage.event import android.content.Context import com.emarsys.common.feature.InnerFeature import com.emarsys.core.feature.FeatureRegistry +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.FeatureTestUtils import com.emarsys.testUtil.ReflectionTestUtils import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import org.json.JSONObject -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock -internal class CacheableEventHandlerTest { +internal class CacheableEventHandlerTest : AnnotationSpec() { private lateinit var cacheableEventHandler: CacheableEventHandler - @BeforeEach + @Before fun setUp() { FeatureTestUtils.resetFeatures() cacheableEventHandler = CacheableEventHandler() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/DefaultEventServiceInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/DefaultEventServiceInternalTest.kt index e985c79a..68062321 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/DefaultEventServiceInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/event/DefaultEventServiceInternalTest.kt @@ -1,19 +1,17 @@ package com.emarsys.mobileengage.event + import com.emarsys.core.api.result.CompletionListener import com.emarsys.core.request.RequestManager import com.emarsys.core.request.model.RequestModel import com.emarsys.mobileengage.request.MobileEngageRequestModelFactory +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.mockito.kotlin.spy -class DefaultEventServiceInternalTest { +class DefaultEventServiceInternalTest : AnnotationSpec() { companion object { const val REQUEST_ID = "request_id" @@ -31,7 +29,7 @@ class DefaultEventServiceInternalTest { private lateinit var eventServiceInternal: EventServiceInternal - @BeforeEach + @Before fun setUp() { mockRequestModel = mock(RequestModel::class.java) mockRequestManager = mock(RequestManager::class.java) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt index b38b0b72..7f695c88 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt @@ -26,6 +26,7 @@ import com.emarsys.mobileengage.geofence.model.GeofenceResponse import com.emarsys.mobileengage.geofence.model.TriggeringEmarsysGeofence import com.emarsys.mobileengage.notification.ActionCommandFactory import com.emarsys.mobileengage.request.MobileEngageRequestModelFactory +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ReflectionTestUtils import com.emarsys.testUtil.mockito.whenever import com.google.android.gms.location.FusedLocationProviderClient @@ -36,8 +37,6 @@ import com.google.android.gms.tasks.OnCompleteListener import com.google.android.gms.tasks.Task import io.kotest.matchers.shouldBe import org.json.JSONObject -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito.spy import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor @@ -50,7 +49,7 @@ import org.mockito.kotlin.verifyNoInteractions import java.util.concurrent.CountDownLatch import com.emarsys.mobileengage.api.geofence.Geofence as MEGeofence -class DefaultGeofenceInternalTest { +class DefaultGeofenceInternalTest : AnnotationSpec() { private companion object { val refreshTrigger = Trigger( @@ -106,7 +105,7 @@ class DefaultGeofenceInternalTest { private lateinit var pendingIntent: PendingIntent private lateinit var mockTask: Task - @BeforeEach + @Before fun setUp() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() mockInitialEnterTriggerEnabledStorage = mock() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/FetchGeofencesActionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/FetchGeofencesActionTest.kt index c40baa0e..b0da646c 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/FetchGeofencesActionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/FetchGeofencesActionTest.kt @@ -5,21 +5,20 @@ import com.emarsys.mobileengage.di.setupMobileEngageComponent import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.util.waitForTask -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test + + +import com.emarsys.testUtil.AnnotationSpec import org.mockito.kotlin.mock import org.mockito.kotlin.verify -class FetchGeofencesActionTest { - +class FetchGeofencesActionTest : AnnotationSpec() { private lateinit var mockGeofenceInternal: GeofenceInternal private lateinit var mockActivity: Activity private lateinit var fetchGeofencesAction: FetchGeofencesAction - @BeforeEach + @Before fun setUp() { mockGeofenceInternal = mock() mockActivity = mock() @@ -29,7 +28,7 @@ class FetchGeofencesActionTest { fetchGeofencesAction = FetchGeofencesAction(mockGeofenceInternal) } - @AfterEach + @After fun tearDown() { tearDownMobileEngageComponent() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceFilterTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceFilterTest.kt index d2614d99..f1fc7690 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceFilterTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceFilterTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.geofence + import android.location.Location import android.location.LocationManager import com.emarsys.mobileengage.api.geofence.Geofence @@ -7,14 +8,12 @@ import com.emarsys.mobileengage.api.geofence.Trigger import com.emarsys.mobileengage.api.geofence.TriggerType import com.emarsys.mobileengage.geofence.model.GeofenceGroup import com.emarsys.mobileengage.geofence.model.GeofenceResponse +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe import org.json.JSONObject -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test -class GeofenceFilterTest { +class GeofenceFilterTest : AnnotationSpec() { private companion object { val currentLocation: Location = Location(LocationManager.GPS_PROVIDER).apply { @@ -23,11 +22,11 @@ class GeofenceFilterTest { } val trigger = Trigger(id = "triggerId", type = TriggerType.ENTER, action = JSONObject()) val allGeofences = listOf( - Geofence("geofenceId1", 47.493160, 19.058355, 10.0, null, listOf(trigger)), - Geofence("geofenceId2", 47.493812, 19.058537, 10.0, null, listOf(trigger)), - Geofence("geofenceId3", 47.493827, 19.060715, 10.0, null, listOf(trigger)), - Geofence("geofenceId4", 47.489680, 19.061230, 350.0, null, listOf(trigger)), - Geofence("geofenceId5", 47.492292, 19.056440, 10.0, null, listOf(trigger)) + Geofence("geofenceId1", 47.493160, 19.058355, 10.0, null, listOf(trigger)), + Geofence("geofenceId2", 47.493812, 19.058537, 10.0, null, listOf(trigger)), + Geofence("geofenceId3", 47.493827, 19.060715, 10.0, null, listOf(trigger)), + Geofence("geofenceId4", 47.489680, 19.061230, 350.0, null, listOf(trigger)), + Geofence("geofenceId5", 47.492292, 19.056440, 10.0, null, listOf(trigger)) ) } @@ -35,7 +34,7 @@ class GeofenceFilterTest { private lateinit var geofenceFilter: GeofenceFilter - @BeforeEach + @Before fun setUp() { geofenceFilter = GeofenceFilter(allGeofences.size) } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProviderTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProviderTest.kt index 415b04af..f2ffbd5b 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProviderTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofencePendingIntentProviderTest.kt @@ -2,14 +2,15 @@ package com.emarsys.mobileengage.geofence import android.app.PendingIntent import androidx.test.platform.app.InstrumentationRegistry +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.Test -class GeofencePendingIntentProviderTest { +class GeofencePendingIntentProviderTest : AnnotationSpec() { @Test fun testProvidePendingIntent() { - val result = GeofencePendingIntentProvider(InstrumentationRegistry.getInstrumentation().context).providePendingIntent() + val result = + GeofencePendingIntentProvider(InstrumentationRegistry.getInstrumentation().context).providePendingIntent() result shouldNotBe null result::class.java shouldBe PendingIntent::class.java diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapperTest.kt index 43ccbcc7..9a2e6367 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/GeofenceResponseMapperTest.kt @@ -1,28 +1,26 @@ package com.emarsys.mobileengage.geofence + import com.emarsys.core.response.ResponseModel import com.emarsys.mobileengage.api.geofence.Geofence import com.emarsys.mobileengage.api.geofence.Trigger import com.emarsys.mobileengage.api.geofence.TriggerType import com.emarsys.mobileengage.geofence.model.GeofenceGroup import com.emarsys.mobileengage.geofence.model.GeofenceResponse +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe import org.json.JSONArray import org.json.JSONObject -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.mock import org.mockito.kotlin.whenever -class GeofenceResponseMapperTest { +class GeofenceResponseMapperTest : AnnotationSpec() { private lateinit var mockResponseModel: ResponseModel private lateinit var mapper: GeofenceResponseMapper - @BeforeEach + @Before fun setUp() { mapper = GeofenceResponseMapper() mockResponseModel = mock() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/AppStartActionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/AppStartActionTest.kt index 93a62820..a1c66dce 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/AppStartActionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/AppStartActionTest.kt @@ -7,22 +7,20 @@ import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.event.EventServiceInternal import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.util.waitForTask +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions -class AppStartActionTest { +class AppStartActionTest : AnnotationSpec() { private lateinit var mockEventServiceInternal: EventServiceInternal private lateinit var mockContactTokenStorage: Storage private lateinit var startAction: AppStartAction - @BeforeEach + @Before fun setUp() { mockEventServiceInternal = mock() mockContactTokenStorage = mock() @@ -32,7 +30,7 @@ class AppStartActionTest { startAction = AppStartAction(mockEventServiceInternal, mockContactTokenStorage) } - @AfterEach + @After fun tearDown() { tearDownMobileEngageComponent() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppEventHandlerInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppEventHandlerInternalTest.kt index b255f986..ae9f3b47 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppEventHandlerInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppEventHandlerInternalTest.kt @@ -1,18 +1,16 @@ package com.emarsys.mobileengage.iam +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test - -class InAppEventHandlerInternalTest { +class InAppEventHandlerInternalTest : AnnotationSpec() { private lateinit var inAppEventHandlerInternal: InAppEventHandlerInternal - @BeforeEach + @Before fun setUp() { inAppEventHandlerInternal = InAppEventHandlerInternal() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppInternalTest.kt index 2671388b..8b9b375d 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/InAppInternalTest.kt @@ -4,14 +4,14 @@ import com.emarsys.core.api.result.CompletionListener import com.emarsys.core.request.model.RequestModel import com.emarsys.mobileengage.api.event.EventHandler import com.emarsys.mobileengage.event.EventServiceInternal -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test + +import com.emarsys.testUtil.AnnotationSpec import org.mockito.Mockito.mock import org.mockito.Mockito.verify -class InAppInternalTest { +class InAppInternalTest : AnnotationSpec() { private companion object { const val EVENT_NAME = "customEventName" @@ -25,7 +25,7 @@ class InAppInternalTest { private lateinit var mockEventServiceInternal: EventServiceInternal - @BeforeEach + @Before fun init() { mockRequestModel = mock(RequestModel::class.java) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/OverlayInAppPresenterTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/OverlayInAppPresenterTest.kt index 9801e040..95845e8b 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/OverlayInAppPresenterTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/OverlayInAppPresenterTest.kt @@ -12,12 +12,11 @@ import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.mobileengage.iam.dialog.IamDialog import com.emarsys.mobileengage.iam.dialog.IamDialogProvider import com.emarsys.mobileengage.iam.webview.MessageLoadedListener +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.fake.FakeActivity import com.emarsys.testUtil.mockito.anyNotNull import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -25,7 +24,7 @@ import org.mockito.kotlin.times import org.mockito.kotlin.verify import java.util.concurrent.CountDownLatch -class OverlayInAppPresenterTest { +class OverlayInAppPresenterTest : AnnotationSpec() { companion object { private var SID = "testSid" private var URL = "https://www.emarsys.com" @@ -39,7 +38,7 @@ class OverlayInAppPresenterTest { private lateinit var inAppPresenter: OverlayInAppPresenter - @BeforeEach + @Before fun setUp() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() mockIamDialog = mock() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/PushToInAppActionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/PushToInAppActionTest.kt index 45e0231b..eceb2ccc 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/PushToInAppActionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/PushToInAppActionTest.kt @@ -1,14 +1,14 @@ package com.emarsys.mobileengage.iam import com.emarsys.core.provider.timestamp.TimestampProvider -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test + +import com.emarsys.testUtil.AnnotationSpec import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.whenever -class PushToInAppActionTest { +class PushToInAppActionTest : AnnotationSpec() { companion object { const val CAMPAIGN_ID = "campaignId" @@ -25,7 +25,7 @@ class PushToInAppActionTest { private lateinit var mockTimestampProvider: TimestampProvider - @BeforeEach + @Before fun setup() { mockOverlayInAppPresenter = mock() mockTimestampProvider = mock() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/SaveDisplayedIamActionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/SaveDisplayedIamActionTest.kt index 689bf205..222462ec 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/SaveDisplayedIamActionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/SaveDisplayedIamActionTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.iam + import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.database.repository.Repository import com.emarsys.core.database.repository.SqlSpecification @@ -7,17 +8,15 @@ import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.mobileengage.iam.dialog.action.SaveDisplayedIamAction import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIam +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.ThreadSpy import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.timeout import org.mockito.kotlin.verify -class SaveDisplayedIamActionTest { +class SaveDisplayedIamActionTest : AnnotationSpec() { companion object { private const val CAMPAIGN_ID = "123" private const val SID = "testSid" @@ -33,7 +32,7 @@ class SaveDisplayedIamActionTest { private lateinit var timestampProvider: TimestampProvider - @BeforeEach + @Before fun init() { runBlocking { threadSpy = ThreadSpy() @@ -49,7 +48,7 @@ class SaveDisplayedIamActionTest { } } - @AfterEach + @After fun tearDown() { handler.coreLooper.quit() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogProviderTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogProviderTest.kt index 97b5ecb4..90032fda 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogProviderTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogProviderTest.kt @@ -1,23 +1,21 @@ package com.emarsys.mobileengage.iam.dialog + import androidx.test.core.app.ActivityScenario import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.fake.FakeActivity import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import java.util.concurrent.CountDownLatch import kotlin.concurrent.thread -class IamDialogProviderTest { +class IamDialogProviderTest : AnnotationSpec() { private lateinit var iamDialogProvider: IamDialogProvider private lateinit var scenario: ActivityScenario - @BeforeEach + @Before fun setUp() { scenario = ActivityScenario.launch(FakeActivity::class.java) scenario.onActivity { activity -> @@ -31,7 +29,7 @@ class IamDialogProviderTest { } } - @AfterEach + @After fun tearDown() { scenario.close() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogTest.kt index 62a3e296..a87657ce 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/IamDialogTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.iam.dialog + import android.content.pm.ActivityInfo import android.os.Bundle import android.webkit.WebView @@ -26,15 +27,13 @@ import com.emarsys.mobileengage.iam.model.InAppMetaData import com.emarsys.mobileengage.iam.webview.IamWebView import com.emarsys.mobileengage.iam.webview.IamWebViewFactory import com.emarsys.mobileengage.iam.webview.MessageLoadedListener +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ExtensionTestUtils.runOnMain import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.ReflectionTestUtils import com.emarsys.testUtil.fake.FakeActivity import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -43,7 +42,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch -class IamDialogTest { +class IamDialogTest : AnnotationSpec() { private companion object { const val CAMPAIGN_ID = "id_value" private const val SID = "testSid" @@ -65,7 +64,7 @@ class IamDialogTest { private lateinit var iamDialog: IamDialog private lateinit var scenario: ActivityScenario - @BeforeEach + @Before fun setUp() { scenario = ActivityScenario.launch(FakeActivity::class.java) val countDownLatch = CountDownLatch(1) @@ -112,7 +111,7 @@ class IamDialogTest { countDownLatch.await() } - @AfterEach + @After fun tearDown() { tearDownMobileEngageComponent() scenario.close() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamActionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamActionTest.kt index 9e333558..5ed8a44e 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamActionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/dialog/action/SendDisplayedIamActionTest.kt @@ -1,31 +1,30 @@ package com.emarsys.mobileengage.iam.dialog.action + import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory.create import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.mobileengage.iam.InAppInternal +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.ThreadSpy -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer import org.mockito.kotlin.isNull import org.mockito.kotlin.whenever -class SendDisplayedIamActionTest { +class SendDisplayedIamActionTest : AnnotationSpec() { private lateinit var action: SendDisplayedIamAction private lateinit var handler: ConcurrentHandlerHolder private lateinit var inAppInternal: InAppInternal - @BeforeEach + @Before fun init() { handler = create() inAppInternal = Mockito.mock(InAppInternal::class.java) action = SendDisplayedIamAction(handler, inAppInternal) } - @AfterEach + @After fun tearDown() { handler.coreLooper.quit() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeFactoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeFactoryTest.kt index e418cc7e..b27c366c 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeFactoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeFactoryTest.kt @@ -1,11 +1,11 @@ package com.emarsys.mobileengage.iam.jsbridge import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock -class IamJsBridgeFactoryTest { +class IamJsBridgeFactoryTest : AnnotationSpec() { @Test fun createJsBridge_shouldReturnJSBridge() { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeTest.kt index 545d15b7..4bb812b4 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/IamJsBridgeTest.kt @@ -1,18 +1,17 @@ package com.emarsys.mobileengage.iam.jsbridge + import androidx.test.core.app.ActivityScenario import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.mobileengage.api.event.EventHandler import com.emarsys.mobileengage.iam.model.InAppMetaData import com.emarsys.mobileengage.iam.webview.IamWebView +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.fake.FakeActivity import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import org.json.JSONObject -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.ArgumentCaptor import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull @@ -26,7 +25,7 @@ import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.verifyNoMoreInteractions -class IamJsBridgeTest { +class IamJsBridgeTest : AnnotationSpec() { private val jsonObject = JSONObject( mapOf( @@ -51,7 +50,7 @@ class IamJsBridgeTest { private lateinit var captor: ArgumentCaptor private lateinit var scenario: ActivityScenario - @BeforeEach + @Before fun setUp() { scenario = ActivityScenario.launch(FakeActivity::class.java) scenario.onActivity { activity -> @@ -86,7 +85,7 @@ class IamJsBridgeTest { } } - @AfterEach + @After fun tearDown() { scenario.close() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryProviderTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryProviderTest.kt index e77ec59a..6c464bd9 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryProviderTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryProviderTest.kt @@ -8,11 +8,11 @@ import com.emarsys.core.provider.activity.CurrentActivityProvider import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.mobileengage.iam.InAppInternal import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock -class JSCommandFactoryProviderTest { +class JSCommandFactoryProviderTest : AnnotationSpec() { @Test fun provide_shouldReturnJSCommandFactory() { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryTest.kt index c1e69043..b5fe608c 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/jsbridge/JSCommandFactoryTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.iam.jsbridge + import android.app.Activity import android.content.ClipboardManager import androidx.test.core.app.ActivityScenario @@ -12,15 +13,13 @@ import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.mobileengage.iam.InAppInternal import com.emarsys.mobileengage.iam.model.InAppMetaData import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.fake.FakeActivity import com.emarsys.testUtil.mockito.ThreadSpy import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking import org.json.JSONObject -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doAnswer @@ -34,7 +33,7 @@ import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch -class JSCommandFactoryTest { +class JSCommandFactoryTest : AnnotationSpec() { private companion object { const val PROPERTY = "testProperty" const val TIMESTAMP = 1233L @@ -57,7 +56,7 @@ class JSCommandFactoryTest { private lateinit var mockClipboardManager: ClipboardManager private lateinit var scenario: ActivityScenario - @BeforeEach + @Before fun setUp() { scenario = ActivityScenario.launch(FakeActivity::class.java) val countDownLatch = CountDownLatch(1) @@ -91,7 +90,7 @@ class JSCommandFactoryTest { countDownLatch.await() } - @AfterEach + @After fun tearDown() { scenario.close() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/IamConversionUtilsTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/IamConversionUtilsTest.kt index 9d80c62d..be9a1b0e 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/IamConversionUtilsTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/IamConversionUtilsTest.kt @@ -3,12 +3,11 @@ package com.emarsys.mobileengage.iam.model import com.emarsys.core.util.TimestampUtils import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIam +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import java.util.Arrays -class IamConversionUtilsTest { +class IamConversionUtilsTest : AnnotationSpec() { private var buttonClicked1: ButtonClicked? = null private var buttonClicked2: ButtonClicked? = null private var buttonClicked3: ButtonClicked? = null @@ -16,7 +15,7 @@ class IamConversionUtilsTest { private var displayedIam2: DisplayedIam? = null private var displayedIam3: DisplayedIam? = null - @BeforeEach + @Before fun init() { buttonClicked1 = ButtonClicked("campaign1", "button1", 200) buttonClicked2 = ButtonClicked("campaign1", "button2", 400) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/buttonclicked/ButtonClickedRepositoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/buttonclicked/ButtonClickedRepositoryTest.kt index 9c8405c8..457d43f9 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/buttonclicked/ButtonClickedRepositoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/buttonclicked/ButtonClickedRepositoryTest.kt @@ -7,21 +7,20 @@ import com.emarsys.core.database.DatabaseContract import com.emarsys.core.database.helper.CoreDbHelper import com.emarsys.core.database.helper.DbHelper import com.emarsys.core.handler.ConcurrentHandlerHolder +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils.deleteCoreDatabase import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito.mock import java.util.Date -class ButtonClickedRepositoryTest { +class ButtonClickedRepositoryTest : AnnotationSpec() { private lateinit var repository: ButtonClickedRepository private lateinit var buttonClicked1: ButtonClicked private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun setUp() { deleteCoreDatabase() val context = getTargetContext() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/displayediam/DisplayedIamRepositoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/displayediam/DisplayedIamRepositoryTest.kt index f4a21ef7..cbaa0a3b 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/displayediam/DisplayedIamRepositoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/displayediam/DisplayedIamRepositoryTest.kt @@ -8,23 +8,22 @@ import com.emarsys.core.database.DatabaseContract.DISPLAYED_IAM_COLUMN_NAME_TIME import com.emarsys.core.database.helper.CoreDbHelper import com.emarsys.core.database.helper.DbHelper import com.emarsys.core.handler.ConcurrentHandlerHolder +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils.deleteCoreDatabase import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import java.util.Date -class DisplayedIamRepositoryTest { +class DisplayedIamRepositoryTest : AnnotationSpec() { private lateinit var iamRepository: DisplayedIamRepository private lateinit var displayedIam1: DisplayedIam private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun setUp() { deleteCoreDatabase() val context = getTargetContext() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/requestRepositoryProxy/RequestRepositoryProxyTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/requestRepositoryProxy/RequestRepositoryProxyTest.kt index a4e0d4d6..0b314dc3 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/requestRepositoryProxy/RequestRepositoryProxyTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/requestRepositoryProxy/RequestRepositoryProxyTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.iam.model.requestRepositoryProxy + import com.emarsys.common.feature.InnerFeature import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.database.helper.CoreDbHelper @@ -26,17 +27,15 @@ import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIam import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIamRepository import com.emarsys.mobileengage.util.RequestModelHelper import com.emarsys.mobileengage.util.RequestPayloadUtils.createCompositeRequestModelPayload +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils.deleteCoreDatabase import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.RandomTestUtils.randomString import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.* -class RequestRepositoryProxyTest { +class RequestRepositoryProxyTest : AnnotationSpec() { private lateinit var mockRequestContext: MobileEngageRequestContext private lateinit var mockRequestModelRepository: Repository private lateinit var mockDisplayedIamRepository: Repository @@ -53,7 +52,7 @@ class RequestRepositoryProxyTest { private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun setUp() { deleteCoreDatabase() val context = getTargetContext() @@ -91,7 +90,7 @@ class RequestRepositoryProxyTest { ) } - @AfterEach + @After @Throws(Exception::class) fun tearDown() { FeatureRegistry.disableFeature(InnerFeature.EVENT_SERVICE_V4) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/specification/FilterByCampaignIdTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/specification/FilterByCampaignIdTest.kt index 9e51bbc1..3bee3df3 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/specification/FilterByCampaignIdTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/model/specification/FilterByCampaignIdTest.kt @@ -8,22 +8,20 @@ import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClickedRepository import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIam import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIamRepository +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.DatabaseTestUtils import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test - -class FilterByCampaignIdTest { +class FilterByCampaignIdTest : AnnotationSpec() { private lateinit var displayedIamRepository: DisplayedIamRepository private lateinit var buttonClickedRepository: ButtonClickedRepository private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun init() { DatabaseTestUtils.deleteCoreDatabase() concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewClientTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewClientTest.kt index 65621a51..36b5a8b5 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewClientTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewClientTest.kt @@ -4,18 +4,17 @@ import android.webkit.WebView import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.mobileengage.fake.FakeMessageLoadedListener +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import java.util.concurrent.CountDownLatch -class IamWebViewClientTest { +class IamWebViewClientTest : AnnotationSpec() { private lateinit var latch: CountDownLatch private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun setUp() { latch = CountDownLatch(1) concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewFactoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewFactoryTest.kt index 2bddd5d1..84e18d0b 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewFactoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewFactoryTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.iam.webview + import androidx.test.core.app.ActivityScenario import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder @@ -8,20 +9,16 @@ import com.emarsys.mobileengage.iam.jsbridge.IamJsBridge import com.emarsys.mobileengage.iam.jsbridge.IamJsBridgeFactory import com.emarsys.mobileengage.iam.jsbridge.JSCommandFactory import com.emarsys.mobileengage.iam.jsbridge.JSCommandFactoryProvider +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ExtensionTestUtils.runOnMain import com.emarsys.testUtil.fake.FakeActivity import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import java.util.concurrent.CountDownLatch -class IamWebViewFactoryTest { +class IamWebViewFactoryTest : AnnotationSpec() { private lateinit var mockJSCommandFactoryProvider: JSCommandFactoryProvider private lateinit var mockJSCommandFactory: JSCommandFactory @@ -33,7 +30,7 @@ class IamWebViewFactoryTest { private lateinit var webViewFactory: IamWebViewFactory private lateinit var scenario: ActivityScenario - @BeforeEach + @Before fun setUp() { mockJsBridge = mock() mockJsBridgeFactory = mock { @@ -61,7 +58,7 @@ class IamWebViewFactoryTest { } } - @AfterEach + @After fun tearDown() { scenario.close() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewTest.kt index 6510460d..ca4dc191 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/iam/webview/IamWebViewTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.iam.webview + import android.app.Activity import androidx.test.core.app.ActivityScenario import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory @@ -11,18 +12,16 @@ import com.emarsys.mobileengage.iam.jsbridge.JSCommandFactory import com.emarsys.mobileengage.iam.jsbridge.OnAppEventListener import com.emarsys.mobileengage.iam.jsbridge.OnCloseListener import com.emarsys.mobileengage.iam.model.InAppMetaData +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ExtensionTestUtils.runOnMain import com.emarsys.testUtil.fake.FakeActivity import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify -class IamWebViewTest { +class IamWebViewTest : AnnotationSpec() { private lateinit var iamWebView: IamWebView private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder @@ -33,7 +32,7 @@ class IamWebViewTest { private lateinit var mockActivity: Activity private lateinit var scenario: ActivityScenario - @BeforeEach + @Before fun setUp() { concurrentHandlerHolder = ConcurrentHandlerHolderFactory.create() mockActivity = mock() @@ -63,7 +62,7 @@ class IamWebViewTest { } } - @AfterEach + @After fun tearDown() { scenario.close() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/DefaultMessageInboxInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/DefaultMessageInboxInternalTest.kt index 96cca0eb..49fb4225 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/DefaultMessageInboxInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/DefaultMessageInboxInternalTest.kt @@ -18,10 +18,9 @@ import com.emarsys.mobileengage.api.inbox.Message import com.emarsys.mobileengage.fake.FakeRestClient import com.emarsys.mobileengage.fake.FakeResultListener import com.emarsys.mobileengage.request.MobileEngageRequestModelFactory +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe import kotlinx.coroutines.CoroutineScope -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doReturn @@ -33,7 +32,7 @@ import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch -class DefaultMessageInboxInternalTest { +class DefaultMessageInboxInternalTest : AnnotationSpec() { private companion object { private const val TAG = "READ" private const val LOWER_CASED_TAG = "read" @@ -54,7 +53,7 @@ class DefaultMessageInboxInternalTest { private lateinit var message: Message - @BeforeEach + @Before fun setUp() { message = Message( "testMessageId", diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/MessageInboxResponseMapperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/MessageInboxResponseMapperTest.kt index dc62ba59..ed691cef 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/MessageInboxResponseMapperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/inbox/MessageInboxResponseMapperTest.kt @@ -7,17 +7,16 @@ import com.emarsys.mobileengage.api.action.DismissActionModel import com.emarsys.mobileengage.api.action.OpenExternalUrlActionModel import com.emarsys.mobileengage.api.inbox.InboxResult import com.emarsys.mobileengage.api.inbox.Message +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import java.net.URL -class MessageInboxResponseMapperTest { +class MessageInboxResponseMapperTest : AnnotationSpec() { private lateinit var messageInboxResponseMapper: MessageInboxResponseMapper - @BeforeEach + @Before fun setUp() { messageInboxResponseMapper = MessageInboxResponseMapper() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/ActionCommandFactoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/ActionCommandFactoryTest.kt index a62208b2..d3aff66c 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/ActionCommandFactoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/ActionCommandFactoryTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.notification + import android.content.Context import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.mobileengage.event.CacheableEventHandler @@ -7,19 +8,15 @@ import com.emarsys.mobileengage.event.EventServiceInternal import com.emarsys.mobileengage.notification.command.AppEventCommand import com.emarsys.mobileengage.notification.command.CustomEventCommand import com.emarsys.mobileengage.notification.command.OpenExternalUrlCommand +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import org.json.JSONArray import org.json.JSONObject -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.mock -class ActionCommandFactoryTest { - +class ActionCommandFactoryTest : AnnotationSpec() { private lateinit var factory: ActionCommandFactory @@ -28,7 +25,7 @@ class ActionCommandFactoryTest { private lateinit var mockEventServiceInternal: EventServiceInternal private lateinit var mockNotificationCacheableEventHandler: CacheableEventHandler - @BeforeEach + @Before fun setUp() { context = InstrumentationRegistry.getTargetContext().applicationContext diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksFactoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksFactoryTest.kt index fb9a948c..7a757a1e 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksFactoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksFactoryTest.kt @@ -1,10 +1,10 @@ package com.emarsys.mobileengage.notification +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.util.concurrent.CountDownLatch -class LaunchActivityCommandLifecycleCallbacksFactoryTest { +class LaunchActivityCommandLifecycleCallbacksFactoryTest : AnnotationSpec() { @Test fun testCreate() { val latch = CountDownLatch(1) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksTest.kt index 7b04e9dd..607b7dcb 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/LaunchActivityCommandLifecycleCallbacksTest.kt @@ -4,25 +4,27 @@ import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import androidx.test.platform.app.InstrumentationRegistry +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.fake.FakeActivity import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import java.util.concurrent.CountDownLatch -class LaunchActivityCommandLifecycleCallbacksTest { +class LaunchActivityCommandLifecycleCallbacksTest : AnnotationSpec() { private lateinit var latch: CountDownLatch private lateinit var launchIntent: Intent private lateinit var mockPackageManager: PackageManager - @BeforeEach + @Before fun setUp() { latch = CountDownLatch(1) - launchIntent = Intent(InstrumentationRegistry.getInstrumentation().targetContext, FakeActivity::class.java) + launchIntent = Intent( + InstrumentationRegistry.getInstrumentation().targetContext, + FakeActivity::class.java + ) mockPackageManager = mock { on { getLaunchIntentForPackage(any()) } doReturn launchIntent } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/NotificationCommandFactoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/NotificationCommandFactoryTest.kt index 99b00597..4bd98c80 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/NotificationCommandFactoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/NotificationCommandFactoryTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.notification + import android.app.Activity import android.content.Context import android.content.Intent @@ -27,6 +28,7 @@ import com.emarsys.mobileengage.service.IntentUtils import com.emarsys.mobileengage.service.NotificationData import com.emarsys.mobileengage.service.NotificationMethod import com.emarsys.mobileengage.service.NotificationOperation +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry import com.emarsys.testUtil.mockito.whenever import io.kotest.data.forAll @@ -36,13 +38,10 @@ import io.kotest.matchers.shouldNotBe import kotlinx.coroutines.runBlocking import org.json.JSONArray import org.json.JSONObject -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito.mock import org.mockito.kotlin.mock -class NotificationCommandFactoryTest { +class NotificationCommandFactoryTest : AnnotationSpec() { private companion object { const val SID = "129487fw123" const val MISSING_SID = "Missing sid" @@ -92,7 +91,7 @@ class NotificationCommandFactoryTest { private lateinit var mockCurrentActivityProvider: CurrentActivityProvider private lateinit var mockActivity: Activity - @BeforeEach + @Before fun setUp() { context = InstrumentationRegistry.getTargetContext().applicationContext mockConcurrentHandlerHolder = mock() @@ -126,7 +125,7 @@ class NotificationCommandFactoryTest { factory = NotificationCommandFactory(context) } - @AfterEach + @After fun tearDown() { tearDownMobileEngageComponent() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/AppEventCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/AppEventCommandTest.kt index 96267f47..4ceda517 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/AppEventCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/AppEventCommandTest.kt @@ -4,24 +4,23 @@ import android.content.Context import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder import com.emarsys.mobileengage.event.CacheableEventHandler +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.mockito.ThreadSpy +import io.kotest.assertions.fail import org.json.JSONException import org.json.JSONObject -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.fail import org.mockito.kotlin.* import java.util.concurrent.CountDownLatch -class AppEventCommandTest { +class AppEventCommandTest : AnnotationSpec() { private lateinit var applicationContext: Context private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder private lateinit var mockEventHandler: CacheableEventHandler - @BeforeEach + @Before fun setUp() { applicationContext = getTargetContext().applicationContext mockEventHandler = mock() @@ -90,7 +89,7 @@ class AppEventCommandTest { null ).run() } catch (e: Exception) { - fail(e.message) + fail(e.message!!) } } } \ No newline at end of file diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CompositeCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CompositeCommandTest.kt index 65719ae9..4f7b752f 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CompositeCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CompositeCommandTest.kt @@ -1,13 +1,13 @@ package com.emarsys.mobileengage.notification.command -import org.junit.jupiter.api.Test +import com.emarsys.testUtil.AnnotationSpec import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.verify -class CompositeCommandTest { +class CompositeCommandTest : AnnotationSpec() { @Test diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CustomEventCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CustomEventCommandTest.kt index 57880973..e07e1c5c 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CustomEventCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/CustomEventCommandTest.kt @@ -1,15 +1,14 @@ package com.emarsys.mobileengage.notification.command import com.emarsys.mobileengage.event.EventServiceInternal +import com.emarsys.testUtil.AnnotationSpec import io.kotest.assertions.throwables.shouldThrow -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito -class CustomEventCommandTest { +class CustomEventCommandTest : AnnotationSpec() { private lateinit var mockEventServiceInternal: EventServiceInternal - @BeforeEach + @Before fun setUp() { mockEventServiceInternal = Mockito.mock(EventServiceInternal::class.java) } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/DismissNotificationCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/DismissNotificationCommandTest.kt index 390a815d..6cf51b52 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/DismissNotificationCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/DismissNotificationCommandTest.kt @@ -6,14 +6,14 @@ import android.content.Intent import com.emarsys.mobileengage.service.NotificationData import com.emarsys.mobileengage.service.NotificationOperation -import org.junit.jupiter.api.Test +import com.emarsys.testUtil.AnnotationSpec import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions -class DismissNotificationCommandTest { +class DismissNotificationCommandTest : AnnotationSpec() { private companion object { const val TITLE = "title" const val BODY = "body" diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/LaunchApplicationCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/LaunchApplicationCommandTest.kt index 74bad010..ab7fe3fb 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/LaunchApplicationCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/LaunchApplicationCommandTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.notification.command + import android.app.Activity import android.app.Application import android.content.Intent @@ -9,13 +10,11 @@ import androidx.lifecycle.Lifecycle import androidx.test.core.app.ActivityScenario import com.emarsys.mobileengage.fake.FakeActivityLifecycleCallbacks import com.emarsys.mobileengage.notification.LaunchActivityCommandLifecycleCallbacksFactory +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.fake.FakeActivity import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.ArgumentCaptor import org.mockito.ArgumentMatchers import org.mockito.Mockito @@ -25,13 +24,13 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch -class LaunchApplicationCommandTest { +class LaunchApplicationCommandTest : AnnotationSpec() { private lateinit var scenario: ActivityScenario private lateinit var mockProviderLaunchActivityCommand: LaunchActivityCommandLifecycleCallbacksFactory - @BeforeEach + @Before fun setUp() { scenario = ActivityScenario.launch(FakeActivity::class.java) scenario.onActivity { activity -> @@ -40,7 +39,7 @@ class LaunchApplicationCommandTest { } } - @AfterEach + @After fun tearDown() { scenario.close() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/NotificationInformationCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/NotificationInformationCommandTest.kt index e02cca2a..e3c86681 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/NotificationInformationCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/NotificationInformationCommandTest.kt @@ -3,23 +3,29 @@ package com.emarsys.mobileengage.notification.command import com.emarsys.mobileengage.api.push.NotificationInformation import com.emarsys.mobileengage.api.push.NotificationInformationListener import com.emarsys.mobileengage.push.NotificationInformationListenerProvider -import org.junit.jupiter.api.Test +import com.emarsys.testUtil.AnnotationSpec import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify -class NotificationInformationCommandTest { +class NotificationInformationCommandTest : AnnotationSpec() { @Test fun testRun() { val mockNotificationInformationListener: NotificationInformationListener = mock() - val mockNotificationInformationListenerProvider: NotificationInformationListenerProvider = mock { - on { notificationInformationListener } doReturn mockNotificationInformationListener - } + val mockNotificationInformationListenerProvider: NotificationInformationListenerProvider = + mock { + on { notificationInformationListener } doReturn mockNotificationInformationListener + } val notificationInformation = NotificationInformation("campaignId") - val notificationInformationCommand = NotificationInformationCommand(mockNotificationInformationListenerProvider, notificationInformation) + val notificationInformationCommand = NotificationInformationCommand( + mockNotificationInformationListenerProvider, + notificationInformation + ) notificationInformationCommand.run() verify(mockNotificationInformationListenerProvider).notificationInformationListener - verify(mockNotificationInformationListener).onNotificationInformationReceived(notificationInformation) + verify(mockNotificationInformationListener).onNotificationInformationReceived( + notificationInformation + ) } } \ No newline at end of file diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/OpenExternalUrlCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/OpenExternalUrlCommandTest.kt index cd72640b..19be2f6c 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/OpenExternalUrlCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/OpenExternalUrlCommandTest.kt @@ -3,13 +3,13 @@ package com.emarsys.mobileengage.notification.command import android.content.Context import android.content.Intent -import org.junit.jupiter.api.Test +import com.emarsys.testUtil.AnnotationSpec import org.mockito.Mockito import org.mockito.kotlin.mock import org.mockito.kotlin.verify -class OpenExternalUrlCommandTest { +class OpenExternalUrlCommandTest : AnnotationSpec() { companion object { init { Mockito.mock(Context::class.java) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/PreloadedInappHandlerCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/PreloadedInappHandlerCommandTest.kt index 5a7561d6..f00b3087 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/PreloadedInappHandlerCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/PreloadedInappHandlerCommandTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.notification.command + import com.emarsys.core.activity.ActivityLifecycleActionRegistry import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder @@ -10,13 +11,11 @@ import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.service.NotificationData import com.emarsys.mobileengage.service.NotificationOperation +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.FileTestUtils import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.matchers.shouldBe import org.json.JSONObject -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -26,7 +25,7 @@ import java.io.File import java.util.concurrent.CountDownLatch -class PreloadedInappHandlerCommandTest { +class PreloadedInappHandlerCommandTest : AnnotationSpec() { companion object { private const val URL = "https://www.google.com" const val TITLE = "title" @@ -61,7 +60,7 @@ class PreloadedInappHandlerCommandTest { private lateinit var fileUrl: String - @BeforeEach + @Before fun setUp() { fileUrl = InstrumentationRegistry.getTargetContext().applicationContext.cacheDir.absolutePath + "/test.file" @@ -83,7 +82,7 @@ class PreloadedInappHandlerCommandTest { } - @AfterEach + @After fun tearDown() { concurrentHandlerHolder.coreLooper.quitSafely() tearDownMobileEngageComponent() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/SilentNotificationInformationCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/SilentNotificationInformationCommandTest.kt index ddc0c5db..074bcbed 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/SilentNotificationInformationCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/SilentNotificationInformationCommandTest.kt @@ -4,28 +4,34 @@ import com.emarsys.mobileengage.api.push.NotificationInformation import com.emarsys.mobileengage.api.push.NotificationInformationListener import com.emarsys.mobileengage.push.SilentNotificationInformationListenerProvider -import org.junit.jupiter.api.Test +import com.emarsys.testUtil.AnnotationSpec import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify -class SilentNotificationInformationCommandTest { +class SilentNotificationInformationCommandTest : AnnotationSpec() { @Test fun testRun() { val mockNotificationInformationListener: NotificationInformationListener = mock() - val mockSilentNotificationInformationListenerProvider: SilentNotificationInformationListenerProvider = mock { - on { silentNotificationInformationListener } doReturn mockNotificationInformationListener - } + val mockSilentNotificationInformationListenerProvider: SilentNotificationInformationListenerProvider = + mock { + on { silentNotificationInformationListener } doReturn mockNotificationInformationListener + } val testNotificationInformation = NotificationInformation("testCampaignId") - val silentNotificationInformationCommand = SilentNotificationInformationCommand(mockSilentNotificationInformationListenerProvider, testNotificationInformation) + val silentNotificationInformationCommand = SilentNotificationInformationCommand( + mockSilentNotificationInformationListenerProvider, + testNotificationInformation + ) silentNotificationInformationCommand.run() verify(mockSilentNotificationInformationListenerProvider).silentNotificationInformationListener - verify(mockNotificationInformationListener).onNotificationInformationReceived(testNotificationInformation) + verify(mockNotificationInformationListener).onNotificationInformationReceived( + testNotificationInformation + ) } } \ No newline at end of file diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackActionClickCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackActionClickCommandTest.kt index 0ebadec7..34cc7192 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackActionClickCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackActionClickCommandTest.kt @@ -1,11 +1,11 @@ package com.emarsys.mobileengage.notification.command import com.emarsys.mobileengage.event.EventServiceInternal +import com.emarsys.testUtil.AnnotationSpec import io.kotest.assertions.throwables.shouldThrow -import org.junit.jupiter.api.Test import org.mockito.Mockito -class TrackActionClickCommandTest { +class TrackActionClickCommandTest : AnnotationSpec() { @Test fun testConstructor_eventServiceInternal_mustNotBeNull() { shouldThrow { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackMessageOpenCommandTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackMessageOpenCommandTest.kt index 1af30f9d..bffe477d 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackMessageOpenCommandTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/notification/command/TrackMessageOpenCommandTest.kt @@ -2,12 +2,12 @@ package com.emarsys.mobileengage.notification.command import com.emarsys.mobileengage.push.PushInternal -import org.junit.jupiter.api.Test +import com.emarsys.testUtil.AnnotationSpec import org.mockito.Mockito.mock import org.mockito.Mockito.verify -class TrackMessageOpenCommandTest { +class TrackMessageOpenCommandTest : AnnotationSpec() { @Test diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushInternalTest.kt index d9b8367f..439294b0 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushInternalTest.kt @@ -15,12 +15,11 @@ import com.emarsys.mobileengage.event.CacheableEventHandler import com.emarsys.mobileengage.event.EventServiceInternal import com.emarsys.mobileengage.fake.FakeCompletionListener import com.emarsys.mobileengage.request.MobileEngageRequestModelFactory +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.ThreadSpy import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeTypeOf -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argumentCaptor @@ -33,7 +32,7 @@ import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.verifyNoMoreInteractions import java.util.concurrent.CountDownLatch -class DefaultPushInternalTest { +class DefaultPushInternalTest : AnnotationSpec() { private companion object { const val TIMESTAMP = 123456789L @@ -69,7 +68,7 @@ class DefaultPushInternalTest { private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun setUp() { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushTokenProviderTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushTokenProviderTest.kt index 5e54b2dc..d4ef0520 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushTokenProviderTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/push/DefaultPushTokenProviderTest.kt @@ -2,14 +2,12 @@ package com.emarsys.mobileengage.push import com.emarsys.core.storage.Storage import com.emarsys.core.storage.StringStorage +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe - -import org.junit.jupiter.api.Test - import org.mockito.Mockito.mock -class DefaultPushTokenProviderTest { +class DefaultPushTokenProviderTest : AnnotationSpec() { private companion object { const val PUSH_TOKEN = "pushToken" } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyProviderTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyProviderTest.kt index 8d53bf0c..a1999a76 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyProviderTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyProviderTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.request + import com.emarsys.core.CoreCompletionHandler import com.emarsys.core.endpoint.ServiceEndpointProvider import com.emarsys.core.request.RestClient @@ -9,16 +10,13 @@ import com.emarsys.core.worker.CoreCompletionHandlerMiddleware import com.emarsys.core.worker.Worker import com.emarsys.mobileengage.responsehandler.MobileEngageTokenResponseHandler import com.emarsys.mobileengage.util.RequestModelHelper +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito.mock import org.mockito.kotlin.mock -class CoreCompletionHandlerRefreshTokenProxyProviderTest { +class CoreCompletionHandlerRefreshTokenProxyProviderTest : AnnotationSpec() { private lateinit var mockCoreCompletionHandlerMiddlewareProvider: CoreCompletionHandlerMiddlewareProvider private lateinit var mockCoreCompletionHandlerMiddleware: CoreCompletionHandlerMiddleware private lateinit var mockRestClient: RestClient @@ -36,7 +34,7 @@ class CoreCompletionHandlerRefreshTokenProxyProviderTest { private lateinit var mockRequestModelFactory: MobileEngageRequestModelFactory - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun setUp() { mockCoreCompletionHandlerMiddlewareProvider = mock() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyTest.kt index e9415173..b379c905 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/CoreCompletionHandlerRefreshTokenProxyTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.request + import com.emarsys.core.CoreCompletionHandler import com.emarsys.core.request.RestClient import com.emarsys.core.request.model.RequestMethod @@ -8,11 +9,8 @@ import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.Storage import com.emarsys.mobileengage.responsehandler.MobileEngageTokenResponseHandler import com.emarsys.mobileengage.util.RequestModelHelper +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.eq @@ -21,8 +19,7 @@ import org.mockito.kotlin.times import org.mockito.kotlin.verify import java.net.URL -class CoreCompletionHandlerRefreshTokenProxyTest { - +class CoreCompletionHandlerRefreshTokenProxyTest : AnnotationSpec() { companion object { @@ -41,7 +38,7 @@ class CoreCompletionHandlerRefreshTokenProxyTest { private lateinit var mockRequestModelHelper: RequestModelHelper private lateinit var mockRequestModelFactory: MobileEngageRequestModelFactory - @BeforeEach + @Before fun setUp() { mockRequestModel = mock { on { url } doReturn URL(CLIENT_HOST) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/MobileEngageRequestModelFactoryTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/MobileEngageRequestModelFactoryTest.kt index 34013684..9179e6eb 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/MobileEngageRequestModelFactoryTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/MobileEngageRequestModelFactoryTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.request + import com.emarsys.common.feature.InnerFeature import com.emarsys.core.api.notification.NotificationSettings import com.emarsys.core.device.DeviceInfo @@ -14,17 +15,14 @@ import com.emarsys.mobileengage.MobileEngageRequestContext import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClickedRepository import com.emarsys.mobileengage.util.RequestPayloadUtils +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.whenever -class MobileEngageRequestModelFactoryTest { +class MobileEngageRequestModelFactoryTest : AnnotationSpec() { private companion object { const val TIMESTAMP = 123456789L @@ -59,7 +57,7 @@ class MobileEngageRequestModelFactoryTest { lateinit var mockButtonClickedRepository: ButtonClickedRepository - @BeforeEach + @Before fun setUp() { mockEventServiceProvider = mock { on { provideEndpointHost() } doReturn EVENT_HOST diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/ContactTokenHeaderMapperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/ContactTokenHeaderMapperTest.kt index b4628f68..55751088 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/ContactTokenHeaderMapperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/ContactTokenHeaderMapperTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.request.mapper + import com.emarsys.core.device.DeviceInfo import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider @@ -10,18 +11,15 @@ import com.emarsys.core.storage.StringStorage import com.emarsys.mobileengage.MobileEngageRequestContext import com.emarsys.mobileengage.util.RequestModelHelper import com.emarsys.mobileengage.util.RequestPayloadUtils +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock -class ContactTokenHeaderMapperTest { +class ContactTokenHeaderMapperTest : AnnotationSpec() { private companion object { const val CONTACT_TOKEN = "contactToken" const val REFRESH_TOKEN = "refreshToken" @@ -41,7 +39,7 @@ class ContactTokenHeaderMapperTest { private lateinit var mockRequestModelHelper: RequestModelHelper - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun setUp() { mockContactTokenStorage = mock { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DefaultRequestHeaderMapperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DefaultRequestHeaderMapperTest.kt index 7c7a359b..ad737ebe 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DefaultRequestHeaderMapperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DefaultRequestHeaderMapperTest.kt @@ -1,20 +1,18 @@ package com.emarsys.mobileengage.request.mapper + import com.emarsys.core.device.DeviceInfo import com.emarsys.core.request.model.RequestMethod import com.emarsys.core.request.model.RequestModel import com.emarsys.mobileengage.MobileEngageRequestContext +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.whenever -class DefaultRequestHeaderMapperTest { +class DefaultRequestHeaderMapperTest : AnnotationSpec() { private companion object { const val TIMESTAMP = 234123L @@ -29,7 +27,7 @@ class DefaultRequestHeaderMapperTest { private lateinit var mockDeviceInfo: DeviceInfo - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun setUp() { mockDeviceInfo = mock { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DeviceEventStateRequestMapperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DeviceEventStateRequestMapperTest.kt index 799470ca..a58fcf4b 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DeviceEventStateRequestMapperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/DeviceEventStateRequestMapperTest.kt @@ -8,16 +8,15 @@ import com.emarsys.core.request.model.RequestModel import com.emarsys.core.storage.Storage import com.emarsys.mobileengage.MobileEngageRequestContext import com.emarsys.mobileengage.util.RequestModelHelper +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe import org.json.JSONObject -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.whenever -class DeviceEventStateRequestMapperTest { +class DeviceEventStateRequestMapperTest : AnnotationSpec() { companion object { const val DEVICE_EVENT_STATE: String = """{"device-event-state":true}""" val DEVICE_EVENT_STATE_JSON: JSONObject = JSONObject("""{"device-event-state":true}""") @@ -32,7 +31,7 @@ class DeviceEventStateRequestMapperTest { private lateinit var mockDeviceEventStateStorage: Storage private lateinit var mockRequestModelHelper: RequestModelHelper - @BeforeEach + @Before fun setUp() { FeatureRegistry.enableFeature(InnerFeature.EVENT_SERVICE_V4) val mockDeviceInfo: DeviceInfo = mock { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/MobileEngageHeaderMapperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/MobileEngageHeaderMapperTest.kt index 5639db0e..931c52e1 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/MobileEngageHeaderMapperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/MobileEngageHeaderMapperTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.request.mapper + import com.emarsys.core.device.DeviceInfo import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider @@ -9,19 +10,16 @@ import com.emarsys.core.request.model.RequestModel import com.emarsys.core.storage.StringStorage import com.emarsys.mobileengage.MobileEngageRequestContext import com.emarsys.mobileengage.util.RequestModelHelper +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock class -MobileEngageHeaderMapperTest { +MobileEngageHeaderMapperTest : AnnotationSpec() { private companion object { const val CLIENT_STATE = "client-state" const val TIMESTAMP = 123456789L @@ -39,7 +37,7 @@ MobileEngageHeaderMapperTest { private lateinit var mockRequestModelHelper: RequestModelHelper - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun setUp() { mockClientStateStorage = mock { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/OpenIdTokenRequestMapperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/OpenIdTokenRequestMapperTest.kt index 65b368e6..1049cd84 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/OpenIdTokenRequestMapperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/request/mapper/OpenIdTokenRequestMapperTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.request.mapper + import com.emarsys.core.device.DeviceInfo import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider @@ -8,17 +9,14 @@ import com.emarsys.core.request.model.RequestMethod import com.emarsys.core.request.model.RequestModel import com.emarsys.mobileengage.MobileEngageRequestContext import com.emarsys.mobileengage.util.RequestModelHelper +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock -class OpenIdTokenRequestMapperTest { +class OpenIdTokenRequestMapperTest : AnnotationSpec() { private companion object { const val OPEN_ID_TOKEN = "openIdToken" const val TIMESTAMP = 123456789L @@ -35,7 +33,7 @@ class OpenIdTokenRequestMapperTest { private lateinit var mockRequestModelHelper: RequestModelHelper - @BeforeEach + @Before fun setUp() { mockDeviceInfo = mock { on { hardwareId } doReturn HARDWARE_ID diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/ClientInfoResponseHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/ClientInfoResponseHandlerTest.kt index 355bb19d..422b2d15 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/ClientInfoResponseHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/ClientInfoResponseHandlerTest.kt @@ -1,35 +1,32 @@ package com.emarsys.mobileengage.responsehandler + import com.emarsys.core.device.DeviceInfo import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.StringStorage +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito.mock import org.mockito.Mockito.verify import java.net.URL -class ClientInfoResponseHandlerTest { +class ClientInfoResponseHandlerTest : AnnotationSpec() { companion object { val URL: URL = URL("https://me-client.eservice.emarsys.net/v3/apps/12341/client") } - private lateinit var clientInfoResponseHandler: ClientInfoResponseHandler private lateinit var mockDeviceInfo: DeviceInfo - private lateinit var mockDeviceInfoPayloadStorage:StringStorage + private lateinit var mockDeviceInfoPayloadStorage: StringStorage private lateinit var mockResponseModel: ResponseModel private lateinit var mockRequestModel: RequestModel - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun setUp() { mockDeviceInfo = mock(DeviceInfo::class.java) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/DeviceEventStateResponseHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/DeviceEventStateResponseHandlerTest.kt index 43f9fe87..4f6fd4e9 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/DeviceEventStateResponseHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/DeviceEventStateResponseHandlerTest.kt @@ -6,9 +6,8 @@ import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.StringStorage import com.emarsys.mobileengage.util.RequestModelHelper +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -16,7 +15,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import java.net.URL -class DeviceEventStateResponseHandlerTest { +class DeviceEventStateResponseHandlerTest : AnnotationSpec() { companion object { private const val EVENT_HOST = "https://mobile-events.eservice.emarsys.net" private const val EVENT_BASE = "$EVENT_HOST/v4/apps/%s/events" @@ -28,7 +27,7 @@ class DeviceEventStateResponseHandlerTest { private lateinit var handler: DeviceEventStateResponseHandler private lateinit var mockRequestModelHelper: RequestModelHelper - @BeforeEach + @Before fun setup() { mockRequestModel = mock { on { url } doReturn URL(EVENT_BASE) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerTest.kt index 91f72c7a..f3449c63 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.responsehandler + import com.emarsys.common.feature.InnerFeature import com.emarsys.core.database.repository.Repository import com.emarsys.core.database.repository.SqlSpecification @@ -10,20 +11,17 @@ import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIam import com.emarsys.mobileengage.iam.model.specification.FilterByCampaignId import com.emarsys.mobileengage.util.RequestModelHelper +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify import java.net.URL -class InAppCleanUpResponseHandlerTest { +class InAppCleanUpResponseHandlerTest : AnnotationSpec() { companion object { private const val EVENT_HOST = "https://mobile-events.eservice.emarsys.net" private const val EVENT_BASE = "$EVENT_HOST/v3/apps/%s/client/events" @@ -36,7 +34,7 @@ class InAppCleanUpResponseHandlerTest { private lateinit var mockRequestModelHelper: RequestModelHelper - @BeforeEach + @Before fun setUp() { mockRequestModel = mock { on { url } doReturn URL(EVENT_BASE) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerV4Test.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerV4Test.kt index d15883bc..100e6f1f 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerV4Test.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppCleanUpResponseHandlerV4Test.kt @@ -10,12 +10,11 @@ import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIam import com.emarsys.mobileengage.iam.model.specification.FilterByCampaignId import com.emarsys.mobileengage.util.RequestModelHelper +import com.emarsys.testUtil.AnnotationSpec import io.kotest.data.forAll import io.kotest.data.row import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock @@ -24,7 +23,7 @@ import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever import java.net.URL -class InAppCleanUpResponseHandlerV4Test { +class InAppCleanUpResponseHandlerV4Test : AnnotationSpec() { companion object { private const val EVENT_HOST = "https://mobile-events.eservice.emarsys.net" private const val EVENT_BASE = "$EVENT_HOST/v4/apps/%s/events" @@ -37,7 +36,7 @@ class InAppCleanUpResponseHandlerV4Test { private lateinit var mockRequestModelHelper: RequestModelHelper - @BeforeEach + @Before fun setUp() { mockRequestModel = mock { on { url } doReturn URL(EVENT_BASE) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppMessageResponseHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppMessageResponseHandlerTest.kt index 1b83cf03..a7148c56 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppMessageResponseHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/InAppMessageResponseHandlerTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.responsehandler + import android.content.ClipboardManager import androidx.test.core.app.ActivityScenario import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory @@ -14,11 +15,9 @@ import com.emarsys.mobileengage.iam.dialog.IamDialog import com.emarsys.mobileengage.iam.dialog.IamDialogProvider import com.emarsys.mobileengage.iam.jsbridge.IamJsBridge import com.emarsys.mobileengage.iam.jsbridge.IamJsBridgeFactory +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.fake.FakeActivity import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doReturn @@ -26,7 +25,7 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.spy import org.mockito.kotlin.verify -class InAppMessageResponseHandlerTest { +class InAppMessageResponseHandlerTest : AnnotationSpec() { private lateinit var handler: InAppMessageResponseHandler private lateinit var presenter: OverlayInAppPresenter @@ -38,7 +37,7 @@ class InAppMessageResponseHandlerTest { private lateinit var mockCurrentActivityProvider: CurrentActivityProvider private lateinit var scenario: ActivityScenario - @BeforeEach + @Before fun init() { scenario = ActivityScenario.launch(FakeActivity::class.java) scenario.onActivity { activity -> @@ -75,7 +74,7 @@ class InAppMessageResponseHandlerTest { } } - @AfterEach + @After fun tearDown() { scenario.close() } diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageClientStateResponseHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageClientStateResponseHandlerTest.kt index 4fffeade..20b392a2 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageClientStateResponseHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageClientStateResponseHandlerTest.kt @@ -1,25 +1,24 @@ package com.emarsys.mobileengage.responsehandler + import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.StringStorage import com.emarsys.mobileengage.endpoint.Endpoint import com.emarsys.mobileengage.util.RequestModelHelper +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify import java.net.URL -class MobileEngageClientStateResponseHandlerTest { +class MobileEngageClientStateResponseHandlerTest : AnnotationSpec() { private companion object { - const val X_CLIENT_STATE_VALUE = "TG9yZW0gSXBzdW0gaXMgc2ltcGx5IGR1bW15IHRleHQgb2YgdGhlIHByaW50aW5nIGFuZCB0" + const val X_CLIENT_STATE_VALUE = + "TG9yZW0gSXBzdW0gaXMgc2ltcGx5IGR1bW15IHRleHQgb2YgdGhlIHByaW50aW5nIGFuZCB0" const val APPLICATION_CODE = "applicationCode" const val CLIENT_HOST = "https://mobile-events.eservice.emarsys.net/v3" } @@ -30,7 +29,7 @@ class MobileEngageClientStateResponseHandlerTest { private lateinit var mockRequestModelHelper: RequestModelHelper - @BeforeEach + @Before fun setUp() { mockStorage = mock() requestModelMock = mock { diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageTokenResponseHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageTokenResponseHandlerTest.kt index d994abd3..6a1c47e2 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageTokenResponseHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/MobileEngageTokenResponseHandlerTest.kt @@ -1,22 +1,20 @@ package com.emarsys.mobileengage.responsehandler + import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.StringStorage import com.emarsys.mobileengage.util.RequestModelHelper +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify import java.net.URL -class MobileEngageTokenResponseHandlerTest { +class MobileEngageTokenResponseHandlerTest : AnnotationSpec() { private companion object { const val CLIENT_HOST = "https://mobile-events.eservice.emarsys.net" const val CLIENT_BASE = "$CLIENT_HOST/v3/apps/%s/client" @@ -30,7 +28,7 @@ class MobileEngageTokenResponseHandlerTest { private lateinit var mockRequestModelHelper: RequestModelHelper - @BeforeEach + @Before fun setUp() { token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ4IjoieSJ9.bKXKVZCwf8J55WzWagrg2S0o2k_xZQ-HYfHIIj_2Z_U" diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/OnEventActionResponseHandlerTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/OnEventActionResponseHandlerTest.kt index d983f9e0..83f56563 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/OnEventActionResponseHandlerTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/responsehandler/OnEventActionResponseHandlerTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.responsehandler + import android.os.Looper import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.database.repository.Repository @@ -13,14 +14,12 @@ import com.emarsys.mobileengage.event.EventServiceInternal import com.emarsys.mobileengage.iam.model.displayediam.DisplayedIam import com.emarsys.mobileengage.notification.ActionCommandFactory import com.emarsys.mobileengage.notification.command.AppEventCommand +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.anyNotNull import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking import org.json.JSONObject -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.doReturn @@ -29,7 +28,7 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.timeout import org.mockito.kotlin.verify -class OnEventActionResponseHandlerTest { +class OnEventActionResponseHandlerTest : AnnotationSpec() { private lateinit var responseHandler: OnEventActionResponseHandler private lateinit var mockActionCommandFactory: ActionCommandFactory @@ -40,7 +39,7 @@ class OnEventActionResponseHandlerTest { private lateinit var concurrentHandlerHolder: ConcurrentHandlerHolder - @BeforeEach + @Before fun setUp() { mockAppEventCommand = mock() mockActionCommandFactory = mock() @@ -59,7 +58,7 @@ class OnEventActionResponseHandlerTest { ) } - @AfterEach + @After fun tearDown() { try { val looper: Looper? = concurrentHandlerHolder.coreLooper diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/IntentUtilsTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/IntentUtilsTest.kt index 6a277b9c..9f1abdc4 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/IntentUtilsTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/IntentUtilsTest.kt @@ -9,15 +9,14 @@ import com.emarsys.mobileengage.di.setupMobileEngageComponent import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.service.IntentUtils.createLaunchIntent import com.emarsys.mobileengage.service.IntentUtils.createNotificationHandlerServiceIntent +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock -class IntentUtilsTest { +class IntentUtilsTest : AnnotationSpec() { private companion object { const val TITLE = "title" const val BODY = "body" @@ -47,7 +46,7 @@ class IntentUtilsTest { private lateinit var context: Context - @BeforeEach + @Before fun init() { setupMobileEngageComponent(FakeMobileEngageDependencyContainer()) context = getTargetContext() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/MessagingServiceUtilsTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/MessagingServiceUtilsTest.kt index 70d49a49..a70fbcd1 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/MessagingServiceUtilsTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/MessagingServiceUtilsTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.service + import android.R import android.app.Notification import android.content.Context @@ -27,17 +28,13 @@ import com.emarsys.mobileengage.push.SilentNotificationInformationListenerProvid import com.emarsys.mobileengage.service.MessagingServiceUtils.styleNotification import com.emarsys.mobileengage.service.mapper.RemoteMessageMapperFactory import com.emarsys.mobileengage.service.mapper.RemoteMessageMapperV1 +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.copyInputStreamToFile import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import org.json.JSONArray import org.json.JSONObject -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.ArgumentMatchers import org.mockito.kotlin.any import org.mockito.kotlin.doReturn @@ -47,7 +44,7 @@ import org.mockito.kotlin.whenever import java.io.File import java.util.Locale -class MessagingServiceUtilsTest { +class MessagingServiceUtilsTest : AnnotationSpec() { private companion object { const val TITLE = "title" const val BODY = "body" @@ -93,7 +90,7 @@ class MessagingServiceUtilsTest { private lateinit var mockRemoteMessageMapperV1: RemoteMessageMapperV1 - @BeforeEach + @Before fun init() { context = getTargetContext() val mockNotificationSettings: NotificationSettings = mock() @@ -150,7 +147,7 @@ class MessagingServiceUtilsTest { ) } - @AfterEach + @After fun tearDown() { mobileEngage().concurrentHandlerHolder.coreLooper.quitSafely() tearDownMobileEngageComponent() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/NotificationActionUtilsTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/NotificationActionUtilsTest.kt index b25ad141..a2a346cf 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/NotificationActionUtilsTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/NotificationActionUtilsTest.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.service + import android.content.Context import android.content.Intent import androidx.core.app.NotificationCompat @@ -8,21 +9,18 @@ import com.emarsys.mobileengage.di.setupMobileEngageComponent import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.notification.NotificationCommandFactory +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry.Companion.getTargetContext import com.emarsys.testUtil.mockito.ThreadSpy import io.kotest.matchers.shouldBe import org.json.JSONArray import org.json.JSONException import org.json.JSONObject -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test - import org.mockito.Mockito import org.mockito.kotlin.whenever import java.util.concurrent.CountDownLatch -class NotificationActionUtilsTest { +class NotificationActionUtilsTest : AnnotationSpec() { private companion object { const val SMALL_RESOURCE_ID = 123 const val COLOR_RESOURCE_ID = 456 @@ -44,13 +42,13 @@ class NotificationActionUtilsTest { private lateinit var context: Context - @BeforeEach + @Before fun init() { context = getTargetContext().applicationContext setupMobileEngageComponent(FakeMobileEngageDependencyContainer()) } - @AfterEach + @After fun tearDown() { mobileEngage().concurrentHandlerHolder.coreLooper.quitSafely() tearDownMobileEngageComponent() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV1Test.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV1Test.kt index 5e8ab839..47f53668 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV1Test.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV1Test.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.service + import android.content.Context import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.resource.MetaDataReader @@ -9,17 +10,15 @@ import com.emarsys.mobileengage.di.setupMobileEngageComponent import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.service.mapper.RemoteMessageMapperV1 +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import org.json.JSONObject -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.whenever -class RemoteMessageMapperV1Test { +class RemoteMessageMapperV1Test : AnnotationSpec() { private companion object { const val TITLE = "title" const val BODY = "body" @@ -40,7 +39,7 @@ class RemoteMessageMapperV1Test { private lateinit var remoteMessageMapperV1: RemoteMessageMapperV1 - @BeforeEach + @Before fun setUp() { context = InstrumentationRegistry.getTargetContext() @@ -58,7 +57,7 @@ class RemoteMessageMapperV1Test { ) } - @AfterEach + @After fun tearDown() { mobileEngage().concurrentHandlerHolder.coreLooper.quitSafely() tearDownMobileEngageComponent() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV2Test.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV2Test.kt index 0aa61d33..c2080c6f 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV2Test.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/service/RemoteMessageMapperV2Test.kt @@ -1,5 +1,6 @@ package com.emarsys.mobileengage.service + import android.content.Context import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.resource.MetaDataReader @@ -9,19 +10,17 @@ import com.emarsys.mobileengage.di.setupMobileEngageComponent import com.emarsys.mobileengage.di.tearDownMobileEngageComponent import com.emarsys.mobileengage.fake.FakeMobileEngageDependencyContainer import com.emarsys.mobileengage.service.mapper.RemoteMessageMapperV2 +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.InstrumentationRegistry import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import org.json.JSONArray import org.json.JSONObject -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.whenever -class RemoteMessageMapperV2Test { +class RemoteMessageMapperV2Test : AnnotationSpec() { private companion object { const val TITLE = "title" const val BODY = "body" @@ -41,7 +40,7 @@ class RemoteMessageMapperV2Test { private lateinit var remoteMessageMapperV2: RemoteMessageMapperV2 - @BeforeEach + @Before fun init() { context = InstrumentationRegistry.getTargetContext() @@ -60,7 +59,7 @@ class RemoteMessageMapperV2Test { ) } - @AfterEach + @After fun tearDown() { mobileEngage().concurrentHandlerHolder.coreLooper.quitSafely() tearDownMobileEngageComponent() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/session/MobileEngageSessionTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/session/MobileEngageSessionTest.kt index 90205641..2f1c6c31 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/session/MobileEngageSessionTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/session/MobileEngageSessionTest.kt @@ -5,8 +5,8 @@ import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.storage.Storage import com.emarsys.mobileengage.MobileEngageRequestContext import com.emarsys.mobileengage.event.EventServiceInternal -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test + +import com.emarsys.testUtil.AnnotationSpec import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doReturn import org.mockito.kotlin.eq @@ -16,7 +16,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever -class MobileEngageSessionTest { +class MobileEngageSessionTest : AnnotationSpec() { private companion object { const val SESSION_ID = "testSessionId" @@ -30,7 +30,7 @@ class MobileEngageSessionTest { private lateinit var mockContactTokenStorage: Storage private lateinit var mockMobileEngageRequestContext: MobileEngageRequestContext - @BeforeEach + @Before fun setUp() { mockMobileEngageRequestContext = mock { on { applicationCode } doReturn "testApplicationCode" diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/storage/MobileEngageStorageKeyTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/storage/MobileEngageStorageKeyTest.kt index 0d96fd99..49dce7ce 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/storage/MobileEngageStorageKeyTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/storage/MobileEngageStorageKeyTest.kt @@ -1,13 +1,13 @@ package com.emarsys.mobileengage.storage +import com.emarsys.testUtil.AnnotationSpec import io.kotest.data.forAll import io.kotest.data.row import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.Test -class MobileEngageStorageKeyTest { +class MobileEngageStorageKeyTest : AnnotationSpec() { @Test diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestModelHelperTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestModelHelperTest.kt index 6cf1b32f..2406ad80 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestModelHelperTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestModelHelperTest.kt @@ -1,19 +1,17 @@ package com.emarsys.mobileengage.util + import com.emarsys.core.endpoint.ServiceEndpointProvider import com.emarsys.core.request.model.RequestModel +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito.mock import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import java.net.URL -class RequestModelHelperTest { +class RequestModelHelperTest : AnnotationSpec() { private companion object { const val CLIENT_HOST = "https://me-client.eservice.emarsys.net/v3" @@ -34,7 +32,7 @@ class RequestModelHelperTest { private lateinit var mockRequestModel: RequestModel private lateinit var requestModelHelper: RequestModelHelper - @BeforeEach + @Before fun setUp() { mockRequestModel = mock() diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestPayloadUtilsTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestPayloadUtilsTest.kt index 20f4dbce..aaa5d63c 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestPayloadUtilsTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/util/RequestPayloadUtilsTest.kt @@ -14,17 +14,14 @@ import com.emarsys.mobileengage.iam.model.IamConversionUtils import com.emarsys.mobileengage.iam.model.buttonclicked.ButtonClicked import com.emarsys.mobileengage.session.SessionIdHolder import com.emarsys.mobileengage.testUtil.RandomMETestUtils +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.RandomTestUtils import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.whenever -class RequestPayloadUtilsTest { +class RequestPayloadUtilsTest : AnnotationSpec() { private companion object { const val PUSH_TOKEN = "pushToken" const val APPLICATION_CODE = "applicationCode" @@ -58,7 +55,7 @@ class RequestPayloadUtilsTest { private lateinit var mockSessionIdHolder: SessionIdHolder - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun setUp() { mockChannelSettings = listOf( diff --git a/predict-api/build.gradle.kts b/predict-api/build.gradle.kts index 20a8c2a6..d8b5ebe3 100644 --- a/predict-api/build.gradle.kts +++ b/predict-api/build.gradle.kts @@ -20,15 +20,21 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArguments["runnerBuilder"] = - "de.mannodermaus.junit5.AndroidJUnit5Builder" } compileOptions { isCoreLibraryDesugaringEnabled = true } packaging { resources { - excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + excludes += arrayOf( + "README.txt", + "META-INF/LICENSE.md", + "META-INF/LICENSE-notice.md", + "**/attach_hotspot_windows.dll", + "META-INF/AL2.0", + "META-INF/LGPL2.1", + "META-INF/licenses/ASM" + ) } } } diff --git a/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationFilterTest.kt b/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationFilterTest.kt index a07940bf..58eb6d7f 100644 --- a/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationFilterTest.kt +++ b/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationFilterTest.kt @@ -2,12 +2,11 @@ package com.emarsys.predict.api.model import com.emarsys.predict.api.model.RecommendationFilter.Companion.exclude import com.emarsys.predict.api.model.RecommendationFilter.Companion.include +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import java.util.Arrays -class RecommendationFilterTest { +class RecommendationFilterTest : AnnotationSpec() { companion object { private const val FIELD = "field" @@ -21,7 +20,7 @@ class RecommendationFilterTest { lateinit var include: RecommendationFilter.Include - @BeforeEach + @Before fun setUp() { exclude = exclude(FIELD) include = include(FIELD) diff --git a/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationLogicTest.kt b/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationLogicTest.kt index 455aa816..8b84a140 100644 --- a/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationLogicTest.kt +++ b/predict-api/src/androidTest/java/com/emarsys/predict/api/model/RecommendationLogicTest.kt @@ -8,11 +8,11 @@ import com.emarsys.predict.api.model.RecommendationLogic.Companion.personal import com.emarsys.predict.api.model.RecommendationLogic.Companion.popular import com.emarsys.predict.api.model.RecommendationLogic.Companion.related import com.emarsys.predict.api.model.RecommendationLogic.Companion.search +import com.emarsys.testUtil.AnnotationSpec import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test -class RecommendationLogicTest { +class RecommendationLogicTest : AnnotationSpec() { @Test fun testConstructor_variants_mustBeEmptyList_withoutVariantsParam() { diff --git a/predict/build.gradle.kts b/predict/build.gradle.kts index 1145c55e..457ed8fa 100644 --- a/predict/build.gradle.kts +++ b/predict/build.gradle.kts @@ -23,15 +23,21 @@ android { multiDexEnabled = true testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArguments["runnerBuilder"] = - "de.mannodermaus.junit5.AndroidJUnit5Builder" } compileOptions { isCoreLibraryDesugaringEnabled = true } packaging { resources { - excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + excludes += arrayOf( + "README.txt", + "META-INF/LICENSE.md", + "META-INF/LICENSE-notice.md", + "**/attach_hotspot_windows.dll", + "META-INF/AL2.0", + "META-INF/LGPL2.1", + "META-INF/licenses/ASM" + ) } } } diff --git a/predict/src/androidTest/java/com/emarsys/predict/DefaultPredictInternalTest.kt b/predict/src/androidTest/java/com/emarsys/predict/DefaultPredictInternalTest.kt index c274bce2..b380b37f 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/DefaultPredictInternalTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/DefaultPredictInternalTest.kt @@ -30,14 +30,13 @@ import com.emarsys.predict.model.LastTrackedItemContainer import com.emarsys.predict.provider.PredictRequestModelBuilderProvider import com.emarsys.predict.request.PredictRequestContext import com.emarsys.predict.request.PredictRequestModelBuilder +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.ReflectionTestUtils import com.emarsys.testUtil.mockito.ThreadSpy import com.emarsys.testUtil.mockito.anyNotNull import com.emarsys.testUtil.mockito.whenever import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argumentCaptor @@ -49,7 +48,7 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.verify import java.util.concurrent.CountDownLatch -class DefaultPredictInternalTest { +class DefaultPredictInternalTest : AnnotationSpec() { companion object { const val TTL = Long.MAX_VALUE @@ -84,7 +83,7 @@ class DefaultPredictInternalTest { private lateinit var mockResultListener: ResultListener>> private lateinit var mockLastTrackedItemContainer: LastTrackedItemContainer - @BeforeEach + @Before @Suppress("UNCHECKED_CAST") fun init() { latch = CountDownLatch(1) diff --git a/predict/src/androidTest/java/com/emarsys/predict/PredictResponseMapperTest.kt b/predict/src/androidTest/java/com/emarsys/predict/PredictResponseMapperTest.kt index 2e0cec13..4d3b40fc 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/PredictResponseMapperTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/PredictResponseMapperTest.kt @@ -1,24 +1,22 @@ package com.emarsys.predict + import com.emarsys.core.response.ResponseModel import com.emarsys.predict.api.model.Product +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.collections.shouldContainAll import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito -class PredictResponseMapperTest { +class PredictResponseMapperTest : AnnotationSpec() { private lateinit var predictResponseMapper: PredictResponseMapper private lateinit var mockResponseModel: ResponseModel private lateinit var expectedResult: List - @BeforeEach + @Before fun setUp() { predictResponseMapper = PredictResponseMapper() mockResponseModel = Mockito.mock(ResponseModel::class.java) diff --git a/predict/src/androidTest/java/com/emarsys/predict/provider/PredictRequestModelBuilderProviderTest.kt b/predict/src/androidTest/java/com/emarsys/predict/provider/PredictRequestModelBuilderProviderTest.kt index 255a3e99..e7f5595d 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/provider/PredictRequestModelBuilderProviderTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/provider/PredictRequestModelBuilderProviderTest.kt @@ -1,27 +1,25 @@ package com.emarsys.predict.provider + import com.emarsys.core.endpoint.ServiceEndpointProvider import com.emarsys.predict.request.PredictHeaderFactory import com.emarsys.predict.request.PredictRequestContext import com.emarsys.predict.request.PredictRequestModelBuilder +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito.mock -class PredictRequestModelBuilderProviderTest { +class PredictRequestModelBuilderProviderTest : AnnotationSpec() { private lateinit var mockRequestContext: PredictRequestContext private lateinit var mockHeaderFactory: PredictHeaderFactory private lateinit var mockServiceProvider: ServiceEndpointProvider - @BeforeEach + @Before fun setUp() { mockRequestContext = mock(PredictRequestContext::class.java) mockHeaderFactory = mock(PredictHeaderFactory::class.java) diff --git a/predict/src/androidTest/java/com/emarsys/predict/request/PredictHeaderFactoryTest.kt b/predict/src/androidTest/java/com/emarsys/predict/request/PredictHeaderFactoryTest.kt index aeed55e1..ccec297b 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/request/PredictHeaderFactoryTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/request/PredictHeaderFactoryTest.kt @@ -1,17 +1,15 @@ package com.emarsys.predict.request + import com.emarsys.core.device.DeviceInfo import com.emarsys.core.storage.KeyValueStore +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito -class PredictHeaderFactoryTest { +class PredictHeaderFactoryTest : AnnotationSpec() { private companion object { const val OS_VERSION = "1.0.0" const val PLATFORM = "android" @@ -23,7 +21,7 @@ class PredictHeaderFactoryTest { private lateinit var mockKeyValueStore: KeyValueStore - @BeforeEach + @Before fun setUp() { mockKeyValueStore = Mockito.mock(KeyValueStore::class.java) diff --git a/predict/src/androidTest/java/com/emarsys/predict/request/PredictRequestModelBuilderTest.kt b/predict/src/androidTest/java/com/emarsys/predict/request/PredictRequestModelBuilderTest.kt index ee4a6379..fd19609f 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/request/PredictRequestModelBuilderTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/request/PredictRequestModelBuilderTest.kt @@ -14,6 +14,7 @@ import com.emarsys.predict.api.model.PredictCartItem import com.emarsys.predict.api.model.RecommendationFilter import com.emarsys.predict.api.model.RecommendationLogic import com.emarsys.predict.model.LastTrackedItemContainer +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.assertions.throwables.shouldThrow import io.kotest.data.forAll @@ -22,11 +23,9 @@ import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking import org.json.JSONArray import org.json.JSONObject -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito.mock -class PredictRequestModelBuilderTest { +class PredictRequestModelBuilderTest : AnnotationSpec() { private companion object { const val TIMESTAMP = 123456789L @@ -62,7 +61,7 @@ class PredictRequestModelBuilderTest { private lateinit var mockServiceProvider: ServiceEndpointProvider - @BeforeEach + @Before fun setUp() { mockKeyValueStore = mock(KeyValueStore::class.java).apply { whenever(getString(PREDICT_VISITOR_ID_KEY)).thenReturn("visitorId") diff --git a/predict/src/androidTest/java/com/emarsys/predict/response/VisitorIdResponseHandlerTest.kt b/predict/src/androidTest/java/com/emarsys/predict/response/VisitorIdResponseHandlerTest.kt index e95c2b7d..2df7dc6e 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/response/VisitorIdResponseHandlerTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/response/VisitorIdResponseHandlerTest.kt @@ -1,31 +1,27 @@ package com.emarsys.predict.response + import com.emarsys.core.endpoint.ServiceEndpointProvider import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.KeyValueStore +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe - -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito.mock import org.mockito.Mockito.verify -class VisitorIdResponseHandlerTest { - +class VisitorIdResponseHandlerTest : AnnotationSpec() { private lateinit var keyValueStore: KeyValueStore private lateinit var mockServiceEndpointProvider: ServiceEndpointProvider private lateinit var responseHandler: VisitorIdResponseHandler - @BeforeEach + @Before fun init() { keyValueStore = mock(KeyValueStore::class.java) mockServiceEndpointProvider = mock(ServiceEndpointProvider::class.java).apply { diff --git a/predict/src/androidTest/java/com/emarsys/predict/response/XPResponseHandlerTest.kt b/predict/src/androidTest/java/com/emarsys/predict/response/XPResponseHandlerTest.kt index 3e596ca5..0475370b 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/response/XPResponseHandlerTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/response/XPResponseHandlerTest.kt @@ -1,29 +1,26 @@ package com.emarsys.predict.response + import com.emarsys.core.endpoint.ServiceEndpointProvider import com.emarsys.core.provider.timestamp.TimestampProvider import com.emarsys.core.provider.uuid.UUIDProvider import com.emarsys.core.request.model.RequestModel import com.emarsys.core.response.ResponseModel import com.emarsys.core.storage.KeyValueStore +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.matchers.shouldBe - -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito import org.mockito.Mockito.mock -class XPResponseHandlerTest { +class XPResponseHandlerTest : AnnotationSpec() { private lateinit var keyValueStore: KeyValueStore private lateinit var responseHandler: XPResponseHandler private lateinit var mockPredictServiceProvider: ServiceEndpointProvider - @BeforeEach + @Before fun init() { mockPredictServiceProvider = mock(ServiceEndpointProvider::class.java).apply { whenever(provideEndpointHost()).thenReturn("https://recommender.scarabresearch.com") diff --git a/predict/src/androidTest/java/com/emarsys/predict/shard/PredictShardListMergerTest.kt b/predict/src/androidTest/java/com/emarsys/predict/shard/PredictShardListMergerTest.kt index 9eef87af..7a866135 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/shard/PredictShardListMergerTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/shard/PredictShardListMergerTest.kt @@ -9,17 +9,16 @@ import com.emarsys.core.storage.KeyValueStore import com.emarsys.predict.provider.PredictRequestModelBuilderProvider import com.emarsys.predict.request.PredictRequestContext import com.emarsys.predict.request.PredictRequestModelBuilder +import com.emarsys.testUtil.AnnotationSpec import com.emarsys.testUtil.mockito.whenever import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.mockito.Mockito.any import org.mockito.Mockito.anyMap import org.mockito.Mockito.mock import org.mockito.Mockito.verify -class PredictShardListMergerTest { +class PredictShardListMergerTest : AnnotationSpec() { private companion object { const val ID = "id" @@ -47,7 +46,7 @@ class PredictShardListMergerTest { private lateinit var shard3: ShardModel - @BeforeEach + @Before fun init() { mockStore = mock(KeyValueStore::class.java) mockTimestampProvider = mock(TimestampProvider::class.java) diff --git a/predict/src/androidTest/java/com/emarsys/predict/storage/PredictStorageKeyTest.kt b/predict/src/androidTest/java/com/emarsys/predict/storage/PredictStorageKeyTest.kt index 863ca74a..f1ec63eb 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/storage/PredictStorageKeyTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/storage/PredictStorageKeyTest.kt @@ -1,13 +1,13 @@ package com.emarsys.predict.storage +import com.emarsys.testUtil.AnnotationSpec import io.kotest.data.forAll import io.kotest.data.row import io.kotest.matchers.shouldBe import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.Test -class PredictStorageKeyTest { +class PredictStorageKeyTest : AnnotationSpec() { @Test diff --git a/predict/src/androidTest/java/com/emarsys/predict/util/CartItemUtilsTest.kt b/predict/src/androidTest/java/com/emarsys/predict/util/CartItemUtilsTest.kt index c653478b..d51d517d 100644 --- a/predict/src/androidTest/java/com/emarsys/predict/util/CartItemUtilsTest.kt +++ b/predict/src/androidTest/java/com/emarsys/predict/util/CartItemUtilsTest.kt @@ -1,24 +1,21 @@ package com.emarsys.predict.util + import com.emarsys.predict.api.model.CartItem import com.emarsys.predict.api.model.PredictCartItem +import com.emarsys.testUtil.AnnotationSpec import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe - -import org.junit.jupiter.api.BeforeEach - -import org.junit.jupiter.api.Test - import org.mockito.Mockito.mock -class CartItemUtilsTest { +class CartItemUtilsTest : AnnotationSpec() { private lateinit var cartItem1: CartItem private lateinit var cartItem2: CartItem private lateinit var cartItem3: CartItem - @BeforeEach + @Before fun init() { cartItem1 = PredictCartItem("1", 100.0, 2.0) cartItem2 = PredictCartItem("2", 200.0, 4.0) diff --git a/sample/build.gradle.kts b/sample/build.gradle.kts index 77d47c5b..586dc39f 100644 --- a/sample/build.gradle.kts +++ b/sample/build.gradle.kts @@ -31,7 +31,12 @@ android { buildConfigField( "String", "GOOGLE_OAUTH_SERVER_CLIENT_ID", - "\"${env.fetch("GOOGLE_OAUTH_SERVER_CLIENT_ID", System.getenv("GOOGLE_OAUTH_SERVER_CLIENT_ID") ?: "")}\"" + "\"${ + env.fetch( + "GOOGLE_OAUTH_SERVER_CLIENT_ID", + System.getenv("GOOGLE_OAUTH_SERVER_CLIENT_ID") ?: "" + ) + }\"" ) } @@ -58,10 +63,24 @@ android { if (env.fetch("RELEASE_MODE", (System.getenv("RELEASE_MODE") ?: "false")) == "true") { signingConfigs { create("release") { - storePassword = env.fetch( "ANDROID_RELEASE_STORE_PASSWORD", (System.getenv("ANDROID_RELEASE_STORE_PASSWORD") ?: "")) - keyAlias = env.fetch("ANDROID_RELEASE_KEY_ALIAS", (System.getenv("ANDROID_RELEASE_KEY_ALIAS") ?: "")) - keyPassword = env.fetch("ANDROID_RELEASE_KEY_PASSWORD", (System.getenv("ANDROID_RELEASE_KEY_PASSWORD") ?: "")) - storeFile = file(env.fetch("ANDROID_RELEASE_STORE_FILE_BASE64", (System.getenv("ANDROID_RELEASE_STORE_FILE_BASE64") ?: ""))) + storePassword = env.fetch( + "ANDROID_RELEASE_STORE_PASSWORD", + (System.getenv("ANDROID_RELEASE_STORE_PASSWORD") ?: "") + ) + keyAlias = env.fetch( + "ANDROID_RELEASE_KEY_ALIAS", + (System.getenv("ANDROID_RELEASE_KEY_ALIAS") ?: "") + ) + keyPassword = env.fetch( + "ANDROID_RELEASE_KEY_PASSWORD", + (System.getenv("ANDROID_RELEASE_KEY_PASSWORD") ?: "") + ) + storeFile = file( + env.fetch( + "ANDROID_RELEASE_STORE_FILE_BASE64", + (System.getenv("ANDROID_RELEASE_STORE_FILE_BASE64") ?: "") + ) + ) } } buildTypes { @@ -81,13 +100,25 @@ android { } packaging { resources { - excludes += arrayOf("META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + excludes += arrayOf( + "README.txt", + "META-INF/LICENSE.md", + "META-INF/LICENSE-notice.md", + "**/attach_hotspot_windows.dll", + "META-INF/AL2.0", + "META-INF/LGPL2.1", + "META-INF/licenses/ASM" + ) } } } dependencies { - if (env.fetch("USE_LOCAL_DEPENDENCY", (System.getenv("USE_LOCAL_DEPENDENCY") ?: "false")) == "true") { + if (env.fetch( + "USE_LOCAL_DEPENDENCY", + (System.getenv("USE_LOCAL_DEPENDENCY") ?: "false") + ) == "true" + ) { implementation(project(":emarsys-sdk")) implementation(project(":emarsys-firebase")) implementation(project(":emarsys-huawei")) diff --git a/testUtils/build.gradle.kts b/testUtils/build.gradle.kts index 95269230..b75b1368 100644 --- a/testUtils/build.gradle.kts +++ b/testUtils/build.gradle.kts @@ -15,8 +15,6 @@ android { targetSdk = libs.versions.android.targetSdk.get().toInt() } testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - testInstrumentationRunnerArguments["runnerBuilder"] = - "de.mannodermaus.junit5.AndroidJUnit5Builder" } buildTypes { @@ -30,7 +28,15 @@ android { } packaging { resources { - excludes += arrayOf("README.txt", "META-INF/LICENSE.md", "META-INF/LICENSE-notice.md") + excludes += arrayOf( + "README.txt", + "META-INF/LICENSE.md", + "META-INF/LICENSE-notice.md", + "**/attach_hotspot_windows.dll", + "META-INF/AL2.0", + "META-INF/LGPL2.1", + "META-INF/licenses/ASM" + ) } } compileOptions { @@ -54,7 +60,9 @@ dependencies { api(libs.kotlin.stdlib) implementation(libs.kotlin.reflect) + api(libs.junit) api(libs.kotest.assertions.core) + api(libs.kotest.runner.junit4) api(libs.mockito.android) api(libs.mockito.kotlin) api(libs.androidx.test.rules) @@ -63,21 +71,10 @@ dependencies { api(libs.mockk.android) api(libs.mockk.agent) - api("de.mannodermaus.junit5:android-test-core:1.4.0") - api("de.mannodermaus.junit5:android-test-runner:1.4.0") - api("de.mannodermaus.junit5:android-test-extensions:1.4.0") - api("org.junit.jupiter:junit-jupiter-api:5.10.0") - api("org.junit.jupiter:junit-jupiter:5.10.0") - api("org.junit-pioneer:junit-pioneer:2.2.0") - runtimeOnly("org.junit.jupiter:junit-jupiter-engine:5.10.0") - androidTestApi("org.junit.jupiter:junit-jupiter-api:5.10.0") - androidTestRuntimeOnly("de.mannodermaus.junit5:android-test-runner:1.4.0") - coreLibraryDesugaring(libs.android.tools.desugar) } configurations { api { exclude(group = "io.mockk", module = "mockk-agent-jvm") } -} -junitPlatform {} \ No newline at end of file +} \ No newline at end of file diff --git a/testUtils/src/main/java/com/emarsys/testUtil/JUnitTestEngineListener.kt b/testUtils/src/main/java/com/emarsys/testUtil/JUnitTestEngineListener.kt new file mode 100644 index 00000000..954a8410 --- /dev/null +++ b/testUtils/src/main/java/com/emarsys/testUtil/JUnitTestEngineListener.kt @@ -0,0 +1,41 @@ +package com.emarsys.testUtil + + +import io.kotest.core.config.ProjectConfiguration +import io.kotest.core.test.TestCase +import io.kotest.core.test.TestResult +import io.kotest.engine.listener.AbstractTestEngineListener +import io.kotest.engine.test.names.DefaultDisplayNameFormatter +import org.junit.runner.Description +import org.junit.runner.Description.createTestDescription +import org.junit.runner.notification.Failure +import org.junit.runner.notification.RunNotifier + +class JUnitTestEngineListener( + private val notifier: RunNotifier, +) : AbstractTestEngineListener() { + + private val formatter = DefaultDisplayNameFormatter(ProjectConfiguration()) + + override suspend fun testStarted(testCase: TestCase) { + notifier.fireTestStarted(describeTestCase(testCase, formatter.format(testCase))) + } + + override suspend fun testFinished(testCase: TestCase, result: TestResult) { + val desc = describeTestCase(testCase, formatter.format(testCase)) + when (result) { + is TestResult.Success -> notifier.fireTestFinished(desc) + is TestResult.Error -> notifyFailure(desc, result) + is TestResult.Ignored -> notifier.fireTestIgnored(desc) + is TestResult.Failure -> notifyFailure(desc, result) + } + } + + private fun notifyFailure(desc: Description, result: TestResult) { + notifier.fireTestFailure(Failure(desc, result.errorOrNull)) + notifier.fireTestFinished(desc) + } +} + +internal fun describeTestCase(testCase: TestCase, displayName: String) = + createTestDescription(testCase.spec::class.java, displayName) \ No newline at end of file diff --git a/testUtils/src/main/java/com/emarsys/testUtil/KotestRunnerAndroid.kt b/testUtils/src/main/java/com/emarsys/testUtil/KotestRunnerAndroid.kt new file mode 100644 index 00000000..3820e331 --- /dev/null +++ b/testUtils/src/main/java/com/emarsys/testUtil/KotestRunnerAndroid.kt @@ -0,0 +1,45 @@ +package com.emarsys.testUtil + +import io.kotest.core.config.EmptyExtensionRegistry +import io.kotest.core.config.ProjectConfiguration +import io.kotest.core.spec.Spec +import io.kotest.engine.TestEngineLauncher +import io.kotest.engine.spec.Materializer +import io.kotest.engine.spec.createAndInitializeSpec +import io.kotest.engine.test.names.DefaultDisplayNameFormatter +import kotlinx.coroutines.runBlocking +import org.junit.runner.Description +import org.junit.runner.Runner +import org.junit.runner.notification.RunNotifier + +class KotestRunnerAndroid( + private val kClass: Class +) : Runner() { + private val formatter = DefaultDisplayNameFormatter(ProjectConfiguration()) + + override fun run(notifier: RunNotifier) { + runBlocking { + val listener = JUnitTestEngineListener(notifier) + TestEngineLauncher(listener).withClasses(kClass.kotlin).launch() + } + } + + override fun getDescription(): Description { + val spec = runBlocking { + createAndInitializeSpec( + kClass.kotlin, + EmptyExtensionRegistry + ).getOrThrow() + } + val desc = Description.createSuiteDescription(spec::class.java) + Materializer(ProjectConfiguration()).materialize(spec).forEach { rootTest -> + desc.addChild( + describeTestCase( + rootTest, + formatter.format(rootTest) + ) + ) + } + return desc + } +} \ No newline at end of file diff --git a/testUtils/src/main/java/com/emarsys/testUtil/RetryUtils.kt b/testUtils/src/main/java/com/emarsys/testUtil/RetryUtils.kt new file mode 100644 index 00000000..54168b21 --- /dev/null +++ b/testUtils/src/main/java/com/emarsys/testUtil/RetryUtils.kt @@ -0,0 +1,9 @@ +package com.emarsys.testUtil + +import com.emarsys.testUtil.rules.RetryRule + +object RetryUtils { + @JvmStatic + val retryRule + get() = RetryRule(3) +} \ No newline at end of file diff --git a/testUtils/src/main/java/com/emarsys/testUtil/Specs.kt b/testUtils/src/main/java/com/emarsys/testUtil/Specs.kt new file mode 100644 index 00000000..9ed83223 --- /dev/null +++ b/testUtils/src/main/java/com/emarsys/testUtil/Specs.kt @@ -0,0 +1,44 @@ +package com.emarsys.testUtil + +import org.junit.runner.RunWith + + +@RunWith(KotestRunnerAndroid::class) +abstract class FunSpec(body: io.kotest.core.spec.style.FunSpec.() -> Unit = {}) : + io.kotest.core.spec.style.FunSpec(body) + +@RunWith(KotestRunnerAndroid::class) +abstract class AnnotationSpec : + io.kotest.core.spec.style.AnnotationSpec() + +@RunWith(KotestRunnerAndroid::class) +abstract class StringSpec(body: io.kotest.core.spec.style.StringSpec.() -> Unit = {}) : + io.kotest.core.spec.style.StringSpec(body) + +@RunWith(KotestRunnerAndroid::class) +abstract class ShouldSpec(body: io.kotest.core.spec.style.ShouldSpec.() -> Unit = {}) : + io.kotest.core.spec.style.ShouldSpec(body) + +@RunWith(KotestRunnerAndroid::class) +abstract class DescribeSpec(body: io.kotest.core.spec.style.DescribeSpec.() -> Unit = {}) : + io.kotest.core.spec.style.DescribeSpec(body) + +@RunWith(KotestRunnerAndroid::class) +abstract class ExpectSpec(body: io.kotest.core.spec.style.ExpectSpec.() -> Unit = {}) : + io.kotest.core.spec.style.ExpectSpec(body) + +@RunWith(KotestRunnerAndroid::class) +abstract class FeatureSpec(body: io.kotest.core.spec.style.FeatureSpec.() -> Unit = {}) : + io.kotest.core.spec.style.FeatureSpec(body) + +@RunWith(KotestRunnerAndroid::class) +abstract class FreeSpec(body: io.kotest.core.spec.style.FreeSpec.() -> Unit = {}) : + io.kotest.core.spec.style.FreeSpec(body) + +@RunWith(KotestRunnerAndroid::class) +abstract class WordSpec(body: io.kotest.core.spec.style.WordSpec.() -> Unit = {}) : + io.kotest.core.spec.style.WordSpec(body) + +@RunWith(KotestRunnerAndroid::class) +abstract class BehaviorSpec(body: io.kotest.core.spec.style.BehaviorSpec.() -> Unit = {}) : + io.kotest.core.spec.style.BehaviorSpec(body) \ No newline at end of file diff --git a/testUtils/src/main/java/com/emarsys/testUtil/rules/ConnectionRule.kt b/testUtils/src/main/java/com/emarsys/testUtil/rules/ConnectionRule.kt index 0eec0aca..fab45427 100644 --- a/testUtils/src/main/java/com/emarsys/testUtil/rules/ConnectionRule.kt +++ b/testUtils/src/main/java/com/emarsys/testUtil/rules/ConnectionRule.kt @@ -2,12 +2,20 @@ package com.emarsys.testUtil.rules import android.app.Application import com.emarsys.testUtil.ConnectionTestUtils -import org.junit.jupiter.api.extension.BeforeEachCallback -import org.junit.jupiter.api.extension.ExtensionContext +import org.junit.rules.TestRule +import org.junit.runner.Description +import org.junit.runners.model.Statement -class ConnectionExtension(private val application: Application) : BeforeEachCallback { - override fun beforeEach(p0: ExtensionContext?) { - ConnectionTestUtils.checkConnection(application) +class ConnectionRule(private val application: Application) : TestRule { + + override fun apply(base: Statement?, description: Description?): Statement { + return object : Statement() { + override fun evaluate() { + ConnectionTestUtils.checkConnection(application) + base?.evaluate() + return + } + } } diff --git a/testUtils/src/main/java/com/emarsys/testUtil/rules/DuplicatedThreadRule.kt b/testUtils/src/main/java/com/emarsys/testUtil/rules/DuplicatedThreadRule.kt index 592bc89b..3454c3d2 100644 --- a/testUtils/src/main/java/com/emarsys/testUtil/rules/DuplicatedThreadRule.kt +++ b/testUtils/src/main/java/com/emarsys/testUtil/rules/DuplicatedThreadRule.kt @@ -1,17 +1,22 @@ package com.emarsys.testUtil.rules +import org.junit.rules.TestRule +import org.junit.runner.Description +import org.junit.runners.model.Statement -import org.junit.jupiter.api.extension.BeforeEachCallback -import org.junit.jupiter.api.extension.ExtensionContext +class DuplicatedThreadRule(private val threadName: String) : TestRule { -class DuplicatedThreadExtension(private val threadName: String = "CoreSDKHandlerThread") : - BeforeEachCallback { - - override fun beforeEach(p0: ExtensionContext?) { - val threads = - Thread.getAllStackTraces().keys.map { it.name }.filter { it.startsWith(threadName) } - if (threads.size > 1) { - throw Throwable("TEST: $threadName thread is duplicated") + override fun apply(base: Statement?, description: Description?): Statement { + return object : Statement() { + override fun evaluate() { + val threads = Thread.getAllStackTraces().keys.map { it.name } + .filter { it.startsWith(threadName) } + if (threads.size > 1) { + throw Throwable("TEST: $threadName thread is duplicated") + } + base?.evaluate() + return + } } } diff --git a/testUtils/src/main/java/com/emarsys/testUtil/rules/RetryRule.kt b/testUtils/src/main/java/com/emarsys/testUtil/rules/RetryRule.kt new file mode 100644 index 00000000..b0bba3e9 --- /dev/null +++ b/testUtils/src/main/java/com/emarsys/testUtil/rules/RetryRule.kt @@ -0,0 +1,32 @@ +package com.emarsys.testUtil.rules + +import android.util.Log +import org.junit.rules.TestRule +import org.junit.runner.Description +import org.junit.runners.model.Statement + + +class RetryRule(private val retryCount: Int) : TestRule { + + override fun apply(base: Statement, description: Description) = statement(base, description) + + private fun statement(base: Statement, description: Description): Statement { + return object : Statement() { + override fun evaluate() { + var caughtThrowable: Throwable? = null + + for (i in 0..retryCount) { + try { + base.evaluate() + return + } catch (t: Throwable) { + caughtThrowable = t + Log.e("TEST", "${description.displayName}: run ${(i + 1)} failed.") + } + } + Log.e("TEST", "${description.displayName}: giving up after $retryCount failures.") + throw caughtThrowable!! + } + } + } +} \ No newline at end of file From acc36b9b8ce3aceb2d2623e752553a8e8103db94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Tue, 27 Feb 2024 13:20:04 +0100 Subject: [PATCH 23/63] test(geofence): use real context SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .../mobileengage/geofence/DefaultGeofenceInternalTest.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt index 7f695c88..2c31e924 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt @@ -8,6 +8,7 @@ import android.content.pm.PackageManager import android.location.Location import android.location.LocationManager import android.os.Build +import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation import com.emarsys.core.api.MissingPermissionException import com.emarsys.core.concurrency.ConcurrentHandlerHolderFactory import com.emarsys.core.handler.ConcurrentHandlerHolder @@ -120,6 +121,7 @@ class DefaultGeofenceInternalTest : AnnotationSpec() { ) mockContext = mock() + val context: Context = getInstrumentation().targetContext whenever(mockContext.packageName).thenReturn( "com.emarsys.mobileengage.test" ) @@ -127,10 +129,9 @@ class DefaultGeofenceInternalTest : AnnotationSpec() { whenever(mockContext.attributionTag).thenReturn("tag") } - val intent = Intent("com.emarsys.sdk.GEOFENCE_ACTION") pendingIntent = - PendingIntent.getBroadcast(mockContext, 0, intent, PendingIntent.FLAG_IMMUTABLE) + PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE) mockPendingIntentProvider = mock() whenever(mockPendingIntentProvider.providePendingIntent()).thenReturn(pendingIntent) From 5279c52bce0bcbb223960a47473f201c43c6ffe7 Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Tue, 27 Feb 2024 14:16:54 +0100 Subject: [PATCH 24/63] test(geofence): fix verification syntax issue SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: megamegax --- .../mobileengage/geofence/DefaultGeofenceInternalTest.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt index 2c31e924..60ddfc72 100644 --- a/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt +++ b/mobile-engage/src/androidTest/java/com/emarsys/mobileengage/geofence/DefaultGeofenceInternalTest.kt @@ -257,7 +257,7 @@ class DefaultGeofenceInternalTest : AnnotationSpec() { geofenceInternal.enable(null) if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) { - verify(mockPermissionChecker.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)) + verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) } @@ -435,7 +435,7 @@ class DefaultGeofenceInternalTest : AnnotationSpec() { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) { verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) verify(mockPermissionChecker).checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) - verify(mockFusedLocationProviderClient.lastLocation) + verify(mockFusedLocationProviderClient).lastLocation } } From 3e97a648b9783d6d98937a5da60aed01e976d755 Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Tue, 27 Feb 2024 15:05:02 +0100 Subject: [PATCH 25/63] chore(pipeline): added reporting and lint to new on push workflow SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: megamegax --- .github/workflows/on_push_workflow_new.yml | 192 +++++---------------- Makefile | 7 +- 2 files changed, 49 insertions(+), 150 deletions(-) diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml index 903d2fcb..ec828838 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/on_push_workflow_new.yml @@ -31,16 +31,17 @@ env: jobs: Test: runs-on: ubuntu-latest - name: Test modules + name: Test & Lint strategy: matrix: include: - - module: core - - module: mobile-engage - - module: predict - - module: emarsys-firebase - - module: emarsys-huawei - - module: emarsys-sdk + - task: core + - task: mobile-engage + - task: predict + - task: emarsys-firebase + - task: emarsys-huawei + - task: emarsys-sdk + - task: lint steps: - uses: actions/checkout@v4 with: @@ -78,159 +79,58 @@ jobs: run: make build-test - name: Test core - if: matrix.module == 'core' + if: matrix.task == 'core' run: make test-android-firebase-emulator MODULE_NAME=core - name: Test mobile-engage - if: matrix.module == 'mobile-engage' + if: matrix.task == 'mobile-engage' run: make test-android-firebase-emulator MODULE_NAME=mobile-engage - name: Test predict - if: matrix.module == 'predict' + if: matrix.task == 'predict' run: make test-android-firebase-emulator MODULE_NAME=predict - name: Test emarsys-firebase - if: matrix.module == 'emarsys-firebase' + if: matrix.task == 'emarsys-firebase' run: make test-android-firebase-emulator MODULE_NAME=emarsys-firebase - name: Test emarsys-huawei if: matrix.module == 'emarsys-huawei' - run: make test-android-firebase-emulator MODULE_NAME=emarsys-huawei + run: make task-android-firebase-emulator MODULE_NAME=emarsys-huawei - name: Test emarsys-sdk - if: matrix.module == 'emarsys-sdk' + if: matrix.task == 'emarsys-sdk' run: make test-android-firebase-emulator MODULE_NAME=emarsys-sdk -# GradleLint: -# name: Run lint on project -# runs-on: ubuntu-latest -# steps: -# - uses: actions/checkout@v3 -# with: -# submodules: true -# fetch-depth: 0 # 0 indicates all history -# - run: git fetch --all || echo "==> Accept any result" -# - name: set up JDK 1.17 -# uses: actions/setup-java@v3 -# with: -# distribution: 'temurin' -# java-version: 17 -# - name: create-google services json -# uses: jsdaniell/create-json@1.1.2 -# with: -# name: google-services.json -# json: ${{ secrets.GOOGLE_SERVICES_JSON }} -# dir: sample -# -# - name: create local.properties -# run: echo $ANDROID_HOME > local.properties -# -# - name: Lint project with Gradle -# run: ./gradlew lint - -# CreateReleaseBundle: -# name: Create release bundle -# needs: Build -# runs-on: ubuntu-latest -# steps: -# - uses: actions/checkout@v3 -# with: -# submodules: true -# fetch-depth: 0 # 0 indicates all history -# - run: git fetch --all || echo "==> Accept any result" -# - name: set up JDK 1.17 -# uses: actions/setup-java@v3 -# with: -# distribution: 'temurin' -# java-version: 17 -# - name: create-google services json -# uses: jsdaniell/create-json@1.1.2 -# with: -# name: google-services.json -# json: ${{ secrets.GOOGLE_SERVICES_JSON }} -# dir: sample -# -# - name: create local.properties -# run: echo $ANDROID_HOME > local.properties -# -# - name: Create release keystore file -# shell: bash -# run: | -# echo "${{ secrets.ANDROID_KEYSTORE }}" > mobile-team-android.jks.asc -# gpg -d --passphrase "${{ secrets.ANDROID_GPG_PASSWORD }}" --batch mobile-team-android.jks.asc > sample/mobile-team-android.jks -# - name: Create release sample app with Gradle -# run: ./gradlew :sample:bundleRelease -# -# - name: Upload bundle -# uses: actions/upload-artifact@v2 -# with: -# name: mobile-sdk-sample -# path: sample/build/outputs/bundle/release/sample-release.aab - -# ReleaseSample: -# name: Release sample app -# runs-on: ubuntu-latest -# needs: [ Build, TestCore, TestMobileEngage, TestPredict, TestEmarsysSDK, TestEmarsys, TestCommon, TestEmarsysFirebase, TestEmarsysHuawei, CreateReleaseBundle, GradleLint ] -# steps: -# - uses: actions/checkout@v3 -# with: -# submodules: true -# fetch-depth: 0 # 0 indicates all history -# - run: git fetch --all || echo "==> Accept any result" -# -# - name: Download sample app -# uses: actions/download-artifact@v2 -# with: -# name: mobile-sdk-sample -# -# - name: create-google services json -# uses: jsdaniell/create-json@1.1.2 -# with: -# name: google-play-services.json -# json: ${{ secrets.GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON }} -# -# - name: Playstore upload -# uses: r0adkll/upload-google-play@v1.0.15 -# with: -# serviceAccountJson: google-play-services.json -# packageName: com.emarsys.sample -# releaseFile: sample-release.aab -# track: alpha -# -# SlackNotification: -# name: Send slack notification -# runs-on: ubuntu-latest -# needs: [ ReleaseSample ] -# steps: -# - name: Slack Notification -# uses: megamegax/slack_action@0.2.3 -# with: -# channel: '${{env.SLACK_CHANNEL}}' -# message: 'Last push build successful! :man-gesturing-ok: :bananadance:' -# user_name: '${{env.SLACK_USERNAME}}' -# job_status: 'success' -# user_icon: '${{env.SLACK_ICON}}' -# actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" },{ "type": "button", "text": "Install page", "url": "http://ems-mobileteam-artifacts.s3-website-eu-west-1.amazonaws.com/index-ems.html" }]' - -# -# SlackNotificationOnError: -# name: Send slack on error -# runs-on: ubuntu-latest -# needs: [ ReleaseSample ] -# if: ${{ failure() }} -# steps: -# - uses: actions/checkout@v3 -# with: -# submodules: true -# fetch-depth: 0 # 0 indicates all history -# - run: git fetch --all || echo "==> Accept any result" -# -# - name: Slack Notification -# uses: megamegax/slack_action@0.2.3 -# with: -# channel: '${{env.SLACK_CHANNEL}}' -# message: 'Last push build failed! :man-gesturing-no: :blobcatfearful:' -# user_name: '${{env.SLACK_USERNAME}}' -# job_status: 'failure' -# user_icon: '${{env.SLACK_ICON}}' -# actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" }]' + - name: Run lint + if: matrix.task == 'lint' + run: make lint + + Report: + if: always() + needs: [ Test ] + runs-on: ubuntu-latest + steps: + - name: Report on Slack (Error) + if: ${{ !cancelled() && contains(needs.*.result, 'failure') }} + uses: megamegax/slack_action@0.3.1 + with: + webhook_url: '${{env.SLACK_WEBHOOK}}' + channel: '${{env.SLACK_CHANNEL}}' + message: 'On push workflow failed! :man-gesturing-no: :blobcatfearful:' + user_name: '${{env.SLACK_USERNAME}}' + job_status: 'failure' + user_icon: '${{env.SLACK_ICON}}' + actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" }]' + + - name: Report on Slack (Success) + if: ${{ !contains(needs.*.result, 'cancelled') && !contains(needs.*.result, 'failure') }} + uses: megamegax/slack_action@0.3.1 + with: + webhook_url: '${{env.SLACK_WEBHOOK}}' + channel: '${{env.SLACK_CHANNEL}}' + message: 'On push workflow successful! :man-gesturing-ok: :success-kid:' + user_name: '${{env.SLACK_USERNAME}}' + job_status: 'success' + user_icon: '${{env.SLACK_ICON}}' + actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" },{ "type": "button", "text": "Install page", "url": "http://ems-mobileteam-artifacts.s3-website-eu-west-1.amazonaws.com/index-ems.html" }]' \ No newline at end of file diff --git a/Makefile b/Makefile index 14f23679..5416f2dc 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: check-env help build-test create-testing-apks prepare-ci run-github-workflow-locally test-android-firebase test-android-firebase-emulator +.PHONY: check-env help build-test create-testing-apks lint prepare-ci run-github-workflow-locally test-android-firebase test-android-firebase-emulator .DEFAULT_GOAL := help SHELL := /bin/bash @@ -32,9 +32,8 @@ build-test: check-env ## builds android tests excluding and lint create-testing-apks: check-env ## create apks for testing @./gradlew assembleAndroidTest -x :sample:test -prepare-ci: check-env ## setup prerequisites for pipeline - @echo $ANDROID_HOME > local.properties - @./gradlew base64EnvToFile -PpropertyName=GOOGLE_SERVICES_JSON_BASE64 -Pfile=./sample/google-services.json +lint: check-env ## run lint + @./gradlew lint test-android-firebase-emulator: check-env ## run Android Instrumented tests on emulators on Firebase Test Lab @gcloud firebase test android run \ From f0c43f9e7e6c6efd94b5e868138a3207013f2b93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Tue, 27 Feb 2024 15:14:03 +0100 Subject: [PATCH 26/63] feat(dependabot): add automatic dependency update SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .github/dependabot.yml | 18 +++++++ .../workflows/auto_merge_dependabot_pr.yml | 51 +++++++++++++++++++ .github/workflows/on_push_workflow_new.yml | 15 +++++- 3 files changed, 82 insertions(+), 2 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/auto_merge_dependabot_pr.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..f428797f --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,18 @@ +version: 2 +updates: + - package-ecosystem: "gradle" + target-branch: "dev" + directory: "/" + schedule: + interval: "daily" + commit-message: + prefix: "chore(dependabot)" + open-pull-requests-limit: 5 + - package-ecosystem: "github-actions" + target-branch: "dev" + directory: "/" + schedule: + interval: "daily" + commit-message: + prefix: "chore(dependabot)" + open-pull-requests-limit: 5 \ No newline at end of file diff --git a/.github/workflows/auto_merge_dependabot_pr.yml b/.github/workflows/auto_merge_dependabot_pr.yml new file mode 100644 index 00000000..281d9674 --- /dev/null +++ b/.github/workflows/auto_merge_dependabot_pr.yml @@ -0,0 +1,51 @@ +name: Auto-Merge Dependabot PRs on CI Success + +on: + repository_dispatch: + types: [ checks-complete ] +jobs: + auto-merge: + runs-on: ubuntu-latest + steps: + - run: echo "PR_NUMBER=${{ toJson(github.event.client_payload.prNumber) }}" >> $GITHUB_ENV + - name: Wait for 10 seconds + run: sleep 10 + - name: Check CI status and Merge PR + uses: actions/github-script@v7 + with: + script: | + const prNumber = process.env.PR_NUMBER; + if (!prNumber) { + console.log("No PR number found."); + return; + } + + const { data: pullRequest } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: prNumber, + }); + if(pullRequest.merged) { + console.log(`PR #${prNumber} is already merged.`); + return; + } + const { data: listCheckRuns } = await github.rest.checks.listForRef({ + owner: context.repo.owner, + repo: context.repo.repo, + ref: pullRequest.head.sha, + }); + console.log("checks: ", listCheckRuns); + const allChecksPassed = listCheckRuns.check_runs.every(check => check.conclusion === 'success' || check.name === 'Inclusive Language' || check.conclusion === 'skipped'); + + if (allChecksPassed) { + await github.rest.pulls.merge({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: prNumber, + }); + console.log(`Merged PR #${prNumber}`); + } else { + console.log(`Not all checks passed for PR #${prNumber}`); + } + + github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml index ec828838..7e5cd6c0 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/on_push_workflow_new.yml @@ -1,9 +1,12 @@ name: New on commit workflow on: + pull_request: + types: [ opened, reopened, synchronize ] workflow_dispatch: push: - branches: [ dev ] + branches-ignore: + - 'dependabot/**' env: USE_LOCAL_DEPENDENCY: ${{ vars.USE_LOCAL_DEPENDENCY }} @@ -133,4 +136,12 @@ jobs: user_name: '${{env.SLACK_USERNAME}}' job_status: 'success' user_icon: '${{env.SLACK_ICON}}' - actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" },{ "type": "button", "text": "Install page", "url": "http://ems-mobileteam-artifacts.s3-website-eu-west-1.amazonaws.com/index-ems.html" }]' \ No newline at end of file + actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" },{ "type": "button", "text": "Install page", "url": "http://ems-mobileteam-artifacts.s3-website-eu-west-1.amazonaws.com/index-ems.html" }]' + + - name: Trigger automerge + if: ${{ !contains(needs.*.result, 'cancelled') && !contains(needs.*.result, 'failure') && github.event.pull_request != null && github.actor == 'dependabot[bot]' && github.event.pull_request.merged == false}} + uses: peter-evans/repository-dispatch@v3 + with: + token: ${{ secrets.AUTO_MERGE_TOKEN }} + event-type: checks-complete + client-payload: '{ "prNumber": "${{ github.event.pull_request.number }}"}' \ No newline at end of file From 2c7d0ce77c142538e6af4241dc820c23d61d377b Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Tue, 27 Feb 2024 15:17:50 +0100 Subject: [PATCH 27/63] chore(pipeline): readd prepare-ci make command SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: megamegax --- Makefile | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Makefile b/Makefile index 5416f2dc..1ed6aa15 100644 --- a/Makefile +++ b/Makefile @@ -35,6 +35,10 @@ create-testing-apks: check-env ## create apks for testing lint: check-env ## run lint @./gradlew lint +prepare-ci: check-env ## setup prerequisites for pipeline + @echo $ANDROID_HOME > local.properties + @./gradlew base64EnvToFile -PpropertyName=GOOGLE_SERVICES_JSON_BASE64 -Pfile=./sample/google-services.json + test-android-firebase-emulator: check-env ## run Android Instrumented tests on emulators on Firebase Test Lab @gcloud firebase test android run \ --type instrumentation \ From 1477c6b2f1a652e9486e37d44651403c9566db58 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 27 Feb 2024 14:18:08 +0000 Subject: [PATCH 28/63] chore(dependabot): bump google-github-actions/auth from 2.1.1 to 2.1.2 Bumps [google-github-actions/auth](https://github.com/google-github-actions/auth) from 2.1.1 to 2.1.2. - [Release notes](https://github.com/google-github-actions/auth/releases) - [Changelog](https://github.com/google-github-actions/auth/blob/main/CHANGELOG.md) - [Commits](https://github.com/google-github-actions/auth/compare/v2.1.1...v2.1.2) --- updated-dependencies: - dependency-name: google-github-actions/auth dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/on_push_workflow_new.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml index 7e5cd6c0..561af295 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/on_push_workflow_new.yml @@ -69,7 +69,7 @@ jobs: run: make prepare-ci - name: Authenticate to Google Cloud - uses: google-github-actions/auth@v2.1.1 + uses: google-github-actions/auth@v2.1.2 with: credentials_json: ${{ env.FIREBASE_SERVICE_ACCOUNT_JSON }} From 5f802ed6beb9a359d055365f806909857a9bb6da Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 27 Feb 2024 14:18:11 +0000 Subject: [PATCH 29/63] chore(dependabot): bump r0adkll/upload-google-play from 1.0.15 to 1.1.3 Bumps [r0adkll/upload-google-play](https://github.com/r0adkll/upload-google-play) from 1.0.15 to 1.1.3. - [Release notes](https://github.com/r0adkll/upload-google-play/releases) - [Commits](https://github.com/r0adkll/upload-google-play/compare/v1.0.15...v1.1.3) --- updated-dependencies: - dependency-name: r0adkll/upload-google-play dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/nightly_workflow.yml | 2 +- .github/workflows/on_push_workflow.yml | 2 +- .github/workflows/on_tag_workflow.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/nightly_workflow.yml b/.github/workflows/nightly_workflow.yml index 22cbdfd0..a8bc9b6c 100644 --- a/.github/workflows/nightly_workflow.yml +++ b/.github/workflows/nightly_workflow.yml @@ -433,7 +433,7 @@ jobs: json: ${{ secrets.GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON }} - name: Playstore upload - uses: r0adkll/upload-google-play@v1.0.15 + uses: r0adkll/upload-google-play@v1.1.3 with: serviceAccountJson: google-play-services.json packageName: com.emarsys.sample diff --git a/.github/workflows/on_push_workflow.yml b/.github/workflows/on_push_workflow.yml index 51f3b5fc..42acc1ba 100644 --- a/.github/workflows/on_push_workflow.yml +++ b/.github/workflows/on_push_workflow.yml @@ -434,7 +434,7 @@ jobs: json: ${{ secrets.GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON }} - name: Playstore upload - uses: r0adkll/upload-google-play@v1.0.15 + uses: r0adkll/upload-google-play@v1.1.3 with: serviceAccountJson: google-play-services.json packageName: com.emarsys.sample diff --git a/.github/workflows/on_tag_workflow.yml b/.github/workflows/on_tag_workflow.yml index 5cb2c7f9..955c5cf1 100644 --- a/.github/workflows/on_tag_workflow.yml +++ b/.github/workflows/on_tag_workflow.yml @@ -130,7 +130,7 @@ jobs: json: ${{ secrets.GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON }} - name: Playstore upload - uses: r0adkll/upload-google-play@v1.1.1 + uses: r0adkll/upload-google-play@v1.1.3 with: serviceAccountJson: google-play-services.json packageName: com.emarsys.sample From 74a9eebd90bc7cddd94709bc64752a35ae2a2a51 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 27 Feb 2024 14:18:14 +0000 Subject: [PATCH 30/63] chore(dependabot): bump actions/upload-artifact from 2 to 4 Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 2 to 4. - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/v2...v4) --- updated-dependencies: - dependency-name: actions/upload-artifact dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/nightly_e2e_workflow.yml | 4 ++-- .github/workflows/nightly_workflow.yml | 20 ++++++++++---------- .github/workflows/on_push_workflow.yml | 20 ++++++++++---------- .github/workflows/on_tag_workflow.yml | 2 +- 4 files changed, 23 insertions(+), 23 deletions(-) diff --git a/.github/workflows/nightly_e2e_workflow.yml b/.github/workflows/nightly_e2e_workflow.yml index 161ffe23..ba2a6a85 100644 --- a/.github/workflows/nightly_e2e_workflow.yml +++ b/.github/workflows/nightly_e2e_workflow.yml @@ -49,13 +49,13 @@ jobs: run: ./gradlew assembleAndroidTest -x lint - name: upload sample app artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: sample path: sample/build/outputs/apk/androidTest/debug/sample-debug-androidTest.apk - name: upload emarsys-e2e-test test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: emarsys-e2e-test path: emarsys-e2e-test/build/outputs/apk/androidTest/debug/emarsys-e2e-test-debug-androidTest.apk diff --git a/.github/workflows/nightly_workflow.yml b/.github/workflows/nightly_workflow.yml index 22cbdfd0..7338d6f7 100644 --- a/.github/workflows/nightly_workflow.yml +++ b/.github/workflows/nightly_workflow.yml @@ -47,55 +47,55 @@ jobs: run: ./gradlew assembleAndroidTest -x lint - name: upload sample app artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: sample path: sample/build/outputs/apk/androidTest/debug/sample-debug-androidTest.apk - name: upload core test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: core path: core/build/outputs/apk/androidTest/debug/core-debug-androidTest.apk - name: upload mobile-engage test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: mobile-engage path: mobile-engage/build/outputs/apk/androidTest/debug/mobile-engage-debug-androidTest.apk - name: upload predict test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: predict path: predict/build/outputs/apk/androidTest/debug/predict-debug-androidTest.apk - name: upload emarsys test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: emarsys path: emarsys/build/outputs/apk/androidTest/debug/emarsys-debug-androidTest.apk - name: upload emarsys-sdk test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: emarsys-sdk path: emarsys-sdk/build/outputs/apk/androidTest/debug/emarsys-sdk-debug-androidTest.apk - name: upload common test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: common path: common/build/outputs/apk/androidTest/debug/common-debug-androidTest.apk - name: upload emarsys-firebase test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: emarsys-firebase path: emarsys-firebase/build/outputs/apk/androidTest/debug/emarsys-firebase-debug-androidTest.apk - name: upload emarsys-huawei test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: emarsys-huawei path: emarsys-huawei/build/outputs/apk/androidTest/debug/emarsys-huawei-debug-androidTest.apk @@ -169,7 +169,7 @@ jobs: run: ./gradlew :sample:bundleRelease - name: Upload bundle - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: mobile-sdk-sample path: sample/build/outputs/bundle/release/sample-release.aab diff --git a/.github/workflows/on_push_workflow.yml b/.github/workflows/on_push_workflow.yml index 51f3b5fc..6f1cb2f0 100644 --- a/.github/workflows/on_push_workflow.yml +++ b/.github/workflows/on_push_workflow.yml @@ -59,55 +59,55 @@ jobs: run: make build-test - name: upload sample app artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: sample path: sample/build/outputs/apk/androidTest/debug/sample-debug-androidTest.apk - name: upload core test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: core path: core/build/outputs/apk/androidTest/debug/core-debug-androidTest.apk - name: upload mobile-engage test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: mobile-engage path: mobile-engage/build/outputs/apk/androidTest/debug/mobile-engage-debug-androidTest.apk - name: upload emarsys-sdk test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: predict path: predict/build/outputs/apk/androidTest/debug/predict-debug-androidTest.apk - name: upload emarsys test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: emarsys path: emarsys/build/outputs/apk/androidTest/debug/emarsys-debug-androidTest.apk - name: upload emarsys-sdk test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: emarsys-sdk path: emarsys-sdk/build/outputs/apk/androidTest/debug/emarsys-sdk-debug-androidTest.apk - name: upload common test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: common path: common/build/outputs/apk/androidTest/debug/common-debug-androidTest.apk - name: upload emarsys-firebase test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: emarsys-firebase path: emarsys-firebase/build/outputs/apk/androidTest/debug/emarsys-firebase-debug-androidTest.apk - name: upload emarsys-huawei test apk artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: emarsys-huawei path: emarsys-huawei/build/outputs/apk/androidTest/debug/emarsys-huawei-debug-androidTest.apk @@ -179,7 +179,7 @@ jobs: run: ./gradlew :sample:bundleRelease - name: Upload bundle - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: mobile-sdk-sample path: sample/build/outputs/bundle/release/sample-release.aab diff --git a/.github/workflows/on_tag_workflow.yml b/.github/workflows/on_tag_workflow.yml index 5cb2c7f9..9f98a6da 100644 --- a/.github/workflows/on_tag_workflow.yml +++ b/.github/workflows/on_tag_workflow.yml @@ -102,7 +102,7 @@ jobs: run: ./gradlew :sample:bundleRelease - name: Upload bundle - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: mobile-sdk-sample path: sample/build/outputs/bundle/release/sample-release.aab From cc700347375fd8b23cc4255ede15623d1ccc88af Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 27 Feb 2024 14:18:17 +0000 Subject: [PATCH 31/63] chore(dependabot): bump actions/download-artifact from 2 to 4 Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 2 to 4. - [Release notes](https://github.com/actions/download-artifact/releases) - [Commits](https://github.com/actions/download-artifact/compare/v2...v4) --- updated-dependencies: - dependency-name: actions/download-artifact dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/nightly_e2e_workflow.yml | 4 +-- .github/workflows/nightly_workflow.yml | 34 +++++++++++----------- .github/workflows/on_push_workflow.yml | 34 +++++++++++----------- .github/workflows/on_tag_workflow.yml | 2 +- 4 files changed, 37 insertions(+), 37 deletions(-) diff --git a/.github/workflows/nightly_e2e_workflow.yml b/.github/workflows/nightly_e2e_workflow.yml index 161ffe23..4ccf27d0 100644 --- a/.github/workflows/nightly_e2e_workflow.yml +++ b/.github/workflows/nightly_e2e_workflow.yml @@ -78,12 +78,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download Emarsys E2E tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: emarsys-e2e-test diff --git a/.github/workflows/nightly_workflow.yml b/.github/workflows/nightly_workflow.yml index 22cbdfd0..b302cd75 100644 --- a/.github/workflows/nightly_workflow.yml +++ b/.github/workflows/nightly_workflow.yml @@ -187,12 +187,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download core tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: core @@ -216,12 +216,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download mobile-engage tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: mobile-engage @@ -245,12 +245,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download predict tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: predict @@ -274,12 +274,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download emarsys-sdk tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: emarsys-sdk @@ -306,12 +306,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download emarsys tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: emarsys @@ -335,12 +335,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download common tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: common @@ -364,12 +364,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download emarsys-firebase tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: emarsys-firebase @@ -393,12 +393,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download emarsys-huawei tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: emarsys-huawei @@ -422,7 +422,7 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: mobile-sdk-sample diff --git a/.github/workflows/on_push_workflow.yml b/.github/workflows/on_push_workflow.yml index 51f3b5fc..49311f88 100644 --- a/.github/workflows/on_push_workflow.yml +++ b/.github/workflows/on_push_workflow.yml @@ -196,12 +196,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download core tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: core @@ -224,12 +224,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download mobile-engage tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: mobile-engage @@ -252,12 +252,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download predict tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: predict @@ -280,12 +280,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download emarsys-sdk tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: emarsys-sdk @@ -311,12 +311,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download emarsys tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: emarsys @@ -339,12 +339,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download common tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: common @@ -367,12 +367,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download emarsys-firebase tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: emarsys-firebase @@ -395,12 +395,12 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: sample - name: Download emarsys-huawei tests - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: emarsys-huawei @@ -423,7 +423,7 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: mobile-sdk-sample diff --git a/.github/workflows/on_tag_workflow.yml b/.github/workflows/on_tag_workflow.yml index 5cb2c7f9..789cafa4 100644 --- a/.github/workflows/on_tag_workflow.yml +++ b/.github/workflows/on_tag_workflow.yml @@ -119,7 +119,7 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: Download sample app - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: mobile-sdk-sample From 3cf5e5c9b098665ebb64e71e99d975352137aa96 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 27 Feb 2024 14:18:20 +0000 Subject: [PATCH 32/63] chore(dependabot): bump actions/setup-java from 3 to 4 Bumps [actions/setup-java](https://github.com/actions/setup-java) from 3 to 4. - [Release notes](https://github.com/actions/setup-java/releases) - [Commits](https://github.com/actions/setup-java/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/setup-java dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/nightly_e2e_workflow.yml | 2 +- .github/workflows/nightly_workflow.yml | 6 +++--- .github/workflows/on_push_workflow.yml | 6 +++--- .github/workflows/on_tag_workflow.yml | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/nightly_e2e_workflow.yml b/.github/workflows/nightly_e2e_workflow.yml index 161ffe23..ed917cae 100644 --- a/.github/workflows/nightly_e2e_workflow.yml +++ b/.github/workflows/nightly_e2e_workflow.yml @@ -30,7 +30,7 @@ jobs: - run: git fetch --all || echo "==> Accept any result" - name: set up JDK 1.17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 diff --git a/.github/workflows/nightly_workflow.yml b/.github/workflows/nightly_workflow.yml index 22cbdfd0..fc58cf9e 100644 --- a/.github/workflows/nightly_workflow.yml +++ b/.github/workflows/nightly_workflow.yml @@ -29,7 +29,7 @@ jobs: fetch-depth: 0 # 0 indicates all history - run: git fetch --all || echo "==> Accept any result" - name: set up JDK 1.17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 @@ -117,7 +117,7 @@ jobs: fetch-depth: 0 # 0 indicates all history - run: git fetch --all || echo "==> Accept any result" - name: set up JDK 1.17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 @@ -146,7 +146,7 @@ jobs: fetch-depth: 0 # 0 indicates all history - run: git fetch --all || echo "==> Accept any result" - name: set up JDK 1.17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 diff --git a/.github/workflows/on_push_workflow.yml b/.github/workflows/on_push_workflow.yml index 51f3b5fc..84852728 100644 --- a/.github/workflows/on_push_workflow.yml +++ b/.github/workflows/on_push_workflow.yml @@ -47,7 +47,7 @@ jobs: fetch-depth: 0 # 0 indicates all history - run: git fetch --all || echo "==> Accept any result" - name: set up JDK 1.17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 @@ -128,7 +128,7 @@ jobs: fetch-depth: 0 # 0 indicates all history - run: git fetch --all || echo "==> Accept any result" - name: set up JDK 1.17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 @@ -156,7 +156,7 @@ jobs: fetch-depth: 0 # 0 indicates all history - run: git fetch --all || echo "==> Accept any result" - name: set up JDK 1.17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 diff --git a/.github/workflows/on_tag_workflow.yml b/.github/workflows/on_tag_workflow.yml index 5cb2c7f9..a31493c2 100644 --- a/.github/workflows/on_tag_workflow.yml +++ b/.github/workflows/on_tag_workflow.yml @@ -34,7 +34,7 @@ jobs: fetch-depth: 0 # 0 indicates all history - run: git fetch --all || echo "==> Accept any result" - name: set up JDK 1.17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 @@ -76,7 +76,7 @@ jobs: fetch-depth: 0 # 0 indicates all history - run: git fetch --all || echo "==> Accept any result" - name: set up JDK 1.17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 From b107f6a0a0f134779182d7defe8fe7baf2bc8fb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Tue, 27 Feb 2024 15:38:29 +0100 Subject: [PATCH 33/63] chore(gap): enable workload_identity based auth SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .github/workflows/on_push_workflow_new.yml | 4 +++- gradle/libs.versions.toml | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml index 561af295..4db228e7 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/on_push_workflow_new.yml @@ -71,7 +71,9 @@ jobs: - name: Authenticate to Google Cloud uses: google-github-actions/auth@v2.1.2 with: - credentials_json: ${{ env.FIREBASE_SERVICE_ACCOUNT_JSON }} + workload_identity_provider: 'projects/942049623025/locations/global/workloadIdentityPools/development/providers/github-actions' + service_account: 'firebase-test-lab-service-acco@ems-mobile-sdk.iam.gserviceaccount.com' + create_credentials_file: true - name: Set up Cloud SDK uses: google-github-actions/setup-gcloud@v2 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index b392166a..43e6c50a 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -49,7 +49,7 @@ webkit = "1.7.0" mockito-android = "5.10.0" mockito-core = "5.10.0" mockito-kotlin = "4.1.0" -grGit = "5.0.0-rc.3" +grGit = "5.2.2" byte-buddy = "1.14.11" dotEnv = "4.0.0" android-tools-desugar = "2.0.4" From ee803cc82d02e1b00451b542985ee37ec269931f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Tue, 27 Feb 2024 15:49:48 +0100 Subject: [PATCH 34/63] chore(gap): enable workload_identity based auth SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .github/workflows/on_push_workflow_new.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml index 4db228e7..41b978f7 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/on_push_workflow_new.yml @@ -71,7 +71,7 @@ jobs: - name: Authenticate to Google Cloud uses: google-github-actions/auth@v2.1.2 with: - workload_identity_provider: 'projects/942049623025/locations/global/workloadIdentityPools/development/providers/github-actions' + workload_identity_provider: 'projects/395478287999/locations/global/workloadIdentityPools/development/providers/github-actions' service_account: 'firebase-test-lab-service-acco@ems-mobile-sdk.iam.gserviceaccount.com' create_credentials_file: true From f29dcac305975e00ddce030fbde4509797363d97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Tue, 27 Feb 2024 15:55:50 +0100 Subject: [PATCH 35/63] chore(pipeline): add permissions SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .github/workflows/on_push_workflow_new.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml index 41b978f7..270bb248 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/on_push_workflow_new.yml @@ -33,6 +33,9 @@ env: jobs: Test: + permissions: + contents: read + id-token: write runs-on: ubuntu-latest name: Test & Lint strategy: From 86f875264560b1fe8855d5ed10184df36f373d52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Tue, 27 Feb 2024 16:10:02 +0100 Subject: [PATCH 36/63] chore(pipeline): add permissions SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .github/workflows/on_push_workflow_new.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml index 270bb248..a4d1ab27 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/on_push_workflow_new.yml @@ -74,7 +74,7 @@ jobs: - name: Authenticate to Google Cloud uses: google-github-actions/auth@v2.1.2 with: - workload_identity_provider: 'projects/395478287999/locations/global/workloadIdentityPools/development/providers/github-actions' + workload_identity_provider: 'projects/395478287999/locations/global/workloadIdentityPools/github-actions/providers/github-actions ' service_account: 'firebase-test-lab-service-acco@ems-mobile-sdk.iam.gserviceaccount.com' create_credentials_file: true From acf5cea11ce1ca4a64bc0e1ccbaaad727babea04 Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Tue, 27 Feb 2024 16:47:19 +0100 Subject: [PATCH 37/63] chore(pipeline): moved workflow_dispatch SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: megamegax --- .github/workflows/on_push_workflow_new.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml index a4d1ab27..56a990f6 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/on_push_workflow_new.yml @@ -3,10 +3,10 @@ name: New on commit workflow on: pull_request: types: [ opened, reopened, synchronize ] - workflow_dispatch: push: branches-ignore: - 'dependabot/**' + workflow_dispatch: env: USE_LOCAL_DEPENDENCY: ${{ vars.USE_LOCAL_DEPENDENCY }} From c0aa084d381e90bb350e34a243428c43d999a16d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Tue, 27 Feb 2024 16:52:18 +0100 Subject: [PATCH 38/63] chore(pipeline): remove project_id SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .github/workflows/on_push_workflow_new.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml index 56a990f6..1f903cf6 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/on_push_workflow_new.yml @@ -80,8 +80,6 @@ jobs: - name: Set up Cloud SDK uses: google-github-actions/setup-gcloud@v2 - with: - project_id: ${{ env.FIREBASE_PROJECT_ID }} - name: Build run: make build-test From e127d636673945e4ae41e144adb8ce8cfded4d09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Tue, 27 Feb 2024 17:22:41 +0100 Subject: [PATCH 39/63] chore(pipeline): set project_id SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .github/workflows/on_push_workflow_new.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/on_push_workflow_new.yml index 1f903cf6..631e2c4b 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/on_push_workflow_new.yml @@ -81,6 +81,9 @@ jobs: - name: Set up Cloud SDK uses: google-github-actions/setup-gcloud@v2 + - run: gcloud info + - run: gcloud config set project ${{ env.FIREBASE_PROJECT_ID }} + - name: Build run: make build-test From 164dcd7fcacc8ec36b1fe6ceb06580513df2350e Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Wed, 28 Feb 2024 11:10:42 +0100 Subject: [PATCH 40/63] chore(pipeline): create sample app release workflow and delete old on push workflow SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: megamegax Co-authored-by: Andras Sarro --- .github/workflows/on_push_workflow.yml | 497 +++--------------- ...ew.yml => release_sample_app_workflow.yml} | 101 +--- .gitignore | 5 +- Makefile | 8 +- 4 files changed, 118 insertions(+), 493 deletions(-) rename .github/workflows/{on_push_workflow_new.yml => release_sample_app_workflow.yml} (54%) diff --git a/.github/workflows/on_push_workflow.yml b/.github/workflows/on_push_workflow.yml index 21c6439e..fdedbd08 100644 --- a/.github/workflows/on_push_workflow.yml +++ b/.github/workflows/on_push_workflow.yml @@ -1,17 +1,14 @@ -name: Last push build +name: On Push on: - workflow_dispatch: + pull_request: + types: [ opened, reopened, synchronize ] push: - branches: [ dev ] + branches-ignore: + - 'dependabot/**' + workflow_dispatch: env: - RELEASE_KEY_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD }} - RELEASE_KEY_ALIAS: ${{ secrets.ANDROID_KEYSTORE_ALIAS }} - RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} - RELEASE_STORE_FILE: ${{ secrets.RELEASE_STORE_FILE }} - DEVELOPMENT_MODE: ${{ secrets.DEVELOPMENT_MODE }} - USE_LOCAL_DEPENDENCY: ${{ vars.USE_LOCAL_DEPENDENCY }} RELEASE_MODE: ${{ vars.RELEASE_MODE }} ANDROID_RELEASE_STORE_FILE_BASE64: ${{ secrets.ANDROID_RELEASE_STORE_FILE_BASE64 }} @@ -35,446 +32,122 @@ env: SLACK_WEBHOOK: ${{ secrets.SLACK_MOBILE_TEAM_CI_CHANNEL_WEBHOOK }} jobs: - Build: - # The type of runner that the job will run on + Test: + permissions: + contents: read + id-token: write runs-on: ubuntu-latest - name: Build job + name: Test & Lint + strategy: + matrix: + include: + - task: core + - task: mobile-engage + - task: predict + - task: emarsys-firebase + - task: emarsys-huawei + - task: emarsys-sdk + - task: lint steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: ref: dev submodules: true fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - name: set up JDK 1.17 - uses: actions/setup-java@v4 - with: - distribution: 'temurin' - java-version: 17 - - - name: Prepare CI - run: make prepare-ci - - name: Build with Gradle - run: make build-test - - - name: upload sample app artifact - uses: actions/upload-artifact@v4 - with: - name: sample - path: sample/build/outputs/apk/androidTest/debug/sample-debug-androidTest.apk - - - name: upload core test apk artifact - uses: actions/upload-artifact@v4 - with: - name: core - path: core/build/outputs/apk/androidTest/debug/core-debug-androidTest.apk - - - name: upload mobile-engage test apk artifact - uses: actions/upload-artifact@v4 - with: - name: mobile-engage - path: mobile-engage/build/outputs/apk/androidTest/debug/mobile-engage-debug-androidTest.apk - - - name: upload emarsys-sdk test apk artifact - uses: actions/upload-artifact@v4 - with: - name: predict - path: predict/build/outputs/apk/androidTest/debug/predict-debug-androidTest.apk - - - name: upload emarsys test apk artifact - uses: actions/upload-artifact@v4 - with: - name: emarsys - path: emarsys/build/outputs/apk/androidTest/debug/emarsys-debug-androidTest.apk - - - name: upload emarsys-sdk test apk artifact - uses: actions/upload-artifact@v4 - with: - name: emarsys-sdk - path: emarsys-sdk/build/outputs/apk/androidTest/debug/emarsys-sdk-debug-androidTest.apk - - - name: upload common test apk artifact - uses: actions/upload-artifact@v4 - with: - name: common - path: common/build/outputs/apk/androidTest/debug/common-debug-androidTest.apk - - - name: upload emarsys-firebase test apk artifact - uses: actions/upload-artifact@v4 - with: - name: emarsys-firebase - path: emarsys-firebase/build/outputs/apk/androidTest/debug/emarsys-firebase-debug-androidTest.apk - - - name: upload emarsys-huawei test apk artifact - uses: actions/upload-artifact@v4 - with: - name: emarsys-huawei - path: emarsys-huawei/build/outputs/apk/androidTest/debug/emarsys-huawei-debug-androidTest.apk - - - name: create testlab services json - uses: jsdaniell/create-json@1.1.2 - with: - name: sacc_key.json - json: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} - - GradleLint: - name: Run lint on project - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - name: set up JDK 1.17 uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 - - name: create-google services json - uses: jsdaniell/create-json@1.1.2 - with: - name: google-services.json - json: ${{ secrets.GOOGLE_SERVICES_JSON }} - dir: sample - - - name: create local.properties - run: echo $ANDROID_HOME > local.properties - - - name: Lint project with Gradle - run: ./gradlew lint - CreateReleaseBundle: - name: Create release bundle - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 with: - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - name: set up JDK 1.17 - uses: actions/setup-java@v4 - with: - distribution: 'temurin' - java-version: 17 - - name: create-google services json - uses: jsdaniell/create-json@1.1.2 - with: - name: google-services.json - json: ${{ secrets.GOOGLE_SERVICES_JSON }} - dir: sample - - - name: create local.properties - run: echo $ANDROID_HOME > local.properties - - - name: Create release keystore file - shell: bash - run: | - echo "${{ secrets.ANDROID_KEYSTORE }}" > mobile-team-android.jks.asc - gpg -d --passphrase "${{ secrets.ANDROID_GPG_PASSWORD }}" --batch mobile-team-android.jks.asc > sample/mobile-team-android.jks - - name: Create release sample app with Gradle - run: ./gradlew :sample:bundleRelease - - - name: Upload bundle - uses: actions/upload-artifact@v4 - with: - name: mobile-sdk-sample - path: sample/build/outputs/bundle/release/sample-release.aab - - TestCore: - name: Run core tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample - - - name: Download core tests - uses: actions/download-artifact@v4 - with: - name: core - - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithSomeVirtualDevices.yml:core' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} - - TestMobileEngage: - name: Run mobile-engage tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample - - - name: Download mobile-engage tests - uses: actions/download-artifact@v4 - with: - name: mobile-engage - - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithSomeVirtualDevices.yml:mobile-engage' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} - - TestPredict: - name: Run predict tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" + gradle-version: 8.6 + cache-overwrite-existing: true + gradle-home-cache-cleanup: true - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample - - - name: Download predict tests - uses: actions/download-artifact@v4 - with: - name: predict - - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithSomeVirtualDevices.yml:predict' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} - - TestEmarsysSDK: - name: Run emarsys-sdk tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample - - - name: Download emarsys-sdk tests - uses: actions/download-artifact@v4 - with: - name: emarsys-sdk - - - name: Display structure of downloaded files - run: ls -R - - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithSomeVirtualDevices.yml:emarsys-sdk' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} - - TestEmarsys: - name: Run emarsys tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample - - - name: Download emarsys tests - uses: actions/download-artifact@v4 - with: - name: emarsys - - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithSomeVirtualDevices.yml:emarsys' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} - - TestCommon: - name: Run common tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" + - name: Prepare CI + run: make prepare-ci - - name: Download sample app - uses: actions/download-artifact@v4 + - name: Authenticate to Google Cloud + uses: google-github-actions/auth@v2.1.2 with: - name: sample + workload_identity_provider: 'projects/395478287999/locations/global/workloadIdentityPools/github-actions/providers/github-actions ' + service_account: 'firebase-test-lab-service-acco@ems-mobile-sdk.iam.gserviceaccount.com' + create_credentials_file: true - - name: Download common tests - uses: actions/download-artifact@v4 - with: - name: common + - name: Set up Cloud SDK + uses: google-github-actions/setup-gcloud@v2 - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithSomeVirtualDevices.yml:common' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} + - run: gcloud info + - run: gcloud config set project ${{ env.FIREBASE_PROJECT_ID }} - TestEmarsysFirebase: - name: Run emarsys-firebase tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" + - name: Build + run: make build-test - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample + - name: Test core + if: matrix.task == 'core' + run: make test-android-firebase-emulator MODULE_NAME=core - - name: Download emarsys-firebase tests - uses: actions/download-artifact@v4 - with: - name: emarsys-firebase + - name: Test mobile-engage + if: matrix.task == 'mobile-engage' + run: make test-android-firebase-emulator MODULE_NAME=mobile-engage - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithSomeVirtualDevices.yml:emarsys-firebase' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} + - name: Test predict + if: matrix.task == 'predict' + run: make test-android-firebase-emulator MODULE_NAME=predict - TestEmarsysHuawei: - name: Run emarsys-huawei tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" + - name: Test emarsys-firebase + if: matrix.task == 'emarsys-firebase' + run: make test-android-firebase-emulator MODULE_NAME=emarsys-firebase - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample + - name: Test emarsys-huawei + if: matrix.module == 'emarsys-huawei' + run: make task-android-firebase-emulator MODULE_NAME=emarsys-huawei - - name: Download emarsys-huawei tests - uses: actions/download-artifact@v4 - with: - name: emarsys-huawei + - name: Test emarsys-sdk + if: matrix.task == 'emarsys-sdk' + run: make test-android-firebase-emulator MODULE_NAME=emarsys-sdk - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithSomeVirtualDevices.yml:emarsys-huawei' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} + - name: Run lint + if: matrix.task == 'lint' + run: make lint - ReleaseSample: - name: Release sample app + Report: + if: always() + needs: [ Test ] runs-on: ubuntu-latest - needs: [ Build, TestCore, TestMobileEngage, TestPredict, TestEmarsysSDK, TestEmarsys, TestCommon, TestEmarsysFirebase, TestEmarsysHuawei, CreateReleaseBundle, GradleLint ] steps: - - uses: actions/checkout@v3 - with: - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: mobile-sdk-sample - - - name: create-google services json - uses: jsdaniell/create-json@1.1.2 + - name: Report on Slack (Error) + if: ${{ !cancelled() && contains(needs.*.result, 'failure') }} + uses: megamegax/slack_action@0.3.1 with: - name: google-play-services.json - json: ${{ secrets.GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON }} - - - name: Playstore upload - uses: r0adkll/upload-google-play@v1.1.3 - with: - serviceAccountJson: google-play-services.json - packageName: com.emarsys.sample - releaseFile: sample-release.aab - track: alpha + webhook_url: '${{env.SLACK_WEBHOOK}}' + channel: '${{env.SLACK_CHANNEL}}' + message: 'On push workflow failed! :man-gesturing-no: :blobcatfearful:' + user_name: '${{env.SLACK_USERNAME}}' + job_status: 'failure' + user_icon: '${{env.SLACK_ICON}}' + actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" }]' - SlackNotification: - name: Send slack notification - runs-on: ubuntu-latest - needs: [ ReleaseSample ] - steps: - - name: Slack Notification - uses: megamegax/slack_action@0.2.3 + - name: Report on Slack (Success) + if: ${{ !contains(needs.*.result, 'cancelled') && !contains(needs.*.result, 'failure') }} + uses: megamegax/slack_action@0.3.1 with: + webhook_url: '${{env.SLACK_WEBHOOK}}' channel: '${{env.SLACK_CHANNEL}}' - message: 'Last push build successful! :man-gesturing-ok: :bananadance:' + message: 'On push workflow successful! :man-gesturing-ok: :success-kid:' user_name: '${{env.SLACK_USERNAME}}' job_status: 'success' user_icon: '${{env.SLACK_ICON}}' actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" },{ "type": "button", "text": "Install page", "url": "http://ems-mobileteam-artifacts.s3-website-eu-west-1.amazonaws.com/index-ems.html" }]' - - SlackNotificationOnError: - name: Send slack on error - runs-on: ubuntu-latest - needs: [ ReleaseSample ] - if: ${{ failure() }} - steps: - - uses: actions/checkout@v3 - with: - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - - name: Slack Notification - uses: megamegax/slack_action@0.2.3 + - name: Trigger automerge + if: ${{ !contains(needs.*.result, 'cancelled') && !contains(needs.*.result, 'failure') && github.event.pull_request != null && github.actor == 'dependabot[bot]' && github.event.pull_request.merged == false}} + uses: peter-evans/repository-dispatch@v3 with: - channel: '${{env.SLACK_CHANNEL}}' - message: 'Last push build failed! :man-gesturing-no: :blobcatfearful:' - user_name: '${{env.SLACK_USERNAME}}' - job_status: 'failure' - user_icon: '${{env.SLACK_ICON}}' - actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" }]' + token: ${{ secrets.AUTO_MERGE_TOKEN }} + event-type: checks-complete + client-payload: '{ "prNumber": "${{ github.event.pull_request.number }}"}' \ No newline at end of file diff --git a/.github/workflows/on_push_workflow_new.yml b/.github/workflows/release_sample_app_workflow.yml similarity index 54% rename from .github/workflows/on_push_workflow_new.yml rename to .github/workflows/release_sample_app_workflow.yml index 631e2c4b..abc14691 100644 --- a/.github/workflows/on_push_workflow_new.yml +++ b/.github/workflows/release_sample_app_workflow.yml @@ -1,12 +1,10 @@ -name: New on commit workflow +name: Release Sample on: - pull_request: - types: [ opened, reopened, synchronize ] - push: - branches-ignore: - - 'dependabot/**' workflow_dispatch: + workflows: [ "On Push" ] + types: + - completed env: USE_LOCAL_DEPENDENCY: ${{ vars.USE_LOCAL_DEPENDENCY }} @@ -32,29 +30,14 @@ env: SLACK_WEBHOOK: ${{ secrets.SLACK_MOBILE_TEAM_CI_CHANNEL_WEBHOOK }} jobs: - Test: - permissions: - contents: read - id-token: write + ReleaseSampleApp: + name: Release Sample App runs-on: ubuntu-latest - name: Test & Lint - strategy: - matrix: - include: - - task: core - - task: mobile-engage - - task: predict - - task: emarsys-firebase - - task: emarsys-huawei - - task: emarsys-sdk - - task: lint steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v3 with: - ref: dev submodules: true fetch-depth: 0 # 0 indicates all history - - name: set up JDK 1.17 uses: actions/setup-java@v4 with: @@ -64,60 +47,28 @@ jobs: - name: Setup Gradle uses: gradle/actions/setup-gradle@v3 with: - gradle-version: 8.6 - cache-overwrite-existing: true - gradle-home-cache-cleanup: true + cache-disabled: true - name: Prepare CI run: make prepare-ci - - name: Authenticate to Google Cloud - uses: google-github-actions/auth@v2.1.2 - with: - workload_identity_provider: 'projects/395478287999/locations/global/workloadIdentityPools/github-actions/providers/github-actions ' - service_account: 'firebase-test-lab-service-acco@ems-mobile-sdk.iam.gserviceaccount.com' - create_credentials_file: true - - - name: Set up Cloud SDK - uses: google-github-actions/setup-gcloud@v2 - - - run: gcloud info - - run: gcloud config set project ${{ env.FIREBASE_PROJECT_ID }} - - - name: Build - run: make build-test - - - name: Test core - if: matrix.task == 'core' - run: make test-android-firebase-emulator MODULE_NAME=core - - - name: Test mobile-engage - if: matrix.task == 'mobile-engage' - run: make test-android-firebase-emulator MODULE_NAME=mobile-engage + - name: Prepare keystore file + run: make base64-secret-to-file SECRET=ANDROID_RELEASE_STORE_FILE_BASE64 FILE=sample/mobile-team-android.jks - - name: Test predict - if: matrix.task == 'predict' - run: make test-android-firebase-emulator MODULE_NAME=predict + - name: Create sample app release bundle + run: ./gradlew :sample:bundleRelease - - name: Test emarsys-firebase - if: matrix.task == 'emarsys-firebase' - run: make test-android-firebase-emulator MODULE_NAME=emarsys-firebase - - - name: Test emarsys-huawei - if: matrix.module == 'emarsys-huawei' - run: make task-android-firebase-emulator MODULE_NAME=emarsys-huawei - - - name: Test emarsys-sdk - if: matrix.task == 'emarsys-sdk' - run: make test-android-firebase-emulator MODULE_NAME=emarsys-sdk - - - name: Run lint - if: matrix.task == 'lint' - run: make lint + - name: PlayStore upload + uses: r0adkll/upload-google-play@v1.1.3 + with: + serviceAccountJson: ./sample/google-services.json + packageName: com.emarsys.sample + releaseFile: sample/build/outputs/bundle/release/sample-release.aab + track: alpha Report: if: always() - needs: [ Test ] + needs: [ ReleaseSampleApp ] runs-on: ubuntu-latest steps: - name: Report on Slack (Error) @@ -126,7 +77,7 @@ jobs: with: webhook_url: '${{env.SLACK_WEBHOOK}}' channel: '${{env.SLACK_CHANNEL}}' - message: 'On push workflow failed! :man-gesturing-no: :blobcatfearful:' + message: 'Release sample app failed! :man-gesturing-no: :blobcatfearful:' user_name: '${{env.SLACK_USERNAME}}' job_status: 'failure' user_icon: '${{env.SLACK_ICON}}' @@ -138,16 +89,8 @@ jobs: with: webhook_url: '${{env.SLACK_WEBHOOK}}' channel: '${{env.SLACK_CHANNEL}}' - message: 'On push workflow successful! :man-gesturing-ok: :success-kid:' + message: 'Sample app released! :man-gesturing-ok: :success-kid:' user_name: '${{env.SLACK_USERNAME}}' job_status: 'success' user_icon: '${{env.SLACK_ICON}}' actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" },{ "type": "button", "text": "Install page", "url": "http://ems-mobileteam-artifacts.s3-website-eu-west-1.amazonaws.com/index-ems.html" }]' - - - name: Trigger automerge - if: ${{ !contains(needs.*.result, 'cancelled') && !contains(needs.*.result, 'failure') && github.event.pull_request != null && github.actor == 'dependabot[bot]' && github.event.pull_request.merged == false}} - uses: peter-evans/repository-dispatch@v3 - with: - token: ${{ secrets.AUTO_MERGE_TOKEN }} - event-type: checks-complete - client-payload: '{ "prNumber": "${{ github.event.pull_request.number }}"}' \ No newline at end of file diff --git a/.gitignore b/.gitignore index ea1f6a9f..dff80d42 100644 --- a/.gitignore +++ b/.gitignore @@ -10,4 +10,7 @@ sample/agconnect-services.json .fleet .env firebase_service_account.json -workflow.secrets \ No newline at end of file +workflow.secrets +mobile-team-android.jks.asc +sample/mobile-team-android.jks +/mobile-team-android.jks diff --git a/Makefile b/Makefile index 1ed6aa15..8fc39f43 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: check-env help build-test create-testing-apks lint prepare-ci run-github-workflow-locally test-android-firebase test-android-firebase-emulator +.PHONY: base64-secret-to-file build-test check-env help create-sample-release-bundle create-testing-apks lint prepare-ci run-github-workflow-locally test-android-firebase test-android-firebase-emulator .DEFAULT_GOAL := help SHELL := /bin/bash @@ -26,12 +26,18 @@ help: check-env ## Show this help @fgrep -h "##" $(MAKEFILE_LIST) | grep ":" | fgrep -v fgrep | sed -e 's/\\$$//' | sed -e 's/\(.*\):.*##[ \t]*/ \1 ## /' | sort | column -t -s '##' @echo +base64-secret-to-file: check-env ## decode base64 secret to path + @./gradlew base64EnvToFile -PpropertyName=$(SECRET) -Pfile=$(FILE) + build-test: check-env ## builds android tests excluding and lint @./gradlew clean assembleAndroidTest -x lint create-testing-apks: check-env ## create apks for testing @./gradlew assembleAndroidTest -x :sample:test +create-sample-release-bundle: check-env ## create sample app release bundle + @./gradlew :sample:bundleRelease + lint: check-env ## run lint @./gradlew lint From 1adce9e5c642a3ec306a8d87d74a7b72e533f2bb Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Wed, 28 Feb 2024 13:50:40 +0100 Subject: [PATCH 41/63] chore(pipeline): remove gcloud project setup SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: megamegax --- .github/workflows/on_push_workflow.yml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.github/workflows/on_push_workflow.yml b/.github/workflows/on_push_workflow.yml index fdedbd08..16e55f4e 100644 --- a/.github/workflows/on_push_workflow.yml +++ b/.github/workflows/on_push_workflow.yml @@ -55,7 +55,7 @@ jobs: submodules: true fetch-depth: 0 # 0 indicates all history - - name: set up JDK 1.17 + - name: Set up JDK 1.17 uses: actions/setup-java@v4 with: distribution: 'temurin' @@ -81,9 +81,6 @@ jobs: - name: Set up Cloud SDK uses: google-github-actions/setup-gcloud@v2 - - run: gcloud info - - run: gcloud config set project ${{ env.FIREBASE_PROJECT_ID }} - - name: Build run: make build-test From 2a5f049f4744485ce90015663354f19a15f29d0b Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Wed, 28 Feb 2024 15:11:29 +0100 Subject: [PATCH 42/63] chore(pipeline): remove extra whitespace SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: megamegax --- .github/workflows/on_push_workflow.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/on_push_workflow.yml b/.github/workflows/on_push_workflow.yml index 16e55f4e..fbaa14d9 100644 --- a/.github/workflows/on_push_workflow.yml +++ b/.github/workflows/on_push_workflow.yml @@ -74,7 +74,7 @@ jobs: - name: Authenticate to Google Cloud uses: google-github-actions/auth@v2.1.2 with: - workload_identity_provider: 'projects/395478287999/locations/global/workloadIdentityPools/github-actions/providers/github-actions ' + workload_identity_provider: 'projects/395478287999/locations/global/workloadIdentityPools/github-actions/providers/github-actions' service_account: 'firebase-test-lab-service-acco@ems-mobile-sdk.iam.gserviceaccount.com' create_credentials_file: true From 03603a9ebb8d035338fa3f489399dbf4c10d9f6f Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Wed, 28 Feb 2024 15:29:38 +0100 Subject: [PATCH 43/63] chore(pipeline): modified pool name SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: Andras Sarro Co-authored-by: matusekma <36794575+matusekma@users.noreply.github.com> --- .github/workflows/on_push_workflow.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/on_push_workflow.yml b/.github/workflows/on_push_workflow.yml index fbaa14d9..02a6ead0 100644 --- a/.github/workflows/on_push_workflow.yml +++ b/.github/workflows/on_push_workflow.yml @@ -74,7 +74,7 @@ jobs: - name: Authenticate to Google Cloud uses: google-github-actions/auth@v2.1.2 with: - workload_identity_provider: 'projects/395478287999/locations/global/workloadIdentityPools/github-actions/providers/github-actions' + workload_identity_provider: 'projects/395478287999/locations/global/workloadIdentityPools/github-actions' service_account: 'firebase-test-lab-service-acco@ems-mobile-sdk.iam.gserviceaccount.com' create_credentials_file: true From 0021f459e588548d343adbee24da71b30b73dccd Mon Sep 17 00:00:00 2001 From: Marton Matusek Date: Wed, 28 Feb 2024 16:04:27 +0100 Subject: [PATCH 44/63] Revert "chore(pipeline): modified pool name" This reverts commit 03603a9ebb8d035338fa3f489399dbf4c10d9f6f. --- .github/workflows/on_push_workflow.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/on_push_workflow.yml b/.github/workflows/on_push_workflow.yml index 02a6ead0..fbaa14d9 100644 --- a/.github/workflows/on_push_workflow.yml +++ b/.github/workflows/on_push_workflow.yml @@ -74,7 +74,7 @@ jobs: - name: Authenticate to Google Cloud uses: google-github-actions/auth@v2.1.2 with: - workload_identity_provider: 'projects/395478287999/locations/global/workloadIdentityPools/github-actions' + workload_identity_provider: 'projects/395478287999/locations/global/workloadIdentityPools/github-actions/providers/github-actions' service_account: 'firebase-test-lab-service-acco@ems-mobile-sdk.iam.gserviceaccount.com' create_credentials_file: true From 50c379fdfad42edf7acd4ccd1961cf37775dddec Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Wed, 28 Feb 2024 16:30:31 +0100 Subject: [PATCH 45/63] chore(pipeline): trigger release sample for the first time SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: Andras Sarro Co-authored-by: matusekma <36794575+matusekma@users.noreply.github.com> --- .github/workflows/release_sample_app_workflow.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/release_sample_app_workflow.yml b/.github/workflows/release_sample_app_workflow.yml index abc14691..01a97038 100644 --- a/.github/workflows/release_sample_app_workflow.yml +++ b/.github/workflows/release_sample_app_workflow.yml @@ -5,6 +5,8 @@ on: workflows: [ "On Push" ] types: - completed + push: + branches: [ dev ] env: USE_LOCAL_DEPENDENCY: ${{ vars.USE_LOCAL_DEPENDENCY }} From 6f40340144a2a7cb51d7d2fc00f0ae581aed01ac Mon Sep 17 00:00:00 2001 From: LasOri Date: Thu, 29 Feb 2024 14:29:37 +0100 Subject: [PATCH 46/63] chore(pipeline): release workflow SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> Co-authored-by: megamegax Co-authored-by: Andras Sarro --- .github/workflows/release_sample_app_workflow.yml | 2 -- build.gradle.kts | 7 ++++--- sample/build.gradle.kts | 7 +------ 3 files changed, 5 insertions(+), 11 deletions(-) diff --git a/.github/workflows/release_sample_app_workflow.yml b/.github/workflows/release_sample_app_workflow.yml index 01a97038..abc14691 100644 --- a/.github/workflows/release_sample_app_workflow.yml +++ b/.github/workflows/release_sample_app_workflow.yml @@ -5,8 +5,6 @@ on: workflows: [ "On Push" ] types: - completed - push: - branches: [ dev ] env: USE_LOCAL_DEPENDENCY: ${{ vars.USE_LOCAL_DEPENDENCY }} diff --git a/build.gradle.kts b/build.gradle.kts index 87d742bd..d494d4bf 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -60,10 +60,11 @@ tasks { doLast { val base64String = env.fetch(propertyName) val decoder = Base64.getDecoder() - val decodedString = String(decoder.decode(base64String)) + val decodedBytes = decoder.decode(base64String) - val outputFile = file(file) - outputFile.writeText(decodedString) + file(file).apply { + writeBytes(decodedBytes) + } } } } \ No newline at end of file diff --git a/sample/build.gradle.kts b/sample/build.gradle.kts index 586dc39f..ef05d925 100644 --- a/sample/build.gradle.kts +++ b/sample/build.gradle.kts @@ -76,10 +76,7 @@ android { (System.getenv("ANDROID_RELEASE_KEY_PASSWORD") ?: "") ) storeFile = file( - env.fetch( - "ANDROID_RELEASE_STORE_FILE_BASE64", - (System.getenv("ANDROID_RELEASE_STORE_FILE_BASE64") ?: "") - ) + "./mobile-team-android.jks" ) } } @@ -133,13 +130,11 @@ dependencies { implementation(libs.kotlin.reflect) implementation(libs.kotlin.stdlib) implementation(libs.androidx.material) - // implementation("androidx.cardview:cardview:1.0.0") implementation(libs.play.services.auth) implementation(libs.androidx.appcompat) implementation(libs.io.coil) implementation(libs.androidx.core.ktx) - // implementation("com.google.android.material:material:1.11.0") implementation(libs.androidx.compose.ui) implementation(libs.androidx.compose.material) implementation(libs.androidx.compose.ui.tooling.preview) From 50ae24dc3c09362a255ea20c7edd1e18f8d9e34b Mon Sep 17 00:00:00 2001 From: LasOri Date: Thu, 29 Feb 2024 14:29:37 +0100 Subject: [PATCH 47/63] chore(pipeline): release workflow SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> Co-authored-by: megamegax Co-authored-by: Andras Sarro --- .github/workflows/release_sample_app_workflow.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release_sample_app_workflow.yml b/.github/workflows/release_sample_app_workflow.yml index abc14691..bc794bd1 100644 --- a/.github/workflows/release_sample_app_workflow.yml +++ b/.github/workflows/release_sample_app_workflow.yml @@ -1,7 +1,7 @@ name: Release Sample on: - workflow_dispatch: + workflow_run: workflows: [ "On Push" ] types: - completed From 96779c12344a114b37f58f349b31aaf4b3afea7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyady=20Mih=C3=A1ly?= Date: Thu, 29 Feb 2024 17:09:18 +0100 Subject: [PATCH 48/63] chore(pipeline): rework release pipeline SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .gitignore | 3 +- Makefile | 12 +- build.gradle.kts | 37 ++++++- buildSrc/build.gradle.kts | 4 + common/build.gradle.kts | 2 + core-api/build.gradle.kts | 2 + core/build.gradle.kts | 9 +- emarsys-firebase/build.gradle.kts | 1 + emarsys-huawei/build.gradle.kts | 1 + emarsys-sdk/build.gradle.kts | 1 + emarsys/build.gradle.kts | 1 + gradle/libs.versions.toml | 2 + gradle/release.gradle | 171 +++++++++++------------------ mobile-engage-api/build.gradle.kts | 1 + mobile-engage/build.gradle.kts | 1 + predict-api/build.gradle.kts | 1 + predict/build.gradle.kts | 1 + sample/build.gradle.kts | 11 +- 18 files changed, 139 insertions(+), 122 deletions(-) diff --git a/.gitignore b/.gitignore index dff80d42..a649b16b 100644 --- a/.gitignore +++ b/.gitignore @@ -13,4 +13,5 @@ firebase_service_account.json workflow.secrets mobile-team-android.jks.asc sample/mobile-team-android.jks -/mobile-team-android.jks +mobile-team-android.jks +secring.asc.gpg \ No newline at end of file diff --git a/Makefile b/Makefile index 8fc39f43..1c4298cb 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: base64-secret-to-file build-test check-env help create-sample-release-bundle create-testing-apks lint prepare-ci run-github-workflow-locally test-android-firebase test-android-firebase-emulator +.PHONY: base64-secret-to-file build-test check-env help create-sample-release-bundle create-testing-apks lint prepare-ci run-github-workflow-locally test-android-firebase test-android-firebase-emulator release-to-sonatype .DEFAULT_GOAL := help SHELL := /bin/bash @@ -45,6 +45,11 @@ prepare-ci: check-env ## setup prerequisites for pipeline @echo $ANDROID_HOME > local.properties @./gradlew base64EnvToFile -PpropertyName=GOOGLE_SERVICES_JSON_BASE64 -Pfile=./sample/google-services.json +prepare-release: check-env ## setup prerequisites for release + @./gradlew base64EnvToFile -PpropertyName=SONATYPE_SIGNING_SECRET_KEY_RING_FILE_BASE64 -Pfile=./secring.asc.gpg + +prepare-sample-release-key: check-env + test-android-firebase-emulator: check-env ## run Android Instrumented tests on emulators on Firebase Test Lab @gcloud firebase test android run \ --type instrumentation \ @@ -68,3 +73,8 @@ test-android-firebase: check-env ## run Android Instrumented tests on real devic run-github-workflow-locally: check-env ## needs act to be installed: `brew install act` and docker running. Pass in workflow path to run @act --secret-file ./workflow.secrets -W $(WORKFLOW_PATH) --container-architecture linux/amd64 + +release: check-env prepare-release prepare-sample-release-key ## release to sonatype + @./gradlew assembleRelease && ./gradlew publishToSonatype +release-locally: check-env prepare-release prepare-sample-release-key ## release to mavenLocal + @./gradlew assembleRelease && ./gradlew publishToMavenLocal \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index d494d4bf..c87dec58 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -15,10 +15,19 @@ plugins { alias(libs.plugins.dotenv) alias(libs.plugins.ben.manes.versions) alias(libs.plugins.android.junit5) apply false + alias(libs.plugins.nexus.publish) + id("maven-publish") + id("signing") } versionData() +allprojects { + val sdkVersion: GitVersion by rootProject.extra + group = "com.emarsys" + version = sdkVersion.versionName +} + fun versionData() { val git = Grgit.open( mapOf("currentDir" to project.rootDir) @@ -44,10 +53,17 @@ fun versionData() { versionCodeTime = 0 ) } - val version by extra(v) + val sdkVersion by extra(v) + + ext["signing.keyId"] = + env.fetch("SONATYPE_SIGNING_KEY_ID") ?: System.getenv("SONATYPE_SIGNING_KEY_ID") + ext["signing.password"] = + env.fetch("SONATYPE_SIGNING_PASSWORD") ?: System.getenv("SONATYPE_SIGNING_PASSWORD") + ext["signing.secretKeyRingFile"] = "./secring.asc.gpg" - println("versionName: ${version.versionName}") - println("versionCode: ${version.versionCode}") + + println("versionName: ${sdkVersion.versionName}") + println("versionCode: ${sdkVersion.versionCode}") } tasks { @@ -67,4 +83,17 @@ tasks { } } } -} \ No newline at end of file +} + + +nexusPublishing { + packageGroup = "com.emarsys" + repositories { + sonatype { + stagingProfileId = env.fetch("SONATYPE_STAGING_PROFILE_ID") + ?: System.getenv("SONATYPE_STAGING_PROFILE_ID") + username = env.fetch("OSSRH_USERNAME") ?: System.getenv("OSSRH_USERNAME") + password = env.fetch("OSSRH_PASSWORD") ?: System.getenv("OSSRH_PASSWORD") + } + } +} diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index ddb09cf0..3c4319bd 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -1,5 +1,9 @@ plugins { id("org.jetbrains.kotlin.jvm") version "1.9.0" + id("io.github.gradle-nexus.publish-plugin") version "1.3.0" + id("co.uzzu.dotenv.gradle") version "4.0.0" + id("maven-publish") + signing } repositories { diff --git a/common/build.gradle.kts b/common/build.gradle.kts index ea6f251b..fc111d5e 100644 --- a/common/build.gradle.kts +++ b/common/build.gradle.kts @@ -4,6 +4,8 @@ plugins { alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) } +apply(from = "../gradle/release.gradle") + dependencies { implementation(project(":core-api")) diff --git a/core-api/build.gradle.kts b/core-api/build.gradle.kts index 2c145d3b..ac452475 100644 --- a/core-api/build.gradle.kts +++ b/core-api/build.gradle.kts @@ -4,6 +4,8 @@ plugins { alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) } +apply(from = "../gradle/release.gradle") + dependencies { api(libs.androidx.annotation) api(libs.androidx.appcompat) diff --git a/core/build.gradle.kts b/core/build.gradle.kts index a8d73efd..e7d78556 100644 --- a/core/build.gradle.kts +++ b/core/build.gradle.kts @@ -4,6 +4,9 @@ plugins { alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) } +apply(from = "../gradle/release.gradle") + +val sdkVersion: GitVersion by rootProject.extra dependencies { implementation(project(":core-api")) @@ -26,9 +29,9 @@ android { testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - val version: GitVersion by rootProject.extra - buildConfigField("int", "VERSION_CODE", "${version.versionCode}") - buildConfigField("String", "VERSION_NAME", "\"${version.versionName}\"") + val sdkVersion: GitVersion by rootProject.extra + buildConfigField("int", "VERSION_CODE", "${sdkVersion.versionCode}") + buildConfigField("String", "VERSION_NAME", "\"${sdkVersion.versionName}\"") } buildFeatures { diff --git a/emarsys-firebase/build.gradle.kts b/emarsys-firebase/build.gradle.kts index 6fe6968b..3d617710 100644 --- a/emarsys-firebase/build.gradle.kts +++ b/emarsys-firebase/build.gradle.kts @@ -4,6 +4,7 @@ plugins { alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) } +apply(from = "../gradle/release.gradle") dependencies { implementation(project(":core-api")) diff --git a/emarsys-huawei/build.gradle.kts b/emarsys-huawei/build.gradle.kts index acbe2feb..29c72344 100644 --- a/emarsys-huawei/build.gradle.kts +++ b/emarsys-huawei/build.gradle.kts @@ -5,6 +5,7 @@ plugins { alias(libs.plugins.kapt) // alias(libs.plugins.huawei.agconnect) } +apply(from = "../gradle/release.gradle") dependencies { implementation(project(":core-api")) diff --git a/emarsys-sdk/build.gradle.kts b/emarsys-sdk/build.gradle.kts index 607a8cbc..f79b3426 100644 --- a/emarsys-sdk/build.gradle.kts +++ b/emarsys-sdk/build.gradle.kts @@ -4,6 +4,7 @@ plugins { alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) } +apply(from = "../gradle/release.gradle") dependencies { api(project(":core-api")) diff --git a/emarsys/build.gradle.kts b/emarsys/build.gradle.kts index 0ff6eec1..93bb3421 100644 --- a/emarsys/build.gradle.kts +++ b/emarsys/build.gradle.kts @@ -4,6 +4,7 @@ plugins { alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) } +apply(from = "../gradle/release.gradle") dependencies { api(project(":core-api")) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 43e6c50a..3ea4190b 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -55,6 +55,7 @@ dotEnv = "4.0.0" android-tools-desugar = "2.0.4" benManesVersions = "0.51.0" android-junit5 = "1.10.0.0" +nexus-publish = "1.3.0" [libraries] androidx-test-core = { module = "androidx.test:core", version.ref = "androidx-test-core" } @@ -130,3 +131,4 @@ grgit = { id = "org.ajoberstar.grgit", version.ref = "grGit" } dotenv = { id = "co.uzzu.dotenv.gradle", version.ref = "dotEnv" } ben-manes-versions = { id = "com.github.ben-manes.versions", version.ref = "benManesVersions" } android-junit5 = { id = "de.mannodermaus.android-junit5", version.ref = "android-junit5" } +nexus-publish = { id = "io.github.gradle-nexus.publish-plugin", version.ref = "nexus-publish" } diff --git a/gradle/release.gradle b/gradle/release.gradle index e43dc263..a229b8ab 100644 --- a/gradle/release.gradle +++ b/gradle/release.gradle @@ -1,104 +1,72 @@ -ext.modules = [':core-api', ':core', ':common', ':mobile-engage-api', ':mobile-engage', ':predict-api', ':predict', ':emarsys', ':emarsys-firebase', ':emarsys-huawei', ':emarsys-sdk'] - -apply plugin: 'maven-publish' -apply plugin: 'signing' -apply plugin: "io.github.gradle-nexus.publish-plugin" - - -def ossrhUsername = null -def ossrhPassword = null -def sonatypeStagingProfileId = null - -def localConfigPropertiesFile = rootProject.file('localConfig.properties') -def localConfigProperties = new Properties() -if (localConfigPropertiesFile.exists()) { - localConfigProperties.load(new FileInputStream(localConfigPropertiesFile)) - ossrhUsername = localConfigProperties.getProperty("ossrhUsername") - ossrhPassword = localConfigProperties.getProperty("ossrhPassword") - sonatypeStagingProfileId = localConfigProperties.getProperty("sonatypeStagingProfileId") - - ext["signing.keyId"] = localConfigProperties.getProperty("signingKeyId") - ext["signing.password"] = localConfigProperties.getProperty("signingPassword") - ext["signing.secretKeyRingFile"] = localConfigProperties.getProperty("signingSecretKeyRingFile") -} else { - ossrhUsername = System.env.OSSRH_USERNAME - ossrhPassword = System.env.OSSRH_PASSWORD - sonatypeStagingProfileId = System.env.SONATYPE_STAGING_PROFILE_ID - - ext["signing.keyId"] = System.env.SIGNING_KEYID - ext["signing.password"] = System.env.SIGNING_PASSWORD - ext["signing.secretKeyRingFile"] = System.env.SIGNING_SECRET_KEY_RING_FILE +task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + archiveClassifier = 'sources' } -modules.each { - project(it) { - task sourcesJar(type: Jar) { - from android.sourceSets.main.java.srcDirs - archiveClassifier = 'sources' - } - - task javadoc(type: Javadoc) { - source = android.sourceSets.main.java.srcDirs - failOnError false - } +task javadoc(type: Javadoc) { + source = android.sourceSets.main.java.srcDirs + failOnError false +} - task javadocJar(type: Jar, dependsOn: javadoc) { - archiveClassifier = 'javadoc' - from javadoc.destinationDir - } +task javadocJar(type: Jar, dependsOn: javadoc) { + archiveClassifier = 'javadoc' + if (javadoc.destinationDir != null) { + from javadoc.destinationDir + } else { + println("Javadoc not found") + } +} - afterEvaluate { - publishing { - publications { - "${project.name}"(MavenPublication) { - groupId = group - artifactId = project.name - artifact sourcesJar - artifact javadocJar - artifact("$buildDir/outputs/aar/${project.name}-release.aar") - pom { - name = project.name - description = "${project.name} module of the EmarsysSDK" - url = 'https://github.com/emartech/android-emarsys-sdk' - licenses { - license { - name = 'Mozilla Public License 2.0' - url = 'https://github.com/emartech/android-emarsys-sdk/blob/master/LICENSE' - } - } - organization { - name = 'Emarsys' - url = 'https://emarsys.com' - } - developers { - developer { - organization = 'Emarsys' - organizationUrl = 'https://emarsys.com' - } - } - scm { - connection = 'scm:git:https://github.com/emartech/android-emarsys-sdk.git' - developerConnection = 'scm:git:https://github.com/emartech/android-emarsys-sdk.git' - url = 'https://github.com/emartech/android-emarsys-sdk' +afterEvaluate { + publishing { + publications { + "${project.name}"(MavenPublication) { + groupId = group + artifactId = project.name + artifact sourcesJar + artifact javadocJar + artifact("$buildDir/outputs/aar/${project.name}-release.aar") + pom { + name = project.name + description = "${project.name} module of the EmarsysSDK" + url = 'https://github.com/emartech/android-emarsys-sdk' + licenses { + license { + name = 'Mozilla Public License 2.0' + url = 'https://github.com/emartech/android-emarsys-sdk/blob/master/LICENSE' + } + } + organization { + name = 'Emarsys' + url = 'https://emarsys.com' + } + developers { + developer { + organization = 'Emarsys' + organizationUrl = 'https://emarsys.com' + } + } + scm { + connection = 'scm:git:https://github.com/emartech/android-emarsys-sdk.git' + developerConnection = 'scm:git:https://github.com/emartech/android-emarsys-sdk.git' + url = 'https://github.com/emartech/android-emarsys-sdk' + } + withXml { + def dependenciesNode = asNode().appendNode("dependencies") + configurations.getByName("api") { + dependencies.forEach { + def dependencyNode = dependenciesNode.appendNode("dependency") + dependencyNode.appendNode("groupId", it.group) + dependencyNode.appendNode("artifactId", it.name) + dependencyNode.appendNode("version", it.version) } - withXml { - def dependenciesNode = asNode().appendNode("dependencies") - configurations.getByName("api") { - dependencies.forEach { - def dependencyNode = dependenciesNode.appendNode("dependency") - dependencyNode.appendNode("groupId", it.group) - dependencyNode.appendNode("artifactId", it.name) - dependencyNode.appendNode("version", it.version) - } - } - configurations.getByName("implementation") { - dependencies.forEach { - def dependencyNode = dependenciesNode.appendNode("dependency") - dependencyNode.appendNode("groupId", it.group) - dependencyNode.appendNode("artifactId", it.name) - dependencyNode.appendNode("version", it.version) - } - } + } + configurations.getByName("implementation") { + dependencies.forEach { + def dependencyNode = dependenciesNode.appendNode("dependency") + dependencyNode.appendNode("groupId", it.group) + dependencyNode.appendNode("artifactId", it.name) + dependencyNode.appendNode("version", it.version) } } } @@ -108,17 +76,6 @@ modules.each { } } -nexusPublishing { - packageGroup = "com.emarsys" - repositories { - sonatype { - stagingProfileId = sonatypeStagingProfileId - username = ossrhUsername - password = ossrhPassword - } - } -} - signing { sign publishing.publications } \ No newline at end of file diff --git a/mobile-engage-api/build.gradle.kts b/mobile-engage-api/build.gradle.kts index 5438e861..be011a97 100644 --- a/mobile-engage-api/build.gradle.kts +++ b/mobile-engage-api/build.gradle.kts @@ -4,6 +4,7 @@ plugins { alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) } +apply(from = "../gradle/release.gradle") dependencies { implementation(project(":core-api")) diff --git a/mobile-engage/build.gradle.kts b/mobile-engage/build.gradle.kts index 7602e257..9bbc5dc3 100644 --- a/mobile-engage/build.gradle.kts +++ b/mobile-engage/build.gradle.kts @@ -5,6 +5,7 @@ plugins { alias(libs.plugins.kotlin.parcelize) alias(libs.plugins.kapt) } +apply(from = "../gradle/release.gradle") dependencies { implementation(project(":common")) diff --git a/predict-api/build.gradle.kts b/predict-api/build.gradle.kts index d8b5ebe3..1776b6ae 100644 --- a/predict-api/build.gradle.kts +++ b/predict-api/build.gradle.kts @@ -4,6 +4,7 @@ plugins { alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) } +apply(from = "../gradle/release.gradle") dependencies { implementation(project(":core")) diff --git a/predict/build.gradle.kts b/predict/build.gradle.kts index 457ed8fa..13c5e116 100644 --- a/predict/build.gradle.kts +++ b/predict/build.gradle.kts @@ -4,6 +4,7 @@ plugins { alias(libs.plugins.kotlin.allopen) alias(libs.plugins.kapt) } +apply(from = "../gradle/release.gradle") dependencies { implementation(project(":core")) diff --git a/sample/build.gradle.kts b/sample/build.gradle.kts index ef05d925..2cde2c0d 100644 --- a/sample/build.gradle.kts +++ b/sample/build.gradle.kts @@ -7,9 +7,9 @@ plugins { alias(libs.plugins.google.services) // alias(libs.plugins.huawei.agconnect) } - +val sdkVersion: GitVersion by rootProject.extra group = "com.emarsys.sample" - +version = sdkVersion.versionName android { namespace = "com.emarsys.sample" defaultConfig { @@ -22,12 +22,11 @@ android { targetSdk = libs.versions.android.targetSdk.get().toInt() } multiDexEnabled = true - val version: GitVersion by rootProject.extra - versionCode = version.versionCode - versionName = version.versionName + versionCode = sdkVersion.versionCode + versionName = sdkVersion.versionName testInstrumentationRunner = "com.emarsys.sample.testutils.SampleAppTestRunner" - resValue("string", "sdk_version", version.versionName) + resValue("string", "sdk_version", sdkVersion.versionName) buildConfigField( "String", "GOOGLE_OAUTH_SERVER_CLIENT_ID", From 9c23d5f92109c1f5310516d54a5a2ef5cfdb3e9b Mon Sep 17 00:00:00 2001 From: LasOri Date: Fri, 1 Mar 2024 10:54:01 +0100 Subject: [PATCH 49/63] chore(pipeline): use google-service-account.json SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .github/workflows/on_push_workflow.yml | 1 + .github/workflows/release_sample_app_workflow.yml | 7 ++++--- Makefile | 10 ++++++---- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/.github/workflows/on_push_workflow.yml b/.github/workflows/on_push_workflow.yml index fbaa14d9..3c3b1e1a 100644 --- a/.github/workflows/on_push_workflow.yml +++ b/.github/workflows/on_push_workflow.yml @@ -19,6 +19,7 @@ env: FIREBASE_SERVICE_ACCOUNT_JSON: ${{ secrets.FIREBASE_SERVICE_ACCOUNT_JSON }} GOOGLE_OAUTH_SERVER_CLIENT_ID: ${{ secrets.GOOGLE_OAUTH_SERVER_CLIENT_ID }} GOOGLE_SERVICES_JSON_BASE64: ${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }} + GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON_BASE64: ${{ secrets.GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON_BASE64 }} OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} SONATYPE_STAGING_PROFILE_ID: ${{ secrets.SONATYPE_STAGING_PROFILE_ID }} diff --git a/.github/workflows/release_sample_app_workflow.yml b/.github/workflows/release_sample_app_workflow.yml index bc794bd1..e25f2eec 100644 --- a/.github/workflows/release_sample_app_workflow.yml +++ b/.github/workflows/release_sample_app_workflow.yml @@ -17,6 +17,7 @@ env: FIREBASE_SERVICE_ACCOUNT_JSON: ${{ secrets.FIREBASE_SERVICE_ACCOUNT_JSON }} GOOGLE_OAUTH_SERVER_CLIENT_ID: ${{ secrets.GOOGLE_OAUTH_SERVER_CLIENT_ID }} GOOGLE_SERVICES_JSON_BASE64: ${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }} + GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON_BASE64: ${{ secrets.GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON_BASE64 }} OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} SONATYPE_STAGING_PROFILE_ID: ${{ secrets.SONATYPE_STAGING_PROFILE_ID }} @@ -52,8 +53,8 @@ jobs: - name: Prepare CI run: make prepare-ci - - name: Prepare keystore file - run: make base64-secret-to-file SECRET=ANDROID_RELEASE_STORE_FILE_BASE64 FILE=sample/mobile-team-android.jks + - name: Prepare sample release + run: make prepare-sample-release - name: Create sample app release bundle run: ./gradlew :sample:bundleRelease @@ -61,7 +62,7 @@ jobs: - name: PlayStore upload uses: r0adkll/upload-google-play@v1.1.3 with: - serviceAccountJson: ./sample/google-services.json + serviceAccountJson: ./sample/google-play-store-service-account.json packageName: com.emarsys.sample releaseFile: sample/build/outputs/bundle/release/sample-release.aab track: alpha diff --git a/Makefile b/Makefile index 1c4298cb..6db60c82 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: base64-secret-to-file build-test check-env help create-sample-release-bundle create-testing-apks lint prepare-ci run-github-workflow-locally test-android-firebase test-android-firebase-emulator release-to-sonatype +.PHONY: base64-secret-to-file build-test check-env help create-sample-release-bundle create-testing-apks lint prepare-ci run-github-workflow-locally test-android-firebase test-android-firebase-emulator release-to-sonatype prepare-sample-release .DEFAULT_GOAL := help SHELL := /bin/bash @@ -48,7 +48,9 @@ prepare-ci: check-env ## setup prerequisites for pipeline prepare-release: check-env ## setup prerequisites for release @./gradlew base64EnvToFile -PpropertyName=SONATYPE_SIGNING_SECRET_KEY_RING_FILE_BASE64 -Pfile=./secring.asc.gpg -prepare-sample-release-key: check-env +prepare-sample-release: check-env ## prepares .jks file for sample release + @./gradlew base64EnvToFile -PpropertyName=ANDROID_RELEASE_STORE_FILE_BASE64 -Pfile=sample/mobile-team-android.jks \ + @./gradlew base64EnvToFile -PpropertyName=GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON_BASE64 -Pfile=sample/google-play-store-service-account.json test-android-firebase-emulator: check-env ## run Android Instrumented tests on emulators on Firebase Test Lab @gcloud firebase test android run \ @@ -74,7 +76,7 @@ test-android-firebase: check-env ## run Android Instrumented tests on real devic run-github-workflow-locally: check-env ## needs act to be installed: `brew install act` and docker running. Pass in workflow path to run @act --secret-file ./workflow.secrets -W $(WORKFLOW_PATH) --container-architecture linux/amd64 -release: check-env prepare-release prepare-sample-release-key ## release to sonatype +release: check-env prepare-release prepare-sample-release ## release to sonatype @./gradlew assembleRelease && ./gradlew publishToSonatype -release-locally: check-env prepare-release prepare-sample-release-key ## release to mavenLocal +release-locally: check-env prepare-release prepare-sample-release ## release to mavenLocal @./gradlew assembleRelease && ./gradlew publishToMavenLocal \ No newline at end of file From 66e7d338f023fa2aa20604111453c7e15174d48a Mon Sep 17 00:00:00 2001 From: LasOri Date: Fri, 1 Mar 2024 11:03:00 +0100 Subject: [PATCH 50/63] chore(pipeline): update checkout to use dev branch SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .github/workflows/release_sample_app_workflow.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/release_sample_app_workflow.yml b/.github/workflows/release_sample_app_workflow.yml index e25f2eec..405c884a 100644 --- a/.github/workflows/release_sample_app_workflow.yml +++ b/.github/workflows/release_sample_app_workflow.yml @@ -35,10 +35,12 @@ jobs: name: Release Sample App runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: + ref: dev submodules: true fetch-depth: 0 # 0 indicates all history + - name: set up JDK 1.17 uses: actions/setup-java@v4 with: @@ -57,14 +59,14 @@ jobs: run: make prepare-sample-release - name: Create sample app release bundle - run: ./gradlew :sample:bundleRelease + run: make create-sample-release-bundle - name: PlayStore upload uses: r0adkll/upload-google-play@v1.1.3 with: serviceAccountJson: ./sample/google-play-store-service-account.json packageName: com.emarsys.sample - releaseFile: sample/build/outputs/bundle/release/sample-release.aab + releaseFiles: sample/build/outputs/bundle/release/sample-release.aab track: alpha Report: From ae021653c82eb5667047188a82f41b099314faf8 Mon Sep 17 00:00:00 2001 From: LasOri Date: Fri, 1 Mar 2024 11:07:37 +0100 Subject: [PATCH 51/63] chore(pipeline): add workflow_dispatch SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .github/workflows/release_sample_app_workflow.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release_sample_app_workflow.yml b/.github/workflows/release_sample_app_workflow.yml index 405c884a..d678db90 100644 --- a/.github/workflows/release_sample_app_workflow.yml +++ b/.github/workflows/release_sample_app_workflow.yml @@ -5,6 +5,7 @@ on: workflows: [ "On Push" ] types: - completed + workflow_dispatch: env: USE_LOCAL_DEPENDENCY: ${{ vars.USE_LOCAL_DEPENDENCY }} From 2bb5d96b427f2e2c82a5fd2f78e9db0cc5ba0777 Mon Sep 17 00:00:00 2001 From: LasOri Date: Fri, 1 Mar 2024 11:14:57 +0100 Subject: [PATCH 52/63] chore(pipeline): update makefile SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .env.example | 11 ++++++++++- Makefile | 2 +- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/.env.example b/.env.example index 24efaabf..6ef4174c 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,5 @@ USE_LOCAL_DEPENDENCY= +GOOGLE_SERVICES_API_KEY= RELEASE_MODE= ANDROID_RELEASE_STORE_FILE_BASE64= ANDROID_RELEASE_STORE_PASSWORD= @@ -6,11 +7,19 @@ ANDROID_RELEASE_KEY_ALIAS= ANDROID_RELEASE_KEY_PASSWORD= FIREBASE_PROJECT_ID= FIREBASE_SERVICE_ACCOUNT_JSON= +FIREBASE_SERVICE_ACCOUNT_BASE64= GOOGLE_OAUTH_SERVER_CLIENT_ID= GOOGLE_SERVICES_JSON_BASE64= +GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON_BASE64= OSSRH_USERNAME= OSSRH_PASSWORD= SONATYPE_STAGING_PROFILE_ID= SONATYPE_SIGNING_KEY_ID= SONATYPE_SIGNING_PASSWORD= -SONATYPE_SIGNING_SECRET_KEY_RING_FILE_BASE64= \ No newline at end of file +SONATYPE_SIGNING_SECRET_KEY_RING_FILE_BASE64= +DETECT_LATEST_RELEASE_VERSION= +DETECT_PROJECT_USER_GROUPS= +DETECT_PROJECT_VERSION_DISTRIBUTION= +BLACKDUCK_ACCESS_TOKEN= +BLACKDUCK_URL= +AUTO_MERGE_TOKEN= \ No newline at end of file diff --git a/Makefile b/Makefile index 6db60c82..0f88f4db 100644 --- a/Makefile +++ b/Makefile @@ -50,7 +50,7 @@ prepare-release: check-env ## setup prerequisites for release prepare-sample-release: check-env ## prepares .jks file for sample release @./gradlew base64EnvToFile -PpropertyName=ANDROID_RELEASE_STORE_FILE_BASE64 -Pfile=sample/mobile-team-android.jks \ - @./gradlew base64EnvToFile -PpropertyName=GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON_BASE64 -Pfile=sample/google-play-store-service-account.json + && ./gradlew base64EnvToFile -PpropertyName=GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON_BASE64 -Pfile=sample/google-play-store-service-account.json test-android-firebase-emulator: check-env ## run Android Instrumented tests on emulators on Firebase Test Lab @gcloud firebase test android run \ From 0bf4aa606a52e20fe408eef583218b75a36f13a0 Mon Sep 17 00:00:00 2001 From: LasOri Date: Fri, 1 Mar 2024 11:19:51 +0100 Subject: [PATCH 53/63] chore(pipeline): update .env.example SUITEDEV-35237 Co-authored-by: davidSchuppa <32750715+davidSchuppa@users.noreply.github.com> --- .env.example | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/.env.example b/.env.example index 6ef4174c..bdcb86fd 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,4 @@ USE_LOCAL_DEPENDENCY= -GOOGLE_SERVICES_API_KEY= RELEASE_MODE= ANDROID_RELEASE_STORE_FILE_BASE64= ANDROID_RELEASE_STORE_PASSWORD= @@ -7,7 +6,6 @@ ANDROID_RELEASE_KEY_ALIAS= ANDROID_RELEASE_KEY_PASSWORD= FIREBASE_PROJECT_ID= FIREBASE_SERVICE_ACCOUNT_JSON= -FIREBASE_SERVICE_ACCOUNT_BASE64= GOOGLE_OAUTH_SERVER_CLIENT_ID= GOOGLE_SERVICES_JSON_BASE64= GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON_BASE64= @@ -16,10 +14,4 @@ OSSRH_PASSWORD= SONATYPE_STAGING_PROFILE_ID= SONATYPE_SIGNING_KEY_ID= SONATYPE_SIGNING_PASSWORD= -SONATYPE_SIGNING_SECRET_KEY_RING_FILE_BASE64= -DETECT_LATEST_RELEASE_VERSION= -DETECT_PROJECT_USER_GROUPS= -DETECT_PROJECT_VERSION_DISTRIBUTION= -BLACKDUCK_ACCESS_TOKEN= -BLACKDUCK_URL= -AUTO_MERGE_TOKEN= \ No newline at end of file +SONATYPE_SIGNING_SECRET_KEY_RING_FILE_BASE64= \ No newline at end of file From 3c67c418039f62fd080e24705efdc6e1c0758b9a Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Fri, 1 Mar 2024 11:32:39 +0100 Subject: [PATCH 54/63] feat(sample): set isDebuggable to false for release build SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> --- sample/build.gradle.kts | 1 + 1 file changed, 1 insertion(+) diff --git a/sample/build.gradle.kts b/sample/build.gradle.kts index 2cde2c0d..cece039d 100644 --- a/sample/build.gradle.kts +++ b/sample/build.gradle.kts @@ -83,6 +83,7 @@ android { getByName("release") { signingConfig = signingConfigs.getByName("release") isMinifyEnabled = false + isDebuggable = false proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro") } } From 6a0c1b9b6390c84c83fbe7c6dd0d79ad16a8c1af Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Fri, 1 Mar 2024 13:17:43 +0100 Subject: [PATCH 55/63] chore(pipeline): set release mode to true SUITEDEV-35237 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> --- .github/workflows/release_sample_app_workflow.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release_sample_app_workflow.yml b/.github/workflows/release_sample_app_workflow.yml index d678db90..e9d8581f 100644 --- a/.github/workflows/release_sample_app_workflow.yml +++ b/.github/workflows/release_sample_app_workflow.yml @@ -9,7 +9,7 @@ on: env: USE_LOCAL_DEPENDENCY: ${{ vars.USE_LOCAL_DEPENDENCY }} - RELEASE_MODE: ${{ vars.RELEASE_MODE }} + RELEASE_MODE: true ANDROID_RELEASE_STORE_FILE_BASE64: ${{ secrets.ANDROID_RELEASE_STORE_FILE_BASE64 }} ANDROID_RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_RELEASE_STORE_PASSWORD }} ANDROID_RELEASE_KEY_ALIAS: ${{ secrets.ANDROID_RELEASE_KEY_ALIAS }} From a7162ed79b706ab0c2174b8201d1ff2a7f33875a Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Fri, 1 Mar 2024 15:19:03 +0100 Subject: [PATCH 56/63] chore(pipeline): modified sample release pipeline to use inputs and migrate nightly_workflow SUITEDEV-35237 Co-authored-by: megamegax --- .github/workflows/nightly_workflow.yml | 527 +++--------------- .github/workflows/on_push_workflow.yml | 9 + .../workflows/release_sample_app_workflow.yml | 4 +- 3 files changed, 103 insertions(+), 437 deletions(-) diff --git a/.github/workflows/nightly_workflow.yml b/.github/workflows/nightly_workflow.yml index 88058c2d..d16ac2b1 100644 --- a/.github/workflows/nightly_workflow.yml +++ b/.github/workflows/nightly_workflow.yml @@ -1,16 +1,37 @@ name: Nightly build on: - workflow_dispatch: schedule: - cron: '0 2 * * *' + workflow_dispatch: + inputs: + track: + type: choice + description: 'A track to assign the sample app' + options: + - alpha + - beta + - stable + default: beta env: - RELEASE_KEY_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD }} - RELEASE_KEY_ALIAS: ${{ secrets.ANDROID_KEYSTORE_ALIAS }} - RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} - RELEASE_STORE_FILE: ${{ secrets.RELEASE_STORE_FILE }} - DEVELOPMENT_MODE: ${{ secrets.DEVELOPMENT_MODE }} + USE_LOCAL_DEPENDENCY: ${{ vars.USE_LOCAL_DEPENDENCY }} + RELEASE_MODE: ${{ vars.RELEASE_MODE }} + ANDROID_RELEASE_STORE_FILE_BASE64: ${{ secrets.ANDROID_RELEASE_STORE_FILE_BASE64 }} + ANDROID_RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_RELEASE_STORE_PASSWORD }} + ANDROID_RELEASE_KEY_ALIAS: ${{ secrets.ANDROID_RELEASE_KEY_ALIAS }} + ANDROID_RELEASE_KEY_PASSWORD: ${{ secrets.ANDROID_RELEASE_KEY_PASSWORD }} + FIREBASE_PROJECT_ID: ${{ vars.FIREBASE_PROJECT_ID }} + FIREBASE_SERVICE_ACCOUNT_JSON: ${{ secrets.FIREBASE_SERVICE_ACCOUNT_JSON }} + GOOGLE_OAUTH_SERVER_CLIENT_ID: ${{ secrets.GOOGLE_OAUTH_SERVER_CLIENT_ID }} + GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON_BASE64: ${{ secrets.GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON_BASE64 }} + GOOGLE_SERVICES_JSON_BASE64: ${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }} + OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} + OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} + SONATYPE_STAGING_PROFILE_ID: ${{ secrets.SONATYPE_STAGING_PROFILE_ID }} + SONATYPE_SIGNING_KEY_ID: ${{ secrets.SONATYPE_SIGNING_KEY_ID }} + SONATYPE_SIGNING_PASSWORD: ${{ secrets.SONATYPE_SIGNING_PASSWORD }} + SONATYPE_SIGNING_SECRET_KEY_RING_FILE_BASE64: ${{ secrets.SONATYPE_SIGNING_SECRET_KEY_RING_FILE_BASE64 }} SLACK_CHANNEL: ${{ secrets.SLACK_CHANNEL }} SLACK_ICON: https://icons.iconarchive.com/icons/martz90/circle/256/android-icon.png SLACK_TITLE: Nightly build status @@ -20,470 +41,106 @@ env: jobs: Build: runs-on: ubuntu-latest - name: Build job - steps: - - uses: actions/checkout@v3 - with: - ref: dev - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - name: set up JDK 1.17 - uses: actions/setup-java@v4 - with: - distribution: 'temurin' - java-version: 17 - - name: create-google services json - uses: jsdaniell/create-json@1.1.2 - with: - name: google-services.json - json: ${{ secrets.GOOGLE_SERVICES_JSON }} - dir: sample - - - name: create local.properties - run: echo $ANDROID_HOME > local.properties - - - name: Build with Gradle - run: ./gradlew assembleAndroidTest -x lint - - - name: upload sample app artifact - uses: actions/upload-artifact@v4 - with: - name: sample - path: sample/build/outputs/apk/androidTest/debug/sample-debug-androidTest.apk - - - name: upload core test apk artifact - uses: actions/upload-artifact@v4 - with: - name: core - path: core/build/outputs/apk/androidTest/debug/core-debug-androidTest.apk - - - name: upload mobile-engage test apk artifact - uses: actions/upload-artifact@v4 - with: - name: mobile-engage - path: mobile-engage/build/outputs/apk/androidTest/debug/mobile-engage-debug-androidTest.apk - - - name: upload predict test apk artifact - uses: actions/upload-artifact@v4 - with: - name: predict - path: predict/build/outputs/apk/androidTest/debug/predict-debug-androidTest.apk + name: Test & Lint + strategy: + matrix: + include: + - task: core + - task: mobile-engage + - task: predict + - task: emarsys-firebase + - task: emarsys-huawei + - task: emarsys-sdk + - task: lint - - name: upload emarsys test apk artifact - uses: actions/upload-artifact@v4 - with: - name: emarsys - path: emarsys/build/outputs/apk/androidTest/debug/emarsys-debug-androidTest.apk - - - name: upload emarsys-sdk test apk artifact - uses: actions/upload-artifact@v4 - with: - name: emarsys-sdk - path: emarsys-sdk/build/outputs/apk/androidTest/debug/emarsys-sdk-debug-androidTest.apk - - - name: upload common test apk artifact - uses: actions/upload-artifact@v4 - with: - name: common - path: common/build/outputs/apk/androidTest/debug/common-debug-androidTest.apk - - - name: upload emarsys-firebase test apk artifact - uses: actions/upload-artifact@v4 - with: - name: emarsys-firebase - path: emarsys-firebase/build/outputs/apk/androidTest/debug/emarsys-firebase-debug-androidTest.apk - - - name: upload emarsys-huawei test apk artifact - uses: actions/upload-artifact@v4 - with: - name: emarsys-huawei - path: emarsys-huawei/build/outputs/apk/androidTest/debug/emarsys-huawei-debug-androidTest.apk - - - name: create testlab services json - uses: jsdaniell/create-json@1.1.2 - with: - name: sacc_key.json - json: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} - - GradleLint: - name: Run lint on project - runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: ref: dev submodules: true fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - name: set up JDK 1.17 uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 - - name: create-google services json - uses: jsdaniell/create-json@1.1.2 - with: - name: google-services.json - json: ${{ secrets.GOOGLE_SERVICES_JSON }} - dir: sample - - - name: create local.properties - run: echo $ANDROID_HOME > local.properties - - name: Lint project with Gradle - run: ./gradlew lint - - CreateReleaseBundle: - name: Create release bundle - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 with: - ref: dev - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - name: set up JDK 1.17 - uses: actions/setup-java@v4 - with: - distribution: 'temurin' - java-version: 17 - - name: create-google services json - uses: jsdaniell/create-json@1.1.2 - with: - name: google-services.json - json: ${{ secrets.GOOGLE_SERVICES_JSON }} - dir: sample - - - name: create local.properties - run: echo $ANDROID_HOME > local.properties + gradle-version: 8.6 + cache-overwrite-existing: true + gradle-home-cache-cleanup: true - - name: Create release keystore file - shell: bash - run: | - echo "${{ secrets.ANDROID_KEYSTORE }}" > mobile-team-android.jks.asc - gpg -d --passphrase "${{ secrets.ANDROID_GPG_PASSWORD }}" --batch mobile-team-android.jks.asc > sample/mobile-team-android.jks - - name: Create release sample app with Gradle - run: ./gradlew :sample:bundleRelease + - name: Prepare CI + run: make prepare-ci - - name: Upload bundle - uses: actions/upload-artifact@v4 + - name: Authenticate to Google Cloud + uses: google-github-actions/auth@v2.1.2 with: - name: mobile-sdk-sample - path: sample/build/outputs/bundle/release/sample-release.aab + workload_identity_provider: 'projects/395478287999/locations/global/workloadIdentityPools/github-actions/providers/github-actions' + service_account: 'firebase-test-lab-service-acco@ems-mobile-sdk.iam.gserviceaccount.com' + create_credentials_file: true - TestCore: - name: Run core tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - ref: dev - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" + - name: Set up Cloud SDK + uses: google-github-actions/setup-gcloud@v2 - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample + - name: Build + run: make build-test - - name: Download core tests - uses: actions/download-artifact@v4 - with: - name: core + - name: Test core + if: matrix.task == 'core' + run: make test-android-firebase MODULE_NAME=core - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithAllDevices.yml:core' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} + - name: Test mobile-engage + if: matrix.task == 'mobile-engage' + run: make test-android-firebase MODULE_NAME=mobile-engage - TestMobileEngage: - name: Run mobile-engage tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - ref: dev - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" + - name: Test predict + if: matrix.task == 'predict' + run: make test-android-firebase MODULE_NAME=predict - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample + - name: Test emarsys-firebase + if: matrix.task == 'emarsys-firebase' + run: make test-android-firebase MODULE_NAME=emarsys-firebase - - name: Download mobile-engage tests - uses: actions/download-artifact@v4 - with: - name: mobile-engage + - name: Test emarsys-huawei + if: matrix.module == 'emarsys-huawei' + run: make task-android-firebase MODULE_NAME=emarsys-huawei - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithAllDevices.yml:mobile-engage' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} + - name: Test emarsys-sdk + if: matrix.task == 'emarsys-sdk' + run: make test-android-firebase MODULE_NAME=emarsys-sdk - TestPredict: - name: Run predict tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - ref: dev - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample - - - name: Download predict tests - uses: actions/download-artifact@v4 - with: - name: predict - - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithAllDevices.yml:predict' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} + - name: Run lint + if: matrix.task == 'lint' + run: make lint - TestEmarsysSDK: - name: Run emarsys-sdk tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - ref: dev - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample - - - name: Download emarsys-sdk tests - uses: actions/download-artifact@v4 - with: - name: emarsys-sdk - - - name: Display structure of downloaded files - run: ls -R - - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithAllDevices.yml:emarsys-sdk' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} - - TestEmarsys: - name: Run emarsys tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - ref: dev - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample - - - name: Download emarsys tests - uses: actions/download-artifact@v4 - with: - name: emarsys - - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithAllDevices.yml:emarsys' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} - - TestCommon: - name: Run common tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - ref: dev - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample - - - name: Download common tests - uses: actions/download-artifact@v4 - with: - name: common - - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithAllDevices.yml:common' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} - - TestEmarsysFirebase: - name: Run emarsys-firebase tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - ref: dev - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample - - - name: Download emarsys-firebase tests - uses: actions/download-artifact@v4 - with: - name: emarsys-firebase - - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithAllDevices.yml:emarsys-firebase' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} - - TestEmarsysHuawei: - name: Run emarsys-huawei tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - ref: dev - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample - - - name: Download emarsys-huawei tests - uses: actions/download-artifact@v4 - with: - name: emarsys-huawei - - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithAllDevices.yml:emarsys-huawei' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} - - ReleaseSample: - name: Release sample app - runs-on: ubuntu-latest - needs: [ Build, TestCore, TestMobileEngage, TestPredict, TestEmarsysSDK, TestEmarsys, TestCommon, TestEmarsysFirebase, TestEmarsysHuawei, CreateReleaseBundle, GradleLint ] - steps: - - uses: actions/checkout@v3 - with: - ref: dev - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" - - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: mobile-sdk-sample - - - name: create-google services json - uses: jsdaniell/create-json@1.1.2 - with: - name: google-play-services.json - json: ${{ secrets.GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON }} - - - name: Playstore upload - uses: r0adkll/upload-google-play@v1.1.3 - with: - serviceAccountJson: google-play-services.json - packageName: com.emarsys.sample - releaseFile: sample-release.aab - track: beta - - SlackNotification: - name: Send slack notification + Report: + if: always() + needs: [ Build ] runs-on: ubuntu-latest - needs: [ ReleaseSample ] steps: - - name: Slack Notification - uses: megamegax/slack_action@0.2.3 + - name: Report on Slack (Error) + if: ${{ !cancelled() && contains(needs.*.result, 'failure') }} + uses: megamegax/slack_action@0.3.1 with: + webhook_url: '${{env.SLACK_WEBHOOK}}' channel: '${{env.SLACK_CHANNEL}}' - message: 'Nightly build successful! :man-gesturing-ok: :bananadance:' + message: 'Nightly build failed! :man-gesturing-no: :blobcatfearful:' user_name: '${{env.SLACK_USERNAME}}' - job_status: 'success' + job_status: 'failure' user_icon: '${{env.SLACK_ICON}}' - actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" },{ "type": "button", "text": "Install page", "url": "http://ems-mobileteam-artifacts.s3-website-eu-west-1.amazonaws.com/index-ems.html" }]' - - SlackNotificationOnError: - name: Send slack on error - runs-on: ubuntu-latest - needs: [ ReleaseSample ] - if: ${{ failure() }} - steps: - - uses: actions/checkout@v3 - with: - ref: dev - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" + actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" }]' - - name: Slack Notification - uses: megamegax/slack_action@0.2.3 + - name: Report on Slack (Success) + if: ${{ !contains(needs.*.result, 'cancelled') && !contains(needs.*.result, 'failure') }} + uses: megamegax/slack_action@0.3.1 with: + webhook_url: '${{env.SLACK_WEBHOOK}}' channel: '${{env.SLACK_CHANNEL}}' - message: 'Nightly build failed! :man-gesturing-no: :blobcatfearful:' + message: 'Nightly build successful! :man-gesturing-ok: :bananadance:' user_name: '${{env.SLACK_USERNAME}}' - job_status: 'failure' + job_status: 'success' user_icon: '${{env.SLACK_ICON}}' actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" }]' - Blackduck: - name: Run Blackduck scan - runs-on: ubuntu-latest - needs: [ Build ] - steps: - - name: Trigger Blackduck Scan - uses: peter-evans/repository-dispatch@v1 - with: - token: ${{ secrets.REPO_ACCESS_TOKEN }} - event-type: security-scan \ No newline at end of file diff --git a/.github/workflows/on_push_workflow.yml b/.github/workflows/on_push_workflow.yml index 3c3b1e1a..fc8efc8c 100644 --- a/.github/workflows/on_push_workflow.yml +++ b/.github/workflows/on_push_workflow.yml @@ -7,6 +7,15 @@ on: branches-ignore: - 'dependabot/**' workflow_dispatch: + inputs: + track: + type: choice + description: 'A track to assign the sample app' + options: + - alpha + - beta + - stable + default: alpha env: USE_LOCAL_DEPENDENCY: ${{ vars.USE_LOCAL_DEPENDENCY }} diff --git a/.github/workflows/release_sample_app_workflow.yml b/.github/workflows/release_sample_app_workflow.yml index e9d8581f..1d494bd4 100644 --- a/.github/workflows/release_sample_app_workflow.yml +++ b/.github/workflows/release_sample_app_workflow.yml @@ -2,7 +2,7 @@ name: Release Sample on: workflow_run: - workflows: [ "On Push" ] + workflows: [ "On Push", "Nightly build" ] types: - completed workflow_dispatch: @@ -68,7 +68,7 @@ jobs: serviceAccountJson: ./sample/google-play-store-service-account.json packageName: com.emarsys.sample releaseFiles: sample/build/outputs/bundle/release/sample-release.aab - track: alpha + track: ${{ github.event.workflow_run.inputs.track }} Report: if: always() From 826830ceeeff67becf987fe49f3e565f1a80f493 Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Fri, 1 Mar 2024 15:41:18 +0100 Subject: [PATCH 57/63] chore(pipeline): migrate nightly_e2e_workflow SUITEDEV-35237 Co-authored-by: megamegax --- .github/workflows/nightly_e2e_workflow.yml | 140 +++++++++------------ 1 file changed, 57 insertions(+), 83 deletions(-) diff --git a/.github/workflows/nightly_e2e_workflow.yml b/.github/workflows/nightly_e2e_workflow.yml index 6c4c6a48..fd4f4d88 100644 --- a/.github/workflows/nightly_e2e_workflow.yml +++ b/.github/workflows/nightly_e2e_workflow.yml @@ -3,12 +3,29 @@ name: Nightly E2E pipeline on: workflow_dispatch: schedule: - - cron: '0 3 * * *' + - cron: '0 3 * * *' env: - RELEASE_KEY_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD }} - RELEASE_KEY_ALIAS: ${{ secrets.ANDROID_KEYSTORE_ALIAS }} - RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + USE_LOCAL_DEPENDENCY: ${{ vars.USE_LOCAL_DEPENDENCY }} + RELEASE_MODE: ${{ vars.RELEASE_MODE }} + ANDROID_RELEASE_STORE_FILE_BASE64: ${{ secrets.ANDROID_RELEASE_STORE_FILE_BASE64 }} + ANDROID_RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_RELEASE_STORE_PASSWORD }} + ANDROID_RELEASE_KEY_ALIAS: ${{ secrets.ANDROID_RELEASE_KEY_ALIAS }} + ANDROID_RELEASE_KEY_PASSWORD: ${{ secrets.ANDROID_RELEASE_KEY_PASSWORD }} + FIREBASE_PROJECT_ID: ${{ vars.FIREBASE_PROJECT_ID }} + FIREBASE_SERVICE_ACCOUNT_JSON: ${{ secrets.FIREBASE_SERVICE_ACCOUNT_JSON }} + GOOGLE_OAUTH_SERVER_CLIENT_ID: ${{ secrets.GOOGLE_OAUTH_SERVER_CLIENT_ID }} + GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON_BASE64: ${{ secrets.GOOGLE_PLAY_STORE_SEVICE_ACCOUNT_JSON_BASE64 }} + GOOGLE_SERVICES_JSON_BASE64: ${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }} + OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} + OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} + SONATYPE_STAGING_PROFILE_ID: ${{ secrets.SONATYPE_STAGING_PROFILE_ID }} + SONATYPE_SIGNING_KEY_ID: ${{ secrets.SONATYPE_SIGNING_KEY_ID }} + SONATYPE_SIGNING_PASSWORD: ${{ secrets.SONATYPE_SIGNING_PASSWORD }} + SONATYPE_SIGNING_SECRET_KEY_RING_FILE_BASE64: ${{ secrets.SONATYPE_SIGNING_SECRET_KEY_RING_FILE_BASE64 }} + RELEASE_KEY_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD }} + RELEASE_KEY_ALIAS: ${{ secrets.ANDROID_KEYSTORE_ALIAS }} + RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} RELEASE_STORE_FILE: ${{ secrets.RELEASE_STORE_FILE }} DEVELOPMENT_MODE: ${{ secrets.DEVELOPMENT_MODE }} SLACK_CHANNEL: ${{ secrets.SLACK_CHANNEL }} @@ -22,112 +39,69 @@ jobs: runs-on: ubuntu-latest name: Build job steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: ref: dev submodules: true fetch-depth: 0 - - run: git fetch --all || echo "==> Accept any result" - name: set up JDK 1.17 uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 - - name: create-google services json - uses: jsdaniell/create-json@1.1.2 + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 with: - name: google-services.json - json: ${{ secrets.GOOGLE_SERVICES_JSON }} - dir: sample + gradle-version: 8.6 + cache-overwrite-existing: true + gradle-home-cache-cleanup: true - - name: create local.properties - run: echo $ANDROID_HOME > local.properties + - name: Prepare CI + run: make prepare-ci - - name: Build with Gradle - run: ./gradlew assembleAndroidTest -x lint - - - name: upload sample app artifact - uses: actions/upload-artifact@v4 + - name: Authenticate to Google Cloud + uses: google-github-actions/auth@v2.1.2 with: - name: sample - path: sample/build/outputs/apk/androidTest/debug/sample-debug-androidTest.apk + workload_identity_provider: 'projects/395478287999/locations/global/workloadIdentityPools/github-actions/providers/github-actions' + service_account: 'firebase-test-lab-service-acco@ems-mobile-sdk.iam.gserviceaccount.com' + create_credentials_file: true - - name: upload emarsys-e2e-test test apk artifact - uses: actions/upload-artifact@v4 - with: - name: emarsys-e2e-test - path: emarsys-e2e-test/build/outputs/apk/androidTest/debug/emarsys-e2e-test-debug-androidTest.apk + - name: Set up Cloud SDK + uses: google-github-actions/setup-gcloud@v2 - - name: create testlab services json - uses: jsdaniell/create-json@1.1.2 - with: - name: sacc_key.json - json: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} + - name: Build + run: make build-test - TestE2E: - name: Run E2E tests on Firebase - needs: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - submodules: true - fetch-depth: 0 - - run: git fetch --all || echo "==> Accept any result" + - name: Test E2E + run: make test-android-firebase MODULE_NAME=emarsys-e2e-test - - name: Download sample app - uses: actions/download-artifact@v4 - with: - name: sample - - - name: Download Emarsys E2E tests - uses: actions/download-artifact@v4 - with: - name: emarsys-e2e-test - - - name: Run tests - uses: asadmansr/Firebase-Test-Lab-Action@v1.0 - with: - arg-spec: 'testWithSomeVirtualDevices.yml:emarsys-e2e-test' - env: - SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} - - SlackNotification: - name: Send slack notification + Report: + if: always() + needs: [ Build ] runs-on: ubuntu-latest - needs: [TestE2E] steps: - - name: Slack Notification - uses: megamegax/slack_action@0.2.3 + - name: Report on Slack (Error) + if: ${{ !cancelled() && contains(needs.*.result, 'failure') }} + uses: megamegax/slack_action@0.3.1 with: + webhook_url: '${{env.SLACK_WEBHOOK}}' channel: '${{env.SLACK_CHANNEL}}' - message: 'Nightly E2E tests successful! :man-gesturing-ok: :bananadance:' + message: 'Nightly E2E tests failed! :man-gesturing-no: :blobcatfearful:' user_name: '${{env.SLACK_USERNAME}}' - job_status: 'success' + job_status: 'failure' user_icon: '${{env.SLACK_ICON}}' - actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" },{ "type": "button", "text": "Install page", "url": "http://ems-mobileteam-artifacts.s3-website-eu-west-1.amazonaws.com/index-ems.html" }]' - - - SlackNotificationOnError: - name: Send slack on error - runs-on: ubuntu-latest - needs: [TestE2E] - if: ${{ failure() }} - steps: - - uses: actions/checkout@v3 - with: - submodules: true - fetch-depth: 0 # 0 indicates all history - - run: git fetch --all || echo "==> Accept any result" + actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" }]' - - name: Slack Notification - uses: megamegax/slack_action@0.2.3 + - name: Report on Slack (Success) + if: ${{ !contains(needs.*.result, 'cancelled') && !contains(needs.*.result, 'failure') }} + uses: megamegax/slack_action@0.3.1 with: + webhook_url: '${{env.SLACK_WEBHOOK}}' channel: '${{env.SLACK_CHANNEL}}' - message: 'Nightly E2E tests failed! :man-gesturing-no: :blobcatfearful:' + message: 'Nightly E2E tests successful! :man-gesturing-ok: :bananadance:' user_name: '${{env.SLACK_USERNAME}}' - job_status: 'failure' + job_status: 'success' user_icon: '${{env.SLACK_ICON}}' - actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" }]' + actions: '[{ "type": "button", "text": "View actions", "url": "https://github.com/emartech/android-emarsys-sdk/actions" },{ "type": "button", "text": "View Firebase", "url": "https://console.firebase.google.com/project/ems-mobile-sdk/testlab/histories/" }]' \ No newline at end of file From 94a2ff6f2e005eb850d3fbc0ca7ca775908aca8c Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Fri, 1 Mar 2024 15:49:58 +0100 Subject: [PATCH 58/63] chore(pipeline): avoid running sample release on completed but failed triggering workflows SUITEDEV-35237 Co-authored-by: megamegax --- .github/workflows/release_sample_app_workflow.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release_sample_app_workflow.yml b/.github/workflows/release_sample_app_workflow.yml index 1d494bd4..b56ca5da 100644 --- a/.github/workflows/release_sample_app_workflow.yml +++ b/.github/workflows/release_sample_app_workflow.yml @@ -33,6 +33,7 @@ env: jobs: ReleaseSampleApp: + if: ${{ github.event.workflow_run.conclusion == 'success' }} name: Release Sample App runs-on: ubuntu-latest steps: @@ -71,7 +72,7 @@ jobs: track: ${{ github.event.workflow_run.inputs.track }} Report: - if: always() + if: ${{ always() && github.event.workflow_run.conclusion == 'success' }} needs: [ ReleaseSampleApp ] runs-on: ubuntu-latest steps: From 4814f89a1ac372df199bede5373fbb0dda188e3b Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Thu, 7 Mar 2024 14:20:31 +0100 Subject: [PATCH 59/63] chore(pipeline): fix google auth by giving correct permissions to job SUITEDEV-35352 Co-authored-by: Andras Sarro --- .github/workflows/nightly_workflow.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/nightly_workflow.yml b/.github/workflows/nightly_workflow.yml index d16ac2b1..9669449f 100644 --- a/.github/workflows/nightly_workflow.yml +++ b/.github/workflows/nightly_workflow.yml @@ -42,6 +42,9 @@ jobs: Build: runs-on: ubuntu-latest name: Test & Lint + permissions: + contents: 'read' + id-token: 'write' strategy: matrix: include: From 78313538a3e01d2603e24ebedfc6ef00d31fa5fe Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Thu, 7 Mar 2024 14:54:44 +0100 Subject: [PATCH 60/63] chore(pipeline): fix google auth by giving correct permissions to job SUITEDEV-35352 Co-authored-by: megamegax Co-authored-by: Andras Sarro --- .github/workflows/nightly_e2e_workflow.yml | 3 +++ .github/workflows/release_sample_app_workflow.yml | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/nightly_e2e_workflow.yml b/.github/workflows/nightly_e2e_workflow.yml index fd4f4d88..496202b0 100644 --- a/.github/workflows/nightly_e2e_workflow.yml +++ b/.github/workflows/nightly_e2e_workflow.yml @@ -38,6 +38,9 @@ jobs: Build: runs-on: ubuntu-latest name: Build job + permissions: + contents: 'read' + id-token: 'write' steps: - uses: actions/checkout@v4 with: diff --git a/.github/workflows/release_sample_app_workflow.yml b/.github/workflows/release_sample_app_workflow.yml index b56ca5da..55d1f093 100644 --- a/.github/workflows/release_sample_app_workflow.yml +++ b/.github/workflows/release_sample_app_workflow.yml @@ -33,7 +33,7 @@ env: jobs: ReleaseSampleApp: - if: ${{ github.event.workflow_run.conclusion == 'success' }} + if: ${{ github.event.workflow_run.conclusion == 'success' || github.event_name == 'workflow_dispatch' }} name: Release Sample App runs-on: ubuntu-latest steps: @@ -69,7 +69,7 @@ jobs: serviceAccountJson: ./sample/google-play-store-service-account.json packageName: com.emarsys.sample releaseFiles: sample/build/outputs/bundle/release/sample-release.aab - track: ${{ github.event.workflow_run.inputs.track }} + track: ${{ github.event.workflow_run.inputs.track != null && github.event.workflow_run.inputs.track || alpha }} Report: if: ${{ always() && github.event.workflow_run.conclusion == 'success' }} From 01ca8ec00311224fc5b498538f688ab6b8790f1b Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Thu, 7 Mar 2024 15:06:45 +0100 Subject: [PATCH 61/63] chore(pipeline): fix workflow syntax SUITEDEV-35352 Co-authored-by: megamegax Co-authored-by: Andras Sarro --- .github/workflows/release_sample_app_workflow.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release_sample_app_workflow.yml b/.github/workflows/release_sample_app_workflow.yml index 55d1f093..a882257e 100644 --- a/.github/workflows/release_sample_app_workflow.yml +++ b/.github/workflows/release_sample_app_workflow.yml @@ -69,7 +69,7 @@ jobs: serviceAccountJson: ./sample/google-play-store-service-account.json packageName: com.emarsys.sample releaseFiles: sample/build/outputs/bundle/release/sample-release.aab - track: ${{ github.event.workflow_run.inputs.track != null && github.event.workflow_run.inputs.track || alpha }} + track: ${{ github.event.workflow_run.inputs.track != null && github.event.workflow_run.inputs.track || 'alpha' }} Report: if: ${{ always() && github.event.workflow_run.conclusion == 'success' }} From 673ab83cc578b284942552296dd6c798fb0b6cdb Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Thu, 7 Mar 2024 16:07:29 +0100 Subject: [PATCH 62/63] chore(pipeline): turned on slack reporting on workflow dispatch SUITEDEV-35352 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: Andras Sarro --- .github/workflows/release_sample_app_workflow.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release_sample_app_workflow.yml b/.github/workflows/release_sample_app_workflow.yml index a882257e..b466cf23 100644 --- a/.github/workflows/release_sample_app_workflow.yml +++ b/.github/workflows/release_sample_app_workflow.yml @@ -72,7 +72,7 @@ jobs: track: ${{ github.event.workflow_run.inputs.track != null && github.event.workflow_run.inputs.track || 'alpha' }} Report: - if: ${{ always() && github.event.workflow_run.conclusion == 'success' }} + if: ${{ github.event.workflow_run.conclusion == 'success' || github.event_name == 'workflow_dispatch' }} needs: [ ReleaseSampleApp ] runs-on: ubuntu-latest steps: From 5efa86c5977c8c3c49a00a46951bf45ac6934d4a Mon Sep 17 00:00:00 2001 From: David Schuppa <32750715+davidSchuppa@users.noreply.github.com> Date: Wed, 13 Mar 2024 10:58:01 +0100 Subject: [PATCH 63/63] feat(remote-config): remoteConfig refresh is part of the setup flow SUITEDEV-35377 Co-authored-by: LasOri <24588073+LasOri@users.noreply.github.com> Co-authored-by: megamegax Co-authored-by: Andras Sarro --- .../java/com/emarsys/EmarsysTest.kt | 33 ++++++++++-- .../src/main/java/com/emarsys/Emarsys.kt | 20 +++++++ .../com/emarsys/di/DefaultEmarsysComponent.kt | 2 - .../config/FetchRemoteConfigActionTest.kt | 54 ------------------- .../emarsys/config/FetchRemoteConfigAction.kt | 30 ----------- 5 files changed, 49 insertions(+), 90 deletions(-) delete mode 100644 emarsys/src/androidTest/java/com/emarsys/config/FetchRemoteConfigActionTest.kt delete mode 100644 emarsys/src/main/java/com/emarsys/config/FetchRemoteConfigAction.kt diff --git a/emarsys-sdk/src/androidTest/java/com/emarsys/EmarsysTest.kt b/emarsys-sdk/src/androidTest/java/com/emarsys/EmarsysTest.kt index daa1d8c0..9c1d2686 100644 --- a/emarsys-sdk/src/androidTest/java/com/emarsys/EmarsysTest.kt +++ b/emarsys-sdk/src/androidTest/java/com/emarsys/EmarsysTest.kt @@ -12,8 +12,8 @@ import com.emarsys.Emarsys.trackDeepLink import com.emarsys.clientservice.ClientServiceApi import com.emarsys.common.feature.InnerFeature import com.emarsys.config.ConfigApi +import com.emarsys.config.ConfigInternal import com.emarsys.config.EmarsysConfig -import com.emarsys.config.FetchRemoteConfigAction import com.emarsys.core.activity.ActivityLifecycleWatchdog import com.emarsys.core.activity.CurrentActivityWatchdog import com.emarsys.core.api.experimental.FlipperFeature @@ -139,6 +139,7 @@ class EmarsysTest : AnnotationSpec() { private lateinit var mockLoggingMobileEngageApi: MobileEngageApi private lateinit var mockLoggingPredict: PredictApi private lateinit var mockConfig: ConfigApi + private lateinit var mockConfigInternal: ConfigInternal private lateinit var mockMessageInbox: MessageInboxApi private lateinit var mockHardwareIdProvider: HardwareIdProvider private lateinit var mockLanguageProvider: LanguageProvider @@ -207,6 +208,7 @@ class EmarsysTest : AnnotationSpec() { mockLoggingPredict = mock() mockPredictRestricted = mock() mockConfig = mock() + mockConfigInternal = mock() mockMessageInbox = mock() mockLogic = mock() mockRecommendationFilter = mock() @@ -269,6 +271,7 @@ class EmarsysTest : AnnotationSpec() { predictRestricted = mockPredictRestricted, loggingPredictRestricted = mockPredictRestricted, config = mockConfig, + configInternal = mockConfigInternal, eventService = mockEventServiceApi, loggingEventService = mockLoggingEventServiceApi, deepLink = mockDeepLinkApi, @@ -284,7 +287,7 @@ class EmarsysTest : AnnotationSpec() { } @Test - fun testSetup_whenMobileEngageApplicationCodeAndMerchantIdAreNull_mobileEngageAndPredict_shouldBeDisabled() { + fun testSetup_whenMobileEngageApplicationCodeAndMerchantIdAreNull_mobileEngageAndPredict_shouldBeDisabled_andShouldNotFetchRemoteConfig() { val config = createConfig() .applicationCode(null) .merchantId(null) @@ -295,13 +298,24 @@ class EmarsysTest : AnnotationSpec() { FeatureRegistry.isFeatureEnabled(InnerFeature.MOBILE_ENGAGE) shouldBe false FeatureRegistry.isFeatureEnabled(InnerFeature.PREDICT) shouldBe false + verify(mockConfigInternal, times(0)).refreshRemoteConfig(any()) } @Test - fun testSetup_whenMobileEngageApplicationCodeIsNotNull_mobileEngageFeature_shouldBeEnabled() { + fun testSetup_shouldNotFetchRemoteConfig_when_ApplicationCode_is_invalid() { + listOf("", "null", "nil", "0", null).forEach { + verifyRemoteConfigFetchWithInvalidAppcode(it) + } + } + + @Test + fun testSetup_whenMobileEngageApplicationCodeIsNotNull_mobileEngageFeature_shouldBeEnabled_andFetchRemoteConfig() { setup(mobileEngageConfig) + runBlockingOnCoreSdkThread() + FeatureRegistry.isFeatureEnabled(InnerFeature.MOBILE_ENGAGE) shouldBe true + verify(mockConfigInternal).refreshRemoteConfig(any()) } @Test @@ -508,7 +522,6 @@ class EmarsysTest : AnnotationSpec() { numberOfElementsIn(actions, DeepLinkAction::class.java).toLong() shouldBe 1 numberOfElementsIn(actions, DeviceInfoStartAction::class.java).toLong() shouldBe 1 numberOfElementsIn(actions, FetchGeofencesAction::class.java).toLong() shouldBe 1 - numberOfElementsIn(actions, FetchRemoteConfigAction::class.java).toLong() shouldBe 1 } } @@ -908,6 +921,18 @@ class EmarsysTest : AnnotationSpec() { .enableExperimentalFeatures(*experimentalFeatures) } + private fun verifyRemoteConfigFetchWithInvalidAppcode(appCode: String?) { + val config = createConfig() + .applicationCode(appCode) + .merchantId(null) + .build() + setup(config) + + runBlockingOnCoreSdkThread() + + verify(mockConfigInternal, times(0)).refreshRemoteConfig(any()) + } + private fun runBlockingOnCoreSdkThread(callback: (() -> Unit)? = null) { val latch = CountDownLatch(1) var exception: Exception? = null diff --git a/emarsys-sdk/src/main/java/com/emarsys/Emarsys.kt b/emarsys-sdk/src/main/java/com/emarsys/Emarsys.kt index 4a267314..fc0ea64b 100644 --- a/emarsys-sdk/src/main/java/com/emarsys/Emarsys.kt +++ b/emarsys-sdk/src/main/java/com/emarsys/Emarsys.kt @@ -2,6 +2,7 @@ package com.emarsys import android.app.Activity import android.content.Intent +import android.util.Log import androidx.lifecycle.ProcessLifecycleOwner import com.emarsys.common.feature.InnerFeature.EVENT_SERVICE_V4 import com.emarsys.common.feature.InnerFeature.MOBILE_ENGAGE @@ -17,6 +18,7 @@ import com.emarsys.core.database.trigger.TriggerType import com.emarsys.core.feature.FeatureRegistry import com.emarsys.core.util.log.Logger import com.emarsys.core.util.log.entry.CrashLog +import com.emarsys.core.util.log.entry.StatusLog import com.emarsys.di.DefaultEmarsysDependencies import com.emarsys.di.EmarsysDependencyInjection import com.emarsys.di.emarsys @@ -95,6 +97,8 @@ object Emarsys { initializeMobileEngageContact() } } + + refreshRemoteConfig(emarsysConfig.applicationCode) } private fun registerLifecycleObservers() { @@ -228,4 +232,20 @@ object Emarsys { .setContact() } } + + private fun refreshRemoteConfig(applicationCode: String?) { + if (!listOf("", "null", "nil", "0").contains(applicationCode?.lowercase()) && applicationCode != null) { + emarsys().configInternal.proxyApi(mobileEngage().concurrentHandlerHolder) + .refreshRemoteConfig { + it?.let { + val logEntry = StatusLog(Emarsys::class.java, "refreshRemoteConfig", mapOf("applicationCode" to applicationCode, "exception" to it.message)) + Logger.log(logEntry) + } + } + } else { + Log.w("EmarsysSdk", "Invalid applicationCode: $applicationCode") + val logEntry = StatusLog(Emarsys::class.java, "refreshRemoteConfig", mapOf("applicationCode" to applicationCode)) + Logger.log(logEntry) + } + } } \ No newline at end of file diff --git a/emarsys-sdk/src/main/java/com/emarsys/di/DefaultEmarsysComponent.kt b/emarsys-sdk/src/main/java/com/emarsys/di/DefaultEmarsysComponent.kt index 92c5679f..35511447 100644 --- a/emarsys-sdk/src/main/java/com/emarsys/di/DefaultEmarsysComponent.kt +++ b/emarsys-sdk/src/main/java/com/emarsys/di/DefaultEmarsysComponent.kt @@ -19,7 +19,6 @@ import com.emarsys.config.ConfigApi import com.emarsys.config.ConfigInternal import com.emarsys.config.DefaultConfigInternal import com.emarsys.config.EmarsysConfig -import com.emarsys.config.FetchRemoteConfigAction import com.emarsys.config.RemoteConfigResponseMapper import com.emarsys.core.DefaultCoreCompletionHandler import com.emarsys.core.Mapper @@ -333,7 +332,6 @@ open class DefaultEmarsysComponent(config: EmarsysConfig) : EmarsysComponent { DeviceInfoStartAction(clientServiceInternal, deviceInfoPayloadStorage, deviceInfo), DeepLinkAction(deepLinkInternal), FetchGeofencesAction(geofenceInternal), - FetchRemoteConfigAction(configInternal) { logInitialSetup(config) }, AppStartAction(eventServiceInternal, contactTokenStorage) ) ActivityLifecycleActionRegistry(concurrentHandlerHolder, currentActivityProvider, actions) diff --git a/emarsys/src/androidTest/java/com/emarsys/config/FetchRemoteConfigActionTest.kt b/emarsys/src/androidTest/java/com/emarsys/config/FetchRemoteConfigActionTest.kt deleted file mode 100644 index 8c670a36..00000000 --- a/emarsys/src/androidTest/java/com/emarsys/config/FetchRemoteConfigActionTest.kt +++ /dev/null @@ -1,54 +0,0 @@ -package com.emarsys.config - -import com.emarsys.core.api.result.CompletionListener -import com.emarsys.fake.FakeEmarsysDependencyContainer -import com.emarsys.mobileengage.di.setupMobileEngageComponent -import com.emarsys.mobileengage.di.tearDownMobileEngageComponent - - -import com.emarsys.testUtil.AnnotationSpec -import org.mockito.Mockito.verify -import org.mockito.kotlin.mock -import org.mockito.kotlin.timeout -import org.mockito.kotlin.times -import org.mockito.kotlin.whenever - -class FetchRemoteConfigActionTest : AnnotationSpec() { - - private lateinit var fetchAction: FetchRemoteConfigAction - private lateinit var mockConfigInternal: ConfigInternal - private lateinit var mockCompletionListener: CompletionListener - - - @Before - fun setup() { - mockConfigInternal = mock() - mockCompletionListener = mock() - - setupMobileEngageComponent(FakeEmarsysDependencyContainer()) - - fetchAction = - FetchRemoteConfigAction(mockConfigInternal, completionListener = mockCompletionListener) - } - - @After - fun tearDown() { - tearDownMobileEngageComponent() - } - - @Test - fun testExecute_invokesConfigInternalsRefreshRemoteConfigMethod() { - fetchAction.execute(null) - verify(mockConfigInternal, timeout(100)).refreshRemoteConfig(mockCompletionListener) - } - - @Test - fun testExecute_shouldNotInvokeRefreshConfig_when_ApplicationCode_is_Invalid() { - whenever(mockConfigInternal.applicationCode).thenReturn("Nil") - - fetchAction.execute(null) - - verify(mockConfigInternal, times(0)).refreshRemoteConfig(mockCompletionListener) - } - -} \ No newline at end of file diff --git a/emarsys/src/main/java/com/emarsys/config/FetchRemoteConfigAction.kt b/emarsys/src/main/java/com/emarsys/config/FetchRemoteConfigAction.kt deleted file mode 100644 index 70402078..00000000 --- a/emarsys/src/main/java/com/emarsys/config/FetchRemoteConfigAction.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.emarsys.config - -import android.app.Activity -import android.util.Log -import com.emarsys.core.activity.ActivityLifecycleAction -import com.emarsys.core.activity.ActivityLifecyclePriorities -import com.emarsys.core.api.proxyApi -import com.emarsys.core.api.result.CompletionListener -import com.emarsys.core.util.log.Logger -import com.emarsys.core.util.log.entry.StatusLog -import com.emarsys.mobileengage.di.mobileEngage - -class FetchRemoteConfigAction(private val configInternal: ConfigInternal, - override val priority: Int = ActivityLifecyclePriorities.FETCH_REMOTE_CONFIG_ACTION_PRIORITY, - override val repeatable: Boolean = false, - override val triggeringLifecycle: ActivityLifecycleAction.ActivityLifecycle = ActivityLifecycleAction.ActivityLifecycle.RESUME, - private val completionListener: CompletionListener -) : ActivityLifecycleAction { - - override fun execute(activity: Activity?) { - if (!listOf("", "null", "nil", "0").contains(configInternal.applicationCode?.lowercase())) { - configInternal.proxyApi(mobileEngage().concurrentHandlerHolder) - .refreshRemoteConfig(completionListener) - } else { - Log.w("EmarsysSdk", "Invalid applicationCode: ${configInternal.applicationCode}") - val logEntry = StatusLog(FetchRemoteConfigAction::class.java, "execute", mapOf("applicationCode" to configInternal.applicationCode)) - Logger.log(logEntry) - } - } -}