From 8d42e409a392acf7d43959cb496e1560835fa99c Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Fri, 12 Sep 2025 17:23:43 -0400 Subject: [PATCH 01/23] feat: Implement Trunk tool --- .github/dependabot.yml | 24 +- .github/workflows/cross-platform-tests.yml | 19 +- .github/workflows/daily.yml | 157 +- .github/workflows/dependabot-automerge.yml | 7 +- .../workflows/dependabot-rebase-branch.yml | 5 + .../workflows/issue-autorespond-and-close.yml | 6 +- .github/workflows/pull-request.yml | 41 +- .github/workflows/release.yml | 12 +- .github/workflows/reusable-workflows.yml | 5 + .trunk/.gitignore | 9 + .trunk/configs/.markdownlint.yaml | 2 + .trunk/configs/.shellcheckrc | 7 + .trunk/configs/.yamllint.yaml | 7 + .trunk/trunk.yaml | 55 + ONBOARDING.md | 14 +- README.md | 144 +- .../internal/MParticleJSInterfaceITest.java | 224 +-- .../BatchCreationCallbackTests.kt | 211 +-- .../kotlin/com.mparticle/DataplanTest.kt | 61 +- .../kotlin/com.mparticle/MPUserTest.kt | 73 +- .../com.mparticle/MParticleOptionsTest.kt | 447 ++++-- .../kotlin/com.mparticle/MParticleTest.kt | 138 +- .../com.mparticle/PushRegistrationTest.kt | 406 +++-- .../com.mparticle/SessionMessagesTest.kt | 13 +- .../com.mparticle/UploadEventKotlinTest.kt | 80 +- .../kotlin/com.mparticle/UploadMessageTest.kt | 97 +- .../com.mparticle/commerce/CommerceApiTest.kt | 39 +- .../identity/IdentityApiOutgoingTest.kt | 51 +- .../identity/IdentityApiStartTest.kt | 111 +- .../com.mparticle/identity/IdentityApiTest.kt | 326 ++-- .../MParticleIdentityClientImplTest.kt | 384 ++--- .../identity/MParticleUserDelegateITest.kt | 47 +- .../identity/MParticleUserTest.kt | 9 +- .../AppStateManagerInstrumentedTest.kt | 46 +- .../ApplicationContextWrapperITest.kt | 28 +- .../internal/BatchSessionInfoTest.kt | 10 +- .../internal/ConfigManagerInstrumentedTest.kt | 201 ++- .../internal/ConfigMigrationTest.kt | 33 +- .../internal/ConfigRequestTests.kt | 13 +- .../internal/ConfigStalenessCheckTest.kt | 90 +- .../internal/DeviceAttributesTests.kt | 22 +- .../internal/KitFrameworkWrapperTest.kt | 170 ++- .../internal/MessageManagerTests.kt | 36 +- .../internal/UpdateAdIdIdentityTest.kt | 31 +- .../internal/database/TestSQLiteOpenHelper.kt | 84 +- .../database/UpgradeMessageTableTest.kt | 30 +- .../internal/database/UpgradeVersionTest.kt | 81 +- .../database/services/BaseMPServiceTest.kt | 41 +- .../services/BreadcrumbServiceTest.kt | 16 +- .../services/MParticleDBManagerTest.kt | 56 +- .../database/services/MessageServiceTest.kt | 273 ++-- .../database/services/ReportingServiceTest.kt | 205 +-- .../database/services/SessionServiceTest.kt | 15 +- .../services/UserAttributesServiceTest.kt | 512 ++++--- .../internal/database/tables/BaseTableTest.kt | 5 +- .../database/tables/BreadcrumbTableTest.kt | 39 +- .../database/tables/MessageTableTest.kt | 96 +- .../database/tables/ReportingTableTest.kt | 37 +- .../database/tables/SessionTableTest.kt | 47 +- .../database/tables/UploadTableTest.kt | 28 +- .../database/tables/UserAttributeTableTest.kt | 37 +- .../com.mparticle/networking/AccessUtils.kt | 17 +- .../networking/MParticleBaseClientImplTest.kt | 431 +++--- .../networking/NetworkOptionsManagerTest.kt | 16 +- .../networking/NetworkOptionsTest.kt | 385 ++--- .../com.mparticle/networking/PinningTest.kt | 39 +- .../networking/PinningTestHelper.kt | 67 +- .../PinningTestNetworkOptionsDisabled.kt | 14 +- .../PinningTestNetworkOptionsEnabled.kt | 14 +- .../com.mparticle/startup/StartupTest.kt | 154 +- .../main/java/com/mparticle/MParticle.java | 6 +- .../java/com/mparticle/MParticleOptions.java | 12 +- .../KitsLoadedListenerConfiguration.kt | 9 +- .../internal/MParticleApiClientImpl.java | 20 +- .../mparticle/internal/SegmentDatabase.java | 18 +- .../mparticle/internal/SideloadedKitsUtils.kt | 6 +- .../internal/UserAudiencesRetriever.kt | 15 +- .../database/tables/BreadcrumbTable.java | 16 +- .../database/tables/MessageTable.java | 28 +- .../database/tables/ReportingTable.java | 16 +- .../database/tables/SessionTable.java | 28 +- .../internal/database/tables/UploadTable.java | 18 +- .../database/tables/UserAttributesTable.java | 14 +- .../com/mparticle/segmentation/Segment.java | 4 +- .../com/mparticle/MpRoktEventCallback.kt | 10 +- .../src/main/kotlin/com/mparticle/Rokt.kt | 18 +- .../main/kotlin/com/mparticle/RoktEvent.kt | 43 +- .../mparticle/TypedUserAttributeListener.kt | 4 +- .../main/kotlin/com/mparticle/WrapperSdk.kt | 12 +- .../kotlin/com/mparticle/audience/Audience.kt | 4 +- .../mparticle/audience/AudienceResponse.kt | 11 +- .../com/mparticle/audience/AudienceTask.kt | 4 +- .../audience/AudienceTaskFailureListener.kt | 2 +- .../audience/AudienceTaskSuccessListener.kt | 2 +- .../mparticle/audience/BaseAudienceTask.kt | 16 +- .../identity/UserAttributeListenerWrapper.kt | 30 +- .../com/mparticle/internal/AppStateManager.kt | 809 +++++----- .../internal/ApplicationContextWrapper.kt | 105 +- .../kotlin/com/mparticle/internal/BatchId.kt | 10 +- .../com/mparticle/internal/Constants.kt | 262 ++-- .../com/mparticle/internal/CoreCallbacks.kt | 69 +- .../com/mparticle/internal/JellybeanHelper.kt | 2 +- .../com/mparticle/internal/KitKatHelper.kt | 5 +- .../internal/MPLifecycleCallbackDelegate.kt | 15 +- .../mparticle/internal/MPLocationListener.kt | 10 +- .../com/mparticle/internal/SideloadedKit.kt | 1 - .../com/mparticle/internal/UserStorage.kt | 288 ++-- .../internal/listeners/GraphListener.kt | 7 +- .../internal/listeners/InternalListener.kt | 192 ++- .../listeners/InternalListenerManager.kt | 267 ++-- .../kotlin/com/mparticle/rokt/RoktConfig.kt | 5 +- .../com/mparticle/rokt/RoktEmbeddedView.kt | 2 +- .../rokt/RoktLayoutDimensionCallBack.kt | 10 +- .../kotlin/com/mparticle/rokt/RoktOptions.kt | 16 +- .../test/kotlin/com/mparticle/MPEventTests.kt | 45 +- .../kotlin/com/mparticle/MParticleTest.kt | 240 +-- .../kotlin/com/mparticle/MockMParticle.kt | 25 +- .../src/test/kotlin/com/mparticle/RoktTest.kt | 39 +- .../test/kotlin/com/mparticle/SessionTest.kt | 1 - .../audience/AudienceResponseTest.kt | 46 +- .../audience/BaseAudienceTaskTest.kt | 116 +- .../mparticle/commerce/CommerceEventTest.kt | 133 +- .../com/mparticle/commerce/ProductTest.kt | 20 +- .../com/mparticle/consent/ConsentStateTest.kt | 276 +++- .../mparticle/identity/AliasRequestTest.kt | 22 +- .../com/mparticle/identity/IdentityApiTest.kt | 131 +- .../MParticleIdentityClientImplTest.kt | 23 +- .../identity/MParticleUserDelegateTest.kt | 55 +- .../mparticle/identity/MParticleUserTest.kt | 307 ++-- .../mparticle/internal/AppStateManagerTest.kt | 92 +- .../internal/ApplicationContextWrapperTest.kt | 99 +- .../mparticle/internal/BaseMPMessageTest.kt | 59 +- .../mparticle/internal/ConfigManagerTest.kt | 228 +-- .../internal/DeviceAttributesTest.kt | 11 +- .../internal/KitFrameworkWrapperTest.kt | 726 +++++---- .../com/mparticle/internal/LoggerTest.kt | 43 +- .../com/mparticle/internal/MPUtilityTest.kt | 131 +- .../internal/MParticleApiClientImplTest.kt | 161 +- .../internal/MParticleJSInterfaceTest.kt | 85 +- .../mparticle/internal/MessageBatchTest.kt | 92 +- .../mparticle/internal/MessageHandlerTest.kt | 54 +- .../mparticle/internal/MessageManagerTest.kt | 346 +++-- .../mparticle/internal/UploadHandlerTest.kt | 348 +++-- .../listeners/InternalListenerManagerTest.kt | 4 +- .../networking/CustomAttributesTests.kt | 30 +- .../mparticle/networking/DomainMappingTest.kt | 36 +- .../networking/NetworkOptionsTest.kt | 79 +- .../com/mparticle/rokt/RoktOptionsTest.kt | 82 +- .../com/mparticle/kits/BaseKitOptionsTest.kt | 37 +- .../mparticle/kits/ConfiguredKitOptions.kt | 14 +- .../kits/DataplanBlockingUserTests.kt | 133 +- .../kits/GCMPushMessageForwardingTest.kt | 17 +- .../com/mparticle/kits/KitBatchingTest.kt | 42 +- .../com/mparticle/kits/KitManagerImplTests.kt | 37 +- .../kits/KnownUserKitsLifecycleTest.kt | 33 +- .../com/mparticle/kits/UpdateConfigTest.kt | 24 +- .../kits/testkits/AttributeListenerTestKit.kt | 22 +- .../mparticle/kits/testkits/BaseTestKit.kt | 10 +- .../kits/testkits/CommerceListenerTestKit.kt | 15 +- .../mparticle/kits/testkits/EventTestKit.kt | 14 +- .../kits/testkits/IdentityListenerTestKit.kt | 12 +- .../kits/testkits/ListenerTestKit.kt | 13 +- .../kits/testkits/PushListenerTestKit.kt | 17 +- .../testkits/UserAttributeListenerTestKit.kt | 32 +- .../com/mparticle/kits/KitManagerImpl.java | 10 +- .../com/mparticle/kits/MPSideloadedFilters.kt | 1 - .../com/mparticle/kits/MPSideloadedKit.kt | 29 +- .../com/mparticle/kits/DataplanFilter.kt | 209 +-- .../kotlin/com/mparticle/kits/KitOptions.kt | 13 +- .../mparticle/kits/DataplanFilterImplTest.kt | 244 +-- .../mparticle/kits/FilteredApiRequestTest.kt | 58 +- .../mparticle/kits/KitConfigurationTest.kt | 579 +++---- .../com/mparticle/kits/KitIntegrationTest.kt | 171 ++- .../com/mparticle/kits/KitManagerImplTest.kt | 1338 ++++++++++------- .../com/mparticle/kits/KitManagerTest.kt | 33 +- .../kits/mappings/CustomMappingTest.kt | 630 +++++--- .../com/mparticle/kits/sample_dataplan.json | 57 +- .../com/mparticle/kits/sample_dataplan2.json | 143 +- release.config.js | 86 +- scripts/install-start-emulator.sh | 38 +- scripts/kits/merge-updates.sh | 4 +- scripts/kits/update.sh | 8 +- scripts/release.sh | 2 +- scripts/startup_perf_tests.sh | 1 + .../google/firebase/iid/FirebaseInstanceId.kt | 7 +- .../testutils/CaptureLogcatOnFailingTest.java | 2 +- .../src/main/kotlin/com.mparticle/Utils.kt | 52 +- .../java/com/mparticle/MParticlePlugin.kt | 33 +- .../java/com/mparticle/MParticlePluginTest.kt | 31 +- .../main/java/com/mparticle/tooling/Config.kt | 27 +- .../mparticle/tooling/DataPlanningNodeApp.kt | 101 +- .../main/java/com/mparticle/tooling/Utils.kt | 42 +- .../com/mparticle/tooling/ValidationResult.kt | 84 +- .../java/com/mparticle/lints/Extensions.kt | 84 +- .../mparticle/lints/MParticleIssueRegistry.kt | 28 +- .../com/mparticle/lints/VariableCollector.kt | 44 +- .../lints/basedetectors/CallScanner.kt | 25 +- .../lints/detectors/DataplanDetector.kt | 184 +-- .../lints/detectors/MpApiDetectorKt.kt | 127 +- .../detectors/ReferrerReceiverDetector.java | 8 +- .../com/mparticle/lints/dtos/Constructor.kt | 17 +- .../com/mparticle/lints/dtos/Expression.kt | 6 +- .../com/mparticle/lints/dtos/MethodCall.kt | 37 +- .../com/mparticle/lints/dtos/StaticFactory.kt | 28 +- .../java/com/mparticle/lints/dtos/Value.kt | 17 +- .../java/com/mparticle/lints/Constants.kt | 7 +- .../mparticle/lints/DataplanDetectorTest.kt | 11 +- .../ValidationResultDeserializationTest.kt | 48 +- 208 files changed, 10559 insertions(+), 7893 deletions(-) create mode 100644 .trunk/.gitignore create mode 100644 .trunk/configs/.markdownlint.yaml create mode 100644 .trunk/configs/.shellcheckrc create mode 100644 .trunk/configs/.yamllint.yaml create mode 100644 .trunk/trunk.yaml diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 27f986cd3..86f162b79 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,14 +1,14 @@ version: 2 updates: - - package-ecosystem: gradle - directory: "/" - schedule: - interval: daily - target-branch: "chore/dependabot" - labels: ["dependabot"] - open-pull-requests-limit: 10 - ignore: - - dependency-name: "com.mparticle:android-core" - - dependency-name: "com.google.firebase:firebase-messaging" - commit-message: - prefix: "chore" + - package-ecosystem: gradle + directory: "/" + schedule: + interval: daily + target-branch: "chore/dependabot" + labels: ["dependabot"] + open-pull-requests-limit: 10 + ignore: + - dependency-name: "com.mparticle:android-core" + - dependency-name: "com.google.firebase:firebase-messaging" + commit-message: + prefix: "chore" diff --git a/.github/workflows/cross-platform-tests.yml b/.github/workflows/cross-platform-tests.yml index 195ebe30c..85fb4058c 100644 --- a/.github/workflows/cross-platform-tests.yml +++ b/.github/workflows/cross-platform-tests.yml @@ -1,28 +1,31 @@ name: "Cross Platform Tests" -on: - pull_request +on: pull_request + +permissions: + contents: read + pull-requests: read jobs: cross-platform-tests: timeout-minutes: 30 runs-on: ubuntu-latest steps: - name: "Checkout Cross Platform Tests Repo" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: repository: mParticle/crossplatform-sdk-tests - + - name: "Checkout Android SDK Branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: repository: ${{github.event.pull_request.head.repo.full_name}} ref: ${{github.head_ref}} path: .sdks/android - + - name: Gradle cache uses: gradle/gradle-build-action@842c587ad8aa4c68eeba24c396e15af4c2e9f30a #v2.9.0 - name: AVD cache - uses: actions/cache@v3 + uses: actions/cache@v4 id: avd-cache with: path: | @@ -45,7 +48,7 @@ jobs: sudo udevadm control --reload-rules sudo udevadm trigger --name-match=kvm - name: "Install JDK 17" - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: "zulu" java-version: "17" diff --git a/.github/workflows/daily.yml b/.github/workflows/daily.yml index fe322c4ac..ac168ba84 100644 --- a/.github/workflows/daily.yml +++ b/.github/workflows/daily.yml @@ -1,5 +1,6 @@ name: "Daily Cron" +# checkov:skip=CKV_GHA_7: This workflow requires dryRun parameter for release control on: # Allow workflow to be manually run from the GitHub UI workflow_dispatch: @@ -18,8 +19,12 @@ on: default: "development" type: string -jobs: +permissions: + contents: read + pull-requests: read + checks: write +jobs: confirm-public-repo: name: "Confirm android daily cron is run from public origin repo" runs-on: ubuntu-latest @@ -40,10 +45,10 @@ jobs: GIT_COMMITTER_EMAIL: developers@mparticle.com steps: - name: "Clone branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: repository: mparticle/mparticle-android-sdk - ref: ${{ inputs.branch_name }} + ref: developmentreq submodules: recursive - name: "Import GPG Key" uses: crazy-max/ghaction-import-gpg@82a020f1f7f605c65dd2449b392a52c3fcfef7ef #v6.0 @@ -64,67 +69,67 @@ jobs: - name: "Push kit updates to release branch" run: git push origin regression/${{ github.run_number }} -# instrumented-tests: -# name: "Instrumented Tests" -# timeout-minutes: 30 -# runs-on: ubuntu-latest -# needs: create-regression-branch -# steps: -# - name: "Checkout future release branch" -# uses: actions/checkout@v3 -# with: -# repository: mparticle/mparticle-android-sdk -# ref: regression/${{ github.run_number }} -# - name: "Install JDK 17" -# uses: actions/setup-java@v3 -# with: -# distribution: "zulu" -# java-version: "17" -# cache: "gradle" -# - name: "Run Instrumented Tests" -# uses: reactivecircus/android-emulator-runner@62dbb605bba737720e10b196cb4220d374026a6d #v2.33.0 -# with: -# api-level: 28 -# #script: ./gradlew :android-core:cAT :android-kit-base:cAT --stacktrace -# script: | -# #Disable benchmark tests as they do not work on emulators -# adb uninstall com.mparticle.kits.test; ./gradlew connectedCheck --stacktrace -# ./gradlew :android-core:cAT :android-kit-base:cAT -Pandroid.testInstrumentationRunnerArguments.androidx.benchmark.enabledRules=none -# - name: "Archive Instrumented Test Results" -# uses: actions/upload-artifact@v4 -# if: always() -# with: -# name: instrumented-test-results -# path: android-core/build/reports/androidTests/connected/** -# -# instrumented-orchestrator-tests: -# name: "Instrumented Orchestrator Tests" -# timeout-minutes: 30 -# runs-on: ubuntu-latest -# needs: create-regression-branch -# steps: -# - name: "Checkout Branch" -# uses: actions/checkout@v3 -# with: -# repository: mparticle/mparticle-android-sdk -# ref: regression/${{ github.run_number }} -# - name: "Install JDK 17" -# uses: actions/setup-java@v3 -# with: -# distribution: "zulu" -# java-version: "17" -# cache: "gradle" -# - name: "Run Instrumented Orchestrator Tests" -# uses: reactivecircus/android-emulator-runner@62dbb605bba737720e10b196cb4220d374026a6d #v2.33.0 -# with: -# api-level: 28 -# script: ./gradlew -Porchestrator=true :android-core:cAT --stacktrace -# - name: "Archive Instrumented Orchestrator Tests Results" -# uses: actions/upload-artifact@v4 -# if: always() -# with: -# name: "instrumented-orchestrator-tests-results" -# path: android-core/build/orchestrator/** + # instrumented-tests: + # name: "Instrumented Tests" + # timeout-minutes: 30 + # runs-on: ubuntu-latest + # needs: create-regression-branch + # steps: + # - name: "Checkout future release branch" + # uses: actions/checkout@v4 + # with: + # repository: mparticle/mparticle-android-sdk + # ref: regression/${{ github.run_number }} + # - name: "Install JDK 17" + # uses: actions/setup-java@v4 + # with: + # distribution: "zulu" + # java-version: "17" + # cache: "gradle" + # - name: "Run Instrumented Tests" + # uses: reactivecircus/android-emulator-runner@62dbb605bba737720e10b196cb4220d374026a6d #v2.33.0 + # with: + # api-level: 28 + # #script: ./gradlew :android-core:cAT :android-kit-base:cAT --stacktrace + # script: | + # #Disable benchmark tests as they do not work on emulators + # adb uninstall com.mparticle.kits.test; ./gradlew connectedCheck --stacktrace + # ./gradlew :android-core:cAT :android-kit-base:cAT -Pandroid.testInstrumentationRunnerArguments.androidx.benchmark.enabledRules=none + # - name: "Archive Instrumented Test Results" + # uses: actions/upload-artifact@v4 + # if: always() + # with: + # name: instrumented-test-results + # path: android-core/build/reports/androidTests/connected/** + # + # instrumented-orchestrator-tests: + # name: "Instrumented Orchestrator Tests" + # timeout-minutes: 30 + # runs-on: ubuntu-latest + # needs: create-regression-branch + # steps: + # - name: "Checkout Branch" + # uses: actions/checkout@v4 + # with: + # repository: mparticle/mparticle-android-sdk + # ref: regression/${{ github.run_number }} + # - name: "Install JDK 17" + # uses: actions/setup-java@v4 + # with: + # distribution: "zulu" + # java-version: "17" + # cache: "gradle" + # - name: "Run Instrumented Orchestrator Tests" + # uses: reactivecircus/android-emulator-runner@62dbb605bba737720e10b196cb4220d374026a6d #v2.33.0 + # with: + # api-level: 28 + # script: ./gradlew -Porchestrator=true :android-core:cAT --stacktrace + # - name: "Archive Instrumented Orchestrator Tests Results" + # uses: actions/upload-artifact@v4 + # if: always() + # with: + # name: "instrumented-orchestrator-tests-results" + # path: android-core/build/orchestrator/** unit-tests: name: "Unit Tests" @@ -133,12 +138,12 @@ jobs: needs: create-regression-branch steps: - name: "Checkout future release branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: repository: mparticle/mparticle-android-sdk ref: regression/${{ github.run_number }} - name: "Install JDK 17" - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: "zulu" java-version: "17" @@ -162,12 +167,12 @@ jobs: needs: create-regression-branch steps: - name: "Checkout Branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: ref: regression/${{ github.run_number }} submodules: recursive - name: "Install JDK 17" - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: "zulu" java-version: "17" @@ -198,12 +203,12 @@ jobs: needs: create-regression-branch steps: - name: "Checkout Branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: ref: regression/${{ github.run_number }} submodules: recursive - name: "Install JDK 17" - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: "zulu" java-version: "17" @@ -238,13 +243,13 @@ jobs: GIT_COMMITTER_EMAIL: developers@mparticle.com steps: - name: "Checkout future release branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: repository: mparticle/mparticle-android-sdk ref: regression/${{ github.run_number }} submodules: recursive - name: "Install JDK 17" - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: "zulu" java-version: "17" @@ -256,7 +261,7 @@ jobs: semantic-release-dryrun: name: "Test Semantic Release - Dry Run" - needs: [ unit-tests, lint-checks, kotlin-lint-checks, update-kits ] + needs: [unit-tests, lint-checks, kotlin-lint-checks, update-kits] runs-on: macos-latest env: GITHUB_TOKEN: ${{ secrets.MP_SEMANTIC_RELEASE_BOT }} @@ -266,7 +271,7 @@ jobs: GIT_COMMITTER_EMAIL: developers@mparticle.com steps: - name: "Checkout public main branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 ref: main @@ -274,7 +279,7 @@ jobs: run: | git pull origin regression/${{ github.run_number }} - name: "Semantic Release --dry-run" - if: ${{ inputs.dryRun }} == 'true' + if: inputs.dryRun == 'true' run: | npx \ -p lodash \ @@ -297,7 +302,7 @@ jobs: GIT_COMMITTER_EMAIL: developers@mparticle.com steps: - name: "Checkout repo" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 repository: ${{ github.repository }} diff --git a/.github/workflows/dependabot-automerge.yml b/.github/workflows/dependabot-automerge.yml index ba7c06811..5db2a7dc6 100644 --- a/.github/workflows/dependabot-automerge.yml +++ b/.github/workflows/dependabot-automerge.yml @@ -6,7 +6,12 @@ on: types: - completed +permissions: + contents: read + pull-requests: read + checks: write + jobs: automerge-dependabot: name: "Automerge Dependabot PR" - uses: mParticle/mparticle-workflows/.github/workflows/dependabot-automerge.yml@main \ No newline at end of file + uses: mParticle/mparticle-workflows/.github/workflows/dependabot-automerge.yml@main diff --git a/.github/workflows/dependabot-rebase-branch.yml b/.github/workflows/dependabot-rebase-branch.yml index 4b4c2b652..9c1abc276 100644 --- a/.github/workflows/dependabot-rebase-branch.yml +++ b/.github/workflows/dependabot-rebase-branch.yml @@ -6,6 +6,11 @@ on: - development workflow_dispatch: +permissions: + contents: read + pull-requests: read + checks: write + jobs: rebase-branch: name: "Rebase Development onto Dependabot Branch" diff --git a/.github/workflows/issue-autorespond-and-close.yml b/.github/workflows/issue-autorespond-and-close.yml index f1a6baa64..8abd27130 100644 --- a/.github/workflows/issue-autorespond-and-close.yml +++ b/.github/workflows/issue-autorespond-and-close.yml @@ -5,10 +5,14 @@ on: types: - opened +permissions: + contents: read + issues: write + jobs: auto-respond-and-close-issue: uses: mparticle/mparticle-workflows/.github/workflows/auto-respond-close-issue.yml@main with: issue_number: ${{ github.event.issue.number }} repository: ${{ github.repository }} - user_login: ${{ github.event.issue.user.login }} \ No newline at end of file + user_login: ${{ github.event.issue.user.login }} diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 4842834b1..32e408738 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -1,6 +1,6 @@ name: "Build and Test" -on: [ workflow_dispatch, pull_request ] +on: [workflow_dispatch, pull_request] concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} @@ -19,16 +19,16 @@ jobs: runs-on: ubuntu-latest steps: - name: "Checkout Branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: "Install JDK 17" - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: "zulu" java-version: "17" - name: Gradle cache uses: gradle/gradle-build-action@842c587ad8aa4c68eeba24c396e15af4c2e9f30a #v2.9.0 - name: AVD cache - uses: actions/cache@v3 + uses: actions/cache@v4 id: avd-cache with: path: | @@ -80,9 +80,9 @@ jobs: runs-on: ubuntu-latest steps: - name: "Checkout Branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: "Install JDK 17" - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: "zulu" java-version: "17" @@ -116,7 +116,7 @@ jobs: adb uninstall com.mparticle.kits.test || true adb uninstall com.mparticle.legacyTest || true adb uninstall com.mparticle.test || true - + ./gradlew connectedCheck --stacktrace ./gradlew -Porchestrator=true :android-core:cAT -Pandroid.testInstrumentationRunnerArguments.androidx.benchmark.enabledRules=none - name: "Archive Instrumented Orchestrator Tests Results" @@ -131,9 +131,9 @@ jobs: runs-on: ubuntu-latest steps: - name: "Checkout Branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: "Install JDK 17" - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: "zulu" java-version: "17" @@ -155,11 +155,11 @@ jobs: runs-on: macos-latest steps: - name: "Checkout Branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: submodules: recursive - name: "Install JDK 17" - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: "zulu" java-version: "17" @@ -178,11 +178,11 @@ jobs: runs-on: macos-latest steps: - name: "Checkout Branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: submodules: recursive - name: "Install JDK 17" - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: "zulu" java-version: "17" @@ -207,12 +207,12 @@ jobs: if: github.event_name == 'pull_request' steps: - name: "Checkout Branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: submodules: recursive fetch-depth: 0 - name: "Install JDK 17" - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: "zulu" java-version: "17" @@ -227,7 +227,15 @@ jobs: automerge-dependabot: name: "Save PR Number for Dependabot Automerge" - needs: [ instrumented-tests, instrumented-orchestrator-tests, unit-tests, lint-checks, kotlin-lint-checks, kit-compatibility-test ] + needs: + [ + instrumented-tests, + instrumented-orchestrator-tests, + unit-tests, + lint-checks, + kotlin-lint-checks, + kit-compatibility-test, + ] uses: mParticle/mparticle-workflows/.github/workflows/dependabot-save-pr-number.yml@main pr-notify: @@ -244,4 +252,3 @@ jobs: uses: ROKT/rokt-workflows/.github/workflows/oss_pr_opened_notification.yml@main secrets: gchat_webhook: ${{ secrets.GCHAT_PRS_WEBHOOK }} - diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 08f1803f2..caaf61f4e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,5 +1,6 @@ name: "Release SDK" +# checkov:skip=CKV_GHA_7: This workflow requires dryRun parameter for release control on: workflow_dispatch: inputs: @@ -8,6 +9,11 @@ on: required: true default: "true" +permissions: + contents: read + pull-requests: read + checks: write + jobs: # SDK release is done from public main branch. confirm-public-repo-main-branch: @@ -125,13 +131,13 @@ jobs: mavenSigningKeyPassword: ${{ secrets.MAVEN_CENTRAL_SIGNING_KEY_PASSWORD }} steps: - name: "Checkout release branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: repository: mparticle/mparticle-android-sdk ref: release/${{ github.run_number }} submodules: recursive - name: "Install JDK 17" - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: "zulu" java-version: "17" @@ -152,7 +158,7 @@ jobs: runs-on: ubuntu-latest steps: - name: "Checkout main branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 repository: ${{ github.repository }} diff --git a/.github/workflows/reusable-workflows.yml b/.github/workflows/reusable-workflows.yml index baf801570..1d6d9b7d1 100644 --- a/.github/workflows/reusable-workflows.yml +++ b/.github/workflows/reusable-workflows.yml @@ -3,6 +3,11 @@ name: "PR Reusable Checks" on: pull_request: +permissions: + contents: read + pull-requests: read + checks: write + jobs: pr-check-hadcoded-secrets: name: "Check PR for hardcoded secrets" diff --git a/.trunk/.gitignore b/.trunk/.gitignore new file mode 100644 index 000000000..15966d087 --- /dev/null +++ b/.trunk/.gitignore @@ -0,0 +1,9 @@ +*out +*logs +*actions +*notifications +*tools +plugins +user_trunk.yaml +user.yaml +tmp diff --git a/.trunk/configs/.markdownlint.yaml b/.trunk/configs/.markdownlint.yaml new file mode 100644 index 000000000..b40ee9d7a --- /dev/null +++ b/.trunk/configs/.markdownlint.yaml @@ -0,0 +1,2 @@ +# Prettier friendly markdownlint config (all formatting rules disabled) +extends: markdownlint/style/prettier diff --git a/.trunk/configs/.shellcheckrc b/.trunk/configs/.shellcheckrc new file mode 100644 index 000000000..8c7b1ada8 --- /dev/null +++ b/.trunk/configs/.shellcheckrc @@ -0,0 +1,7 @@ +enable=all +source-path=SCRIPTDIR +disable=SC2154 + +# If you're having issues with shellcheck following source, disable the errors via: +# disable=SC1090 +# disable=SC1091 diff --git a/.trunk/configs/.yamllint.yaml b/.trunk/configs/.yamllint.yaml new file mode 100644 index 000000000..184e251f8 --- /dev/null +++ b/.trunk/configs/.yamllint.yaml @@ -0,0 +1,7 @@ +rules: + quoted-strings: + required: only-when-needed + extra-allowed: ["{|}"] + key-duplicates: {} + octal-values: + forbid-implicit-octal: true diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml new file mode 100644 index 000000000..1c2f253f6 --- /dev/null +++ b/.trunk/trunk.yaml @@ -0,0 +1,55 @@ +# This file controls the behavior of Trunk: https://docs.trunk.io/cli +# To learn more about the format of this file, see https://docs.trunk.io/reference/trunk-yaml +version: 0.1 +cli: + version: 1.25.0 + sha256: + darwin_arm64: 2cff4f1cc63916db290359a058b88167beeac07a496682d9307a1804b498f225 + darwin_x86_64: d0153b87a7eba4cd7d09a048b97bd60ac3ac15352def2bc3599d548875823ed3 + linux_arm64: cc210d2185cf95bedbec06384be6ef342bdb7dcf3ff72dd08fe0e69859516887 + linux_x86_64: 3845ff76a70cebb10e61a267ff719ffdccfa3ef6d877d51870a2c62b79603ab9 + mingw_x86_64: 739f6aabc91d9ba4bce894314e01ab56d2c11b573c921b6f8caed6393c66c5f1 + windows_x86_64: d883930b487d12a47e2c42fb83391417db4c4254c7346720c11e6a947c305a2c +# Trunk provides extensibility via plugins. (https://docs.trunk.io/plugins) +plugins: + sources: + - id: trunk + ref: v1.7.2 + uri: https://github.com/trunk-io/plugins +# Many linters and tools depend on runtimes - configure them here. (https://docs.trunk.io/runtimes) +runtimes: + enabled: + - go@1.21.0 + - java@13.0.11 + - node@22.16.0 + - python@3.10.8 +# This is the section where you manage your linters. (https://docs.trunk.io/check/configuration) +lint: + enabled: + - actionlint@1.7.7 + - checkov@3.2.470 + - git-diff-check + - ktlint@1.7.1 + - markdownlint@0.45.0 + - prettier@3.6.2 + - shellcheck@0.11.0 + - shfmt@3.6.0 + - trufflehog@3.90.6 + disabled: + - yamllint + ignore: + - linters: [ALL] + paths: + - feature/legacy/** + - gradlew + - linters: + - checkov + paths: + - core/network/**/*.json +actions: + enabled: + - trunk-announce + - trunk-check-pre-push + - trunk-check-pre-push-always + - trunk-fmt-pre-commit + - trunk-upgrade-available diff --git a/ONBOARDING.md b/ONBOARDING.md index a1c934c58..8c265ded7 100644 --- a/ONBOARDING.md +++ b/ONBOARDING.md @@ -1,3 +1,5 @@ +# mParticle Android SDK Onboarding Guide + ## Getting Started ### Core SDK @@ -50,14 +52,14 @@ To set JAVA_HOME, do the following: In Windows: Right click My Computer and select Properties. On the Advanced tab, select Environment Variables, -and then edit *JAVA_HOME* to point to where the JDK software is located, for example, C:\Program +and then edit _JAVA_HOME_ to point to where the JDK software is located, for example, C:\Program Files\Java\jdk1.6.0_02 In Mac: Open the `.bash_profile` file and add the following -line: `export PATH="{PATH_TO_MY_JAVA}:$PATH"`, where *PATH_TO_MY_JAVA* is the file path for you JDK +line: `export PATH="{PATH_TO_MY_JAVA}:$PATH"`, where _PATH_TO_MY_JAVA_ is the file path for you JDK installation, for example, /usr/libexec/java_home -Lastly, edit the **Path** system variable and add a new variable *%JAVA_Home%\bin*. +Lastly, edit the **Path** system variable and add a new variable _%JAVA_Home%\bin_. Additionally If you have multiple JDKs downloaded make sure that your Gradle JDK matches Java Home. You can do this by going in Android Studio to: @@ -139,6 +141,6 @@ You can now work on the specific kits you need, test them and even contribute th ## Read More -* [Official Oracle JDK download Website](https://www.oracle.com/java/technologies/downloads/) -* [Adding a new SSH key to your Github account](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account) -* [Adding a new GPG key to your Github account](https://docs.github.com/en/authentication/managing-commit-signature-verification/adding-a-new-gpg-key-to-your-github-account) +- [Official Oracle JDK download Website](https://www.oracle.com/java/technologies/downloads/) +- [Adding a new SSH key to your Github account](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account) +- [Adding a new GPG key to your Github account](https://docs.github.com/en/authentication/managing-commit-signature-verification/adding-a-new-gpg-key-to-your-github-account) diff --git a/README.md b/README.md index 27392aba9..1ac5d8e95 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ - +# mParticle Android SDK # Android SDK +![mParticle logo](https://static.mparticle.com/sdk/mp_logo_black.svg) + +## Overview [![Maven Central Status](https://maven-badges.herokuapp.com/maven-central/com.mparticle/android-core/badge.svg?style=flat-square)](https://search.maven.org/#search%7Cga%7C1%7Cmparticle) @@ -37,46 +40,45 @@ dependencies { Kits are deployed as individual artifacts in Maven Central, and each has a dedicated repository if you'd like to view the source code. Review the table below to see if you need to include any kits: -Kit | Maven Artifact -----|--------- -[Adjust](https://github.com/mparticle-integrations/mparticle-android-integration-adjust) | [`android-adjust-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-adjust-kit%22) -[Adobe](https://github.com/mparticle-integrations/mparticle-android-integration-adobe) | [`android-adobe-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-adobe-kit%22) -[AdobeMedia](https://github.com/mparticle-integrations/mparticle-android-integration-adobe-media) | [`android-adobemedia-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-adobemedia-kit%22) -[Appboy](https://github.com/mparticle-integrations/mparticle-android-integration-appboy) | [`android-appboy-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-appboy-kit%22) -[AppsFlyer](https://github.com/mparticle-integrations/mparticle-android-integration-appsflyer) | [`android-appsflyer-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-appsflyer-kit%22) -[Apptentive](https://github.com/mparticle-integrations/mparticle-android-integration-apptentive) | [`android-apptentive-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-apptentive-kit%22) -[Apptimize](https://github.com/mparticle-integrations/mparticle-android-integration-apptimize) | [`android-apptimize-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-apptimize-kit%22) -[Apteligent](https://github.com/mparticle-integrations/mparticle-android-integration-apteligent) | [`android-apteligent-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-apteligent-kit%22) -[Blueshift](https://github.com/blueshift-labs/mparticle-android-integration-blueshift) | [`android-blueshift-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-blueshift-kit%22) -[Branch Metrics](https://github.com/mparticle-integrations/mparticle-android-integration-branch) | [`android-branch-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-branch-kit%22) -[Button](https://github.com/mparticle-integrations/mparticle-android-integration-button) | [`android-button-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-button-kit%22) -[CleverTap](https://github.com/mparticle-integrations/mparticle-android-integration-clevertap) | [`android-clevertap-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-clevertap-kit%22) -[ComScore](https://github.com/mparticle-integrations/mparticle-android-integration-comscore) | [`android-comscore-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-comscore-kit%22) -[Flurry](https://github.com/mparticle-integrations/mparticle-android-integration-flurry) | [`android-flurry-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-flurry-kit%22) -[ForeSee](https://github.com/mparticle-integrations/mparticle-android-integration-foresee) | [`android-foresee-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-foresee-kit%22) -[Google Analytics for Firebase](https://github.com/mparticle-integrations/mparticle-android-integration-google-analytics-firebase) | [`android-googleanalyticsfirebase-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-googleanalyticsfirebase-kit%22) -[Google Analytics for Firebase - GA4](https://github.com/mparticle-integrations/mparticle-android-integration-google-analytics-firebase-ga4) | [`android-googleanalyticsfirebasega4-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-googleanalyticsfirebasega4-kit%22) -[Iterable](https://github.com/mparticle-integrations/mparticle-android-integration-iterable) | [`android-iterable-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-iterable-kit%22) -[Kochava](https://github.com/mparticle-integrations/mparticle-android-integration-kochava) | [`android-kochava-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-kochava-kit%22) -[Leanplum](https://github.com/mparticle-integrations/mparticle-android-integration-leanplum) | [`android-leanplum-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-leanplum-kit%22) -[Localytics](https://github.com/mparticle-integrations/mparticle-android-integration-localytics) | [`android-localytics-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-localytics-kit%22) -[Neura](https://github.com/NeuraLabs/mparticle-android-integration-neura) | [`android-neura-kit`](https://search.maven.org/search?q=g:com.theneura%20AND%20a:android-mparticle-sdk) -[OneTrust](https://github.com/mparticle-integrations/mparticle-android-integration-onetrust) | [`android-onetrust-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-onetrust-kit%22) -[Optimizely](https://github.com/mparticle-integrations/mparticle-android-integration-optimizely) | [`android-optimizely-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-optimizely-kit%22) -[Pilgrim](https://github.com/mparticle-integrations/mparticle-android-integration-pilgrim) | [`android-pilgrim-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-pilgrim-kit%22) -[Radar](https://github.com/mparticle-integrations/mparticle-android-integration-radar) | [`android-radar-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-radar-kit%22) -[Responsys](https://github.com/mparticle-integrations/mparticle-android-integration-responsys) | [`android-responsys-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-responsys-kit%22) -[Reveal Mobile](https://github.com/mparticle-integrations/mparticle-android-integration-revealmobile) | [`android-revealmobile-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-revealmobile-kit%22) -[Singular](https://github.com/mparticle-integrations/mparticle-android-integration-singular) | [`android-singular-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-singular-kit%22) -[Skyhook](https://github.com/mparticle-integrations/mparticle-android-integration-skyhook) | [`android-skyhook-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-skyhook-kit%22) -[Swrve](https://github.com/swrve-services/mparticle-android-integration-swrve) | [`android-swrve-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-swrve-kit%22) -[Taplytics Mobile](https://github.com/mparticle-integrations/mparticle-android-integration-taplytics) | [`android-taplytics-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-taplytics-kit%22) -[Tune](https://github.com/mparticle-integrations/mparticle-android-integration-tune) | [`android-tune-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-tune-kit%22) -[Urban Airship](https://github.com/mparticle-integrations/mparticle-android-integration-urbanairship) | [`android-urbanairship-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-urbanairship-kit%22) -[Wootric](https://github.com/mparticle-integrations/mparticle-android-integration-wootric) | [`android-wootric-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-wootric-kit%22) - - -##### Google Play Services Ads +| Kit | Maven Artifact | +| -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [Adjust](https://github.com/mparticle-integrations/mparticle-android-integration-adjust) | [`android-adjust-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-adjust-kit%22) | +| [Adobe](https://github.com/mparticle-integrations/mparticle-android-integration-adobe) | [`android-adobe-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-adobe-kit%22) | +| [AdobeMedia](https://github.com/mparticle-integrations/mparticle-android-integration-adobe-media) | [`android-adobemedia-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-adobemedia-kit%22) | +| [Appboy](https://github.com/mparticle-integrations/mparticle-android-integration-appboy) | [`android-appboy-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-appboy-kit%22) | +| [AppsFlyer](https://github.com/mparticle-integrations/mparticle-android-integration-appsflyer) | [`android-appsflyer-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-appsflyer-kit%22) | +| [Apptentive](https://github.com/mparticle-integrations/mparticle-android-integration-apptentive) | [`android-apptentive-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-apptentive-kit%22) | +| [Apptimize](https://github.com/mparticle-integrations/mparticle-android-integration-apptimize) | [`android-apptimize-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-apptimize-kit%22) | +| [Apteligent](https://github.com/mparticle-integrations/mparticle-android-integration-apteligent) | [`android-apteligent-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-apteligent-kit%22) | +| [Blueshift](https://github.com/blueshift-labs/mparticle-android-integration-blueshift) | [`android-blueshift-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-blueshift-kit%22) | +| [Branch Metrics](https://github.com/mparticle-integrations/mparticle-android-integration-branch) | [`android-branch-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-branch-kit%22) | +| [Button](https://github.com/mparticle-integrations/mparticle-android-integration-button) | [`android-button-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-button-kit%22) | +| [CleverTap](https://github.com/mparticle-integrations/mparticle-android-integration-clevertap) | [`android-clevertap-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-clevertap-kit%22) | +| [ComScore](https://github.com/mparticle-integrations/mparticle-android-integration-comscore) | [`android-comscore-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-comscore-kit%22) | +| [Flurry](https://github.com/mparticle-integrations/mparticle-android-integration-flurry) | [`android-flurry-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-flurry-kit%22) | +| [ForeSee](https://github.com/mparticle-integrations/mparticle-android-integration-foresee) | [`android-foresee-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-foresee-kit%22) | +| [Google Analytics for Firebase](https://github.com/mparticle-integrations/mparticle-android-integration-google-analytics-firebase) | [`android-googleanalyticsfirebase-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-googleanalyticsfirebase-kit%22) | +| [Google Analytics for Firebase - GA4](https://github.com/mparticle-integrations/mparticle-android-integration-google-analytics-firebase-ga4) | [`android-googleanalyticsfirebasega4-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-googleanalyticsfirebasega4-kit%22) | +| [Iterable](https://github.com/mparticle-integrations/mparticle-android-integration-iterable) | [`android-iterable-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-iterable-kit%22) | +| [Kochava](https://github.com/mparticle-integrations/mparticle-android-integration-kochava) | [`android-kochava-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-kochava-kit%22) | +| [Leanplum](https://github.com/mparticle-integrations/mparticle-android-integration-leanplum) | [`android-leanplum-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-leanplum-kit%22) | +| [Localytics](https://github.com/mparticle-integrations/mparticle-android-integration-localytics) | [`android-localytics-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-localytics-kit%22) | +| [Neura](https://github.com/NeuraLabs/mparticle-android-integration-neura) | [`android-neura-kit`](https://search.maven.org/search?q=g:com.theneura%20AND%20a:android-mparticle-sdk) | +| [OneTrust](https://github.com/mparticle-integrations/mparticle-android-integration-onetrust) | [`android-onetrust-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-onetrust-kit%22) | +| [Optimizely](https://github.com/mparticle-integrations/mparticle-android-integration-optimizely) | [`android-optimizely-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-optimizely-kit%22) | +| [Pilgrim](https://github.com/mparticle-integrations/mparticle-android-integration-pilgrim) | [`android-pilgrim-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-pilgrim-kit%22) | +| [Radar](https://github.com/mparticle-integrations/mparticle-android-integration-radar) | [`android-radar-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-radar-kit%22) | +| [Responsys](https://github.com/mparticle-integrations/mparticle-android-integration-responsys) | [`android-responsys-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-responsys-kit%22) | +| [Reveal Mobile](https://github.com/mparticle-integrations/mparticle-android-integration-revealmobile) | [`android-revealmobile-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-revealmobile-kit%22) | +| [Singular](https://github.com/mparticle-integrations/mparticle-android-integration-singular) | [`android-singular-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-singular-kit%22) | +| [Skyhook](https://github.com/mparticle-integrations/mparticle-android-integration-skyhook) | [`android-skyhook-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-skyhook-kit%22) | +| [Swrve](https://github.com/swrve-services/mparticle-android-integration-swrve) | [`android-swrve-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-swrve-kit%22) | +| [Taplytics Mobile](https://github.com/mparticle-integrations/mparticle-android-integration-taplytics) | [`android-taplytics-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-taplytics-kit%22) | +| [Tune](https://github.com/mparticle-integrations/mparticle-android-integration-tune) | [`android-tune-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-tune-kit%22) | +| [Urban Airship](https://github.com/mparticle-integrations/mparticle-android-integration-urbanairship) | [`android-urbanairship-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-urbanairship-kit%22) | +| [Wootric](https://github.com/mparticle-integrations/mparticle-android-integration-wootric) | [`android-wootric-kit`](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mparticle%22%20AND%20a%3A%22android-wootric-kit%22) | + +### Google Play Services Ads The Google Play Services Ads framework is necessary to collect the Android Advertisting ID. AAID collection is required by all attribution and audience integrations, and many other integrations. Include the `-ads` artifact, a subset of [Google Play Services](https://developers.google.com/android/guides/setup): @@ -94,7 +96,7 @@ When apps target Android 13 or above, you will need to declare a Google Play ser For more information, please check out this link: [https://support.google.com/googleplay/android-developer/answer/6048248?hl=en](https://support.google.com/googleplay/android-developer/answer/6048248?hl=en) -##### Firebase Cloud Messaging +### Firebase Cloud Messaging mParticle supports several marketing automation and push messaging integrations. These require that mParticle register for an instance id using the Firebase Cloud Messaging framework: @@ -122,7 +124,6 @@ Simply add this dependency to your app and the mParticle SDK will detect it: implementation 'com.android.installreferrer:installreferrer:1+' ``` - ## Initialize the SDK 1. Grab your mParticle key and secret from [your workspace's dashboard](https://app.mparticle.com/setup/inputs/apps) and construct an `MParticleOptions` object. @@ -172,7 +173,7 @@ To enable Data Plan validation via linting, you must first download your Data Pl We recommended you add the Data Plan in your application's root level directory, but it can be located anywhere in your project directory since `dataPlanFile` accepts a relative file path -##### 1) Add the mParticle Gradle Plugin +### 1) Add the mParticle Gradle Plugin The next step is to configure the mParticle Gradle Plugin. In your root `build.gradle` use the following code to add the plugin dependency to your buildscript: @@ -194,7 +195,7 @@ Next, apply the plugin in your project-level `build.gradle` apply plugin: 'com.mparticle' ``` -##### 2) Configure the Plugin +### 2) Configure the Plugin Either configure the mParticle Plugin object @@ -207,21 +208,22 @@ mparticle { verbose false //{optional) defaults to "false" } ``` -*Or* + +### Or provide an `mp.config` config file in the project-level directory ```json { - "dataPlanFile": "./mp-dataplan.json", //(required) accepts filename or path - - "resultsFile": "./mp-dp-results.json", //(optional) accepts filename or path - "disabled": "false", //(optional) defaults to "false" - "verbose": false //(optional) defaults to "false" + "dataPlanFile": "./mp-dataplan.json", //(required) accepts filename or path + + "resultsFile": "./mp-dp-results.json", //(optional) accepts filename or path + "disabled": "false", //(optional) defaults to "false" + "verbose": false //(optional) defaults to "false" } ``` -##### 3) Install the mParticle CLI tool +### 3) Install the mParticle CLI tool Install the mParticle CLI. More documentation is available in it's [Github repo](https://git.corp.mparticle.com/mParticle/mparticle-cli) @@ -229,11 +231,11 @@ Install the mParticle CLI. More documentation is available in it's [Github repo] ./gradlew mpInstall ``` -##### 4) Viewing results +### 4) Viewing results > Note: Any changes to your dataplan are not applied until the Gradle Project Syncs -Validation Errors surface in multiple locations. +Validation Errors surface in multiple locations. - Individual Errors in the IDE as linting errors (red squiggly underlines), marking the offending code. - Written to your `resultsFile`, if you configured one in the mParticle plugin @@ -253,36 +255,32 @@ android { } ``` -##### General +### General -Lint Issue ID | Description ---------------|------- -MParticleVersionInconsistency | mParticle dependencies should, but do not have, matching versions -MParticleInitialization | mParticle.start() is not being called in Application.onCreate(), or may be being called multiple times -MParticleInstallRefReceiver | ReferrerReceiver is present, but has been removed +| Lint Issue ID | Description | +| ----------------------------- | ------------------------------------------------------------------------------------------------------ | +| MParticleVersionInconsistency | mParticle dependencies should, but do not have, matching versions | +| MParticleInitialization | mParticle.start() is not being called in Application.onCreate(), or may be being called multiple times | +| MParticleInstallRefReceiver | ReferrerReceiver is present, but has been removed | -##### Data Planning +### Data Planning -Lint Issue ID | Description ---------------|------- -DataplanViolation | DataPlan violations -NodeMissing | The required `node` dependency is not present in the $PATH variable -DataPlanMissing | Unable to fetch you DataPlan, could be a problem with credentials or network connectivity +| Lint Issue ID | Description | +| ----------------- | ----------------------------------------------------------------------------------------- | +| DataplanViolation | DataPlan violations | +| NodeMissing | The required `node` dependency is not present in the $PATH variable | +| DataPlanMissing | Unable to fetch you DataPlan, could be a problem with credentials or network connectivity | ## Downloading and configuring the mParticle Kits -For information on regarding this topic please read our [Onboarding Document](ONBOARDING.md) +For information on regarding this topic please read our [Onboarding Document](ONBOARDING.md) ## Read More Just by initializing the SDK you'll be set up to track user installs, engagement, and much more. Check out our doc site to learn how to add specific event tracking to your app. -* [SDK Documentation](https://docs.mparticle.com/developers/sdk/android/) -* [Javadocs](http://docs.mparticle.com/developers/sdk/android/javadocs/index.html) - -## Contributing - -We welcome contributions! If you're interested in contributing to the mParticle Android SDK, please read our [Contributing Guidelines](CONTRIBUTING.md). +- [SDK Documentation](https://docs.mparticle.com/developers/sdk/android/) +- [Javadocs](http://docs.mparticle.com/developers/sdk/android/javadocs/index.html) ## License diff --git a/android-core/src/androidTest/java/com/mparticle/internal/MParticleJSInterfaceITest.java b/android-core/src/androidTest/java/com/mparticle/internal/MParticleJSInterfaceITest.java index 3fb2094bd..507e3fc52 100644 --- a/android-core/src/androidTest/java/com/mparticle/internal/MParticleJSInterfaceITest.java +++ b/android-core/src/androidTest/java/com/mparticle/internal/MParticleJSInterfaceITest.java @@ -69,98 +69,98 @@ public class MParticleJSInterfaceITest extends BaseCleanStartedEachTest { private static String bridgeToken = new RandomUtils().getAlphaString(5); private static String bridgeVersion = "2"; - private static final String jsStartupMParticle = "window.mParticle = {\n" + - " config: {\n" + - " isDevelopmentMode: true,\n" + - " useCookieStorage: true,\n" + - " identifyRequest: {\n" + - " userIdentities: { email: 'email@example.com', customerid: '123456' }\n" + - " },\n " + - " requiredWebviewBridgeName: \"" + bridgeToken + "\",\n" + - " minWebviewBridgeVersion:\"" + bridgeVersion + "\"\n" + - " }\n" + - " };" + - " window.mParticle = window.mParticle || {};\n" + - " window.mParticle.config = window.mParticle.config || {};\n" + - " window.mParticle.config.rq = [];\n" + - " window.mParticle.ready = function (f) {\n" + - " window.mParticle.config.rq.push(f);\n" + - " console.log(\"pushed f\");\n" + + private static final String jsStartupMParticle = "window.mParticle = {\n" + " config: {\n" + " isDevelopmentMode: true,\n" + " useCookieStorage: true,\n" + " identifyRequest: {\n" + " userIdentities: { email: 'email@example.com', customerid: '123456' }\n" + " },\n " + " requiredWebviewBridgeName: \"" + bridgeToken + "\",\n" + " minWebviewBridgeVersion:\"" + bridgeVersion + "\"\n" + " }\n" + " };" + " window.mParticle = window.mParticle || {};\n" + " window.mParticle.config = window.mParticle.config || {};\n" + " window.mParticle.config.rq = [];\n" + " window.mParticle.ready = function (f) {\n" + " window.mParticle.config.rq.push(f);\n" + " console.log(\"pushed f\");\n" " };\n"; private static final String jsTestWrapper = - " mParticle.init();\n" + - " mParticle.isDebug = true;\n" + - " console.log(\"testing started\")\n " + - " window.mParticle.ready(function () {\n" + - " console.log(\"mparticle started in JS land\");\n" + - "%s\n" + + " mParticle.init();\n" + " mParticle.isDebug = true;\n" + " console.log(\"testing started\")\n " + " window.mParticle.ready(function () {\n" + " console.log(\"mparticle started in JS land\");\n" + "%s\n" " })\n"; - private static final String jsSetMpidFunction = "function getCookieDomain() {\n" + - " var rootDomain = getDomain(document, location.hostname);\n" + - " if (rootDomain === '') {\n" + - " return '';\n" + - " } else {\n" + - " return '.' + rootDomain;\n" + - " }\n" + - "}\n" + - "\n" + - "function getDomain(doc, locationHostname) {\n" + - " var i,\n" + - " testParts,\n" + - " mpTest = 'mptest=cookie',\n" + - " hostname = locationHostname.split('.');\n" + - " for (i = hostname.length - 1; i >= 0; i--) {\n" + - " testParts = hostname.slice(i).join('.');\n" + - " doc.cookie = mpTest + ';domain=.' + testParts + ';';\n" + - " if (doc.cookie.indexOf(mpTest) > -1){\n" + - " doc.cookie = mpTest.split('=')[0] + '=;domain=.' + testParts + ';expires=Thu, 01 Jan 1970 00:00:01 GMT;';\n" + - " return testParts;\n" + - " }\n" + - " }\n" + - " return '';\n" + - "}\n" + - "\n" + - "\n" + - "function setCookie(cname, data, raw) {\n" + - " var date = new Date(),\n" + - " expires = new Date(date.getTime() +\n" + - " (365 * 24 * 60 * 60 * 1000)).toGMTString(),\n" + - " domain, cookieDomain,\n" + - " value;\n" + - "\n" + - " value = data;\n" + - "\n" + - " cookieDomain = getCookieDomain();\n" + - "\n" + - " if (cookieDomain === '') {\n" + - " domain = '';\n" + - " } else {\n" + - " domain = ';domain=' + cookieDomain;\n" + - " }\n" + - "\n" + - "var cookie = encodeURIComponent(cname) + '=' + value +\n" + - " ';expires=' + expires;\n" + - " // +\n" + - " // ';path=/' + domain;\n" + - " console.log(\"SETTNG COOKIE: \" + cookie);\n" + - " window.document.cookie = cookie;\n" + - " console.log(\"RETRIEVING cookie: \" + window.document.cookie);\n" + + private static final String jsSetMpidFunction = "function getCookieDomain() {\n" + " var rootDomain = getDomain(document, location.hostname);\n" + " if (rootDomain === '') {\n" + " return '';\n" + " } else {\n" + " return '.' + rootDomain;\n" + " }\n" + "}\n" + "\n" + "function getDomain(doc, locationHostname) {\n" + " var i,\n" + " testParts,\n" + " mpTest = 'mptest=cookie',\n" + " hostname = locationHostname.split('.');\n" + " for (i = hostname.length - 1; i >= 0; i--) {\n" + " testParts = hostname.slice(i).join('.');\n" + " doc.cookie = mpTest + ';domain=.' + testParts + ';';\n" + " if (doc.cookie.indexOf(mpTest) > -1){\n" + " doc.cookie = mpTest.split('=')[0] + '=;domain=.' + testParts + ';expires=Thu, 01 Jan 1970 00:00:01 GMT;';\n" + " return testParts;\n" + " }\n" + " }\n" + " return '';\n" + "}\n" + "\n" + "\n" + "function setCookie(cname, data, raw) {\n" + " var date = new Date(),\n" + " expires = new Date(date.getTime() +\n" + " (365 * 24 * 60 * 60 * 1000)).toGMTString(),\n" + " domain, cookieDomain,\n" + " value;\n" + "\n" + " value = data;\n" + "\n" + " cookieDomain = getCookieDomain();\n" + "\n" + " if (cookieDomain === '') {\n" + " domain = '';\n" + " } else {\n" + " domain = ';domain=' + cookieDomain;\n" + " }\n" + "\n" + "var cookie = encodeURIComponent(cname) + '=' + value +\n" + " ';expires=' + expires;\n" + " // +\n" + " // ';path=/' + domain;\n" + " console.log(\"SETTNG COOKIE: \" + cookie);\n" + " window.document.cookie = cookie;\n" + " console.log(\"RETRIEVING cookie: \" + window.document.cookie);\n" "}"; - private static final String htmlWrapper = "\n" + - "\n" + - "\n" + - " \n" + - " Mocha Tests\n" + - "\n" + - "\n" + - "
\n" + - "" + - "\n" + + private static final String htmlWrapper = "\n" + "\n" + "\n" + " \n" + " Mocha Tests\n" + "\n" + "\n" + "
\n" + "" + "\n" ""; @BeforeClass @@ -170,16 +170,16 @@ public static void beforeClass() { InputStream inputStream = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(R.raw.mparticle_js_sdk); //add in all the basic configuration stuff the server would send with a production sdk fetch from the url jsSdk = new StringBuilder() - .append("window.mParticle = window.mParticle || {};;\n" + - "window.mParticle.config = window.mParticle.config || {};;\n" + - "window.mParticle.config.serviceUrl = 'jssdk.mparticle.com/v2/JS/';;\n" + - "window.mParticle.config.secureServiceUrl = 'jssdks.mparticle.com/v2/JS/';;\n" + - "window.mParticle.config.minWebviewBridgeVersion = 1;\n" + - "window.mParticle.config.aliasMaxWindow = 90;\n" + - "window.mParticle.config.kitConfigs = window.mParticle.config.kitConfigs || [];;\n" + + .append("window.mParticle = window.mParticle || {};;\n" + "window.mParticle.config = window.mParticle.config || {};;\n" + "window.mParticle.config.serviceUrl = 'jssdk.mparticle.com/v2/JS/';;\n" + "window.mParticle.config.secureServiceUrl = 'jssdks.mparticle.com/v2/JS/';;\n" + "window.mParticle.config.minWebviewBridgeVersion = 1;\n" + "window.mParticle.config.aliasMaxWindow = 90;\n" + "window.mParticle.config.kitConfigs = window.mParticle.config.kitConfigs || [];;\n" "window.mParticle.config.pixelConfigs = window.mParticle.config.pixelConfigs || [];;") .append(toString(inputStream)) - .append("window.mParticle.config.requestConfig = false;;\n" + + .append("window.mParticle.config.requestConfig = false;;\n" "mParticle.init(null, window.mParticle.config);;") .toString(); } else { @@ -312,9 +312,9 @@ public void setUserAttribute(String json) { public void testLogEvent() throws Exception { final JSONObject customAttributes = MPUtility.mapToJson(mRandomUtils.getRandomAttributes(10)); final JSONObject customFlagsJSON = MPUtility.mapToJson(getCustomFlags()); - String testJavascript = String.format("mParticle.logEvent('Play Movie Tapped',\n" + - " mParticle.EventType.Navigation,\n" + - " %s,\n" + + String testJavascript = String.format("mParticle.logEvent('Play Movie Tapped',\n" + " mParticle.EventType.Navigation,\n" + " %s,\n" " %s);", customAttributes.toString(4), customFlagsJSON.toString(4)); final MutableBoolean called = new MutableBoolean(false); final CountDownLatch latch = new MPLatch(2); @@ -369,22 +369,22 @@ public void logEvent(String json) { public void testLogCommerceEvent() throws Exception { final JSONObject customAttributes = MPUtility.mapToJson(mRandomUtils.getRandomAttributes(10)); final JSONObject customFlags = MPUtility.mapToJson(getCustomFlags()); - String testJavascript = String.format("// 1. Create the product\n" + - "var product = mParticle.eCommerce.createProduct(\n" + - " 'Double Room - Econ Rate', //\n" + - " 'econ-1', \n" + - " 100.00, \n" + - " 4\n" + - ");\n" + - "\n" + - "// 2. Summarize the transaction\n" + - "var transactionAttributes = {\n" + - " Id: 'foo-transaction-id',\n" + - " Revenue: 430.00,\n" + - " Tax: 30\n" + - "};\n" + - "\n" + - "// 3. Log the purchase event\n" + + String testJavascript = String.format("// 1. Create the product\n" + "var product = mParticle.eCommerce.createProduct(\n" + " 'Double Room - Econ Rate', //\n" + " 'econ-1', \n" + " 100.00, \n" + " 4\n" + ");\n" + "\n" + "// 2. Summarize the transaction\n" + "var transactionAttributes = {\n" + " Id: 'foo-transaction-id',\n" + " Revenue: 430.00,\n" + " Tax: 30\n" + "};\n" + "\n" + "// 3. Log the purchase event\n" "mParticle.eCommerce.logPurchase(transactionAttributes, product, true, %s, %s);", customAttributes.toString(4), customFlags); final MutableBoolean called = new MutableBoolean(false); diff --git a/android-core/src/androidTest/kotlin/com.mparticle/BatchCreationCallbackTests.kt b/android-core/src/androidTest/kotlin/com.mparticle/BatchCreationCallbackTests.kt index b2747c74a..1efe2dd76 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/BatchCreationCallbackTests.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/BatchCreationCallbackTests.kt @@ -12,28 +12,31 @@ import kotlin.test.assertNull import kotlin.test.assertTrue class BatchCreationCallbackTests : BaseCleanInstallEachTest() { - @Test fun testListenerNoChange() { var receivedBatch: JSONObject? = null - val options = MParticleOptions.builder(mContext) - .batchCreationListener { - receivedBatch = JSONObject(it.toString()) - it - } + val options = + MParticleOptions + .builder(mContext) + .batchCreationListener { + receivedBatch = JSONObject(it.toString()) + it + } startMParticle(options) MParticle.getInstance()?.apply { logEvent( - MPEvent.Builder("test event") - .build() + MPEvent + .Builder("test event") + .build(), ) upload() } mServer.waitForVerify( Matcher(mServer.Endpoints().eventsUrl).bodyMatch { - it.optJSONArray("msgs") + it + .optJSONArray("msgs") ?.toList() ?.filterIsInstance() ?.any { it.optString("n") == "test event" } @@ -47,7 +50,7 @@ class BatchCreationCallbackTests : BaseCleanInstallEachTest() { assertJsonEqual(it, receivedBatch) } } ?: false - } + }, ) } @@ -55,8 +58,10 @@ class BatchCreationCallbackTests : BaseCleanInstallEachTest() { fun testNullBatchCreationSENDwithoutModify() { val targetEventName = "should send without modified" - val options = MParticleOptions.builder(mContext) - .batchCreationListener(null) + val options = + MParticleOptions + .builder(mContext) + .batchCreationListener(null) startMParticle(options) MParticle.getInstance()?.apply { @@ -66,32 +71,39 @@ class BatchCreationCallbackTests : BaseCleanInstallEachTest() { mServer.waitForVerify( Matcher(mServer.Endpoints().eventsUrl).bodyMatch { - it.optJSONArray("msgs") + it + .optJSONArray("msgs") ?.toList() ?.filterIsInstance() ?.any { it.optString("n") == targetEventName && it.optString("mb").isNullOrEmpty() } ?: false - } + }, ) - mServer.Requests().events.any { - it.bodyJson.optJSONArray("msgs") - ?.toList() - ?.filterIsInstance() - ?.any { it.optString("n") == targetEventName && it.optString("mb").isNullOrEmpty() } - ?: false - }.let { - assertTrue { it } - } + mServer + .Requests() + .events + .any { + it.bodyJson + .optJSONArray("msgs") + ?.toList() + ?.filterIsInstance() + ?.any { it.optString("n") == targetEventName && it.optString("mb").isNullOrEmpty() } + ?: false + }.let { + assertTrue { it } + } } @Test fun testNullOnBatchCreatedShouldNOTsend() { val targetEventName = "should not send" - val options = MParticleOptions.builder(mContext) - .batchCreationListener { null } + val options = + MParticleOptions + .builder(mContext) + .batchCreationListener { null } startMParticle(options) MParticle.getInstance()?.apply { @@ -101,21 +113,26 @@ class BatchCreationCallbackTests : BaseCleanInstallEachTest() { mServer.waitForVerify( Matcher(mServer.Endpoints().eventsUrl).bodyMatch { - it.optJSONArray("msgs") + it + .optJSONArray("msgs") ?.toList() ?.filterIsInstance() ?.any { it.optString("n") == targetEventName } ?: false - } + }, ) - mServer.Requests().events.any { - it.bodyJson.optJSONArray("msgs") - ?.toList() - ?.filterIsInstance() - ?.any { it.optString("n") == targetEventName } ?: false - }.let { - assertFalse { it } - } + mServer + .Requests() + .events + .any { + it.bodyJson + .optJSONArray("msgs") + ?.toList() + ?.filterIsInstance() + ?.any { it.optString("n") == targetEventName } ?: false + }.let { + assertFalse { it } + } } @Test @@ -123,26 +140,30 @@ class BatchCreationCallbackTests : BaseCleanInstallEachTest() { var newBatch = JSONObject().put("the whole", "batch") val targetEventName = "should not send" - val options = MParticleOptions.builder(mContext) - .batchCreationListener { - it.optJSONArray("msgs") - ?.toList() - ?.filterIsInstance() - ?.any { it.optString("n") == targetEventName } - ?.let { result -> - if (result) { - JSONObject(newBatch.toString()) - } else { - it - } - } ?: it - } + val options = + MParticleOptions + .builder(mContext) + .batchCreationListener { + it + .optJSONArray("msgs") + ?.toList() + ?.filterIsInstance() + ?.any { it.optString("n") == targetEventName } + ?.let { result -> + if (result) { + JSONObject(newBatch.toString()) + } else { + it + } + } ?: it + } startMParticle(options) MParticle.getInstance()?.apply { logEvent( - MPEvent.Builder(targetEventName) - .build() + MPEvent + .Builder(targetEventName) + .build(), ) upload() } @@ -154,7 +175,7 @@ class BatchCreationCallbackTests : BaseCleanInstallEachTest() { assertTrue(modified.toString().toBooleanStrict()) } it.toString() == newBatch.toString() - } + }, ) // make sure the upload queue is cleared @@ -165,40 +186,48 @@ class BatchCreationCallbackTests : BaseCleanInstallEachTest() { mServer.waitForVerify( Matcher(mServer.Endpoints().eventsUrl).bodyMatch { - it.optJSONArray("msgs") + it + .optJSONArray("msgs") ?.toList() ?.filterIsInstance() ?.any { it.optString("n") == "test" } ?: false - } + }, ) - mServer.Requests().events.any { - it.bodyJson.optJSONArray("msgs") - ?.toList() - ?.filterIsInstance() - ?.any { it.optString("n") == targetEventName } ?: false - }.let { - assertFalse { it } - } + mServer + .Requests() + .events + .any { + it.bodyJson + .optJSONArray("msgs") + ?.toList() + ?.filterIsInstance() + ?.any { it.optString("n") == targetEventName } ?: false + }.let { + assertFalse { it } + } } @Test fun testListenerCrashes() { val targetEventName = "should send" - val options = MParticleOptions.builder(mContext) - .batchCreationListener { - it.optJSONArray("msgs") - ?.toList() - ?.filterIsInstance() - ?.any { it.optString("n") == targetEventName } - ?.let { result -> - if (result) { - throw RuntimeException() - } else { - it - } - } ?: it - } + val options = + MParticleOptions + .builder(mContext) + .batchCreationListener { + it + .optJSONArray("msgs") + ?.toList() + ?.filterIsInstance() + ?.any { it.optString("n") == targetEventName } + ?.let { result -> + if (result) { + throw RuntimeException() + } else { + it + } + } ?: it + } startMParticle(options) MParticle.getInstance()?.apply { @@ -214,21 +243,26 @@ class BatchCreationCallbackTests : BaseCleanInstallEachTest() { mServer.waitForVerify( Matcher(mServer.Endpoints().eventsUrl).bodyMatch { - it.optJSONArray("msgs") + it + .optJSONArray("msgs") ?.toList() ?.filterIsInstance() ?.any { it.optString("n") == "test" } ?: false - } + }, ) - mServer.Requests().events.any { - it.bodyJson.optJSONArray("msgs") - ?.toList() - ?.filterIsInstance() - ?.any { it.optString("n") == targetEventName } ?: false - }.let { - assertTrue { it } - } + mServer + .Requests() + .events + .any { + it.bodyJson + .optJSONArray("msgs") + ?.toList() + ?.filterIsInstance() + ?.any { it.optString("n") == targetEventName } ?: false + }.let { + assertTrue { it } + } } @Test @@ -241,7 +275,8 @@ class BatchCreationCallbackTests : BaseCleanInstallEachTest() { mServer.waitForVerify( Matcher(mServer.Endpoints().eventsUrl).bodyMatch { - it.optJSONArray("msgs") + it + .optJSONArray("msgs") ?.toList() ?.filterIsInstance() ?.any { it.optString("n") == "test" } @@ -250,7 +285,7 @@ class BatchCreationCallbackTests : BaseCleanInstallEachTest() { assertNull(it.opt(Constants.MessageKey.MODIFIED_BATCH)) } } ?: false - } + }, ) } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/DataplanTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/DataplanTest.kt index ac291b5d3..e3468b350 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/DataplanTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/DataplanTest.kt @@ -21,8 +21,9 @@ class DataplanTest : BaseCleanInstallEachTest() { @Throws(InterruptedException::class) fun noDataPlanTest() { startMParticle( - MParticleOptions.builder(mContext) - .dataplan(null, null) + MParticleOptions + .builder(mContext) + .dataplan(null, null), ) val messageCount = AndroidUtils.Mutable(0) val latch = MPLatch(1) @@ -39,9 +40,9 @@ class DataplanTest : BaseCleanInstallEachTest() { } catch (_: JSONException) { } false - } + }, ), - latch + latch, ) MParticle.getInstance()?.logEvent(testingUtils.randomMPEventRich) MParticle.getInstance()?.logEvent(testingUtils.randomMPEventRich) @@ -55,8 +56,9 @@ class DataplanTest : BaseCleanInstallEachTest() { @Throws(InterruptedException::class) fun dataplanPartialTest() { startMParticle( - MParticleOptions.builder(mContext) - .dataplan("plan1", null) + MParticleOptions + .builder(mContext) + .dataplan("plan1", null), ) val messageCount = AndroidUtils.Mutable(0) val latch = MPLatch(1) @@ -71,13 +73,13 @@ class DataplanTest : BaseCleanInstallEachTest() { dataplanContext.getJSONObject(Constants.MessageKey.DATA_PLAN_KEY) Assert.assertEquals( "plan1", - dataplanJSON.getString(Constants.MessageKey.DATA_PLAN_ID) + dataplanJSON.getString(Constants.MessageKey.DATA_PLAN_ID), ) TestCase.assertNull( dataplanJSON.optString( Constants.MessageKey.DATA_PLAN_VERSION, - null - ) + null, + ), ) messageCount.value += getMessageCount(bodyJson) if (messageCount.value == 3) { @@ -87,9 +89,9 @@ class DataplanTest : BaseCleanInstallEachTest() { } catch (_: JSONException) { } false - } + }, ), - latch + latch, ) MParticle.getInstance()?.logEvent(testingUtils.randomMPEventRich) MParticle.getInstance()?.logEvent(testingUtils.randomMPEventRich) @@ -103,8 +105,9 @@ class DataplanTest : BaseCleanInstallEachTest() { @Throws(InterruptedException::class) fun noDataPlanIdTest() { startMParticle( - MParticleOptions.builder(mContext) - .dataplan(null, 1) + MParticleOptions + .builder(mContext) + .dataplan(null, 1), ) val messageCount = AndroidUtils.Mutable(0) val latch = MPLatch(1) @@ -121,9 +124,9 @@ class DataplanTest : BaseCleanInstallEachTest() { } catch (_: JSONException) { } false - } + }, ), - latch + latch, ) MParticle.getInstance()?.logEvent(testingUtils.randomMPEventRich) MParticle.getInstance()?.logEvent(testingUtils.randomMPEventRich) @@ -137,8 +140,9 @@ class DataplanTest : BaseCleanInstallEachTest() { @Throws(InterruptedException::class) fun dataPlanSetTest() { startMParticle( - MParticleOptions.builder(mContext) - .dataplan("dataplan1", 1) + MParticleOptions + .builder(mContext) + .dataplan("dataplan1", 1), ) val messageCount = AndroidUtils.Mutable(0) val latch = MPLatch(1) @@ -153,11 +157,11 @@ class DataplanTest : BaseCleanInstallEachTest() { dataplanContext.getJSONObject(Constants.MessageKey.DATA_PLAN_KEY) Assert.assertEquals( "dataplan1", - dataplanJSON.getString(Constants.MessageKey.DATA_PLAN_ID) + dataplanJSON.getString(Constants.MessageKey.DATA_PLAN_ID), ) Assert.assertEquals( "1", - dataplanJSON.optString(Constants.MessageKey.DATA_PLAN_VERSION, "") + dataplanJSON.optString(Constants.MessageKey.DATA_PLAN_VERSION, ""), ) messageCount.value += getMessageCount(bodyJson) if (messageCount.value == 3) { @@ -168,9 +172,9 @@ class DataplanTest : BaseCleanInstallEachTest() { Assert.fail(ex.toString()) } false - } + }, ), - latch + latch, ) MParticle.getInstance()?.logEvent(testingUtils.randomMPEventRich) MParticle.getInstance()?.logEvent(testingUtils.randomMPEventRich) @@ -184,14 +188,16 @@ class DataplanTest : BaseCleanInstallEachTest() { @Throws(InterruptedException::class) fun dataplanChanged() { startMParticle( - MParticleOptions.builder(mContext) - .dataplan("dataplan1", 1) + MParticleOptions + .builder(mContext) + .dataplan("dataplan1", 1), ) val totalMessageCount = AndroidUtils.Mutable(0) val dataplan1MessageCount = AndroidUtils.Mutable(0) val dataplan2MessageCount = AndroidUtils.Mutable(0) val latch = MPLatch(1) - MockServer.getInstance() + MockServer + .getInstance() .waitForVerify( Matcher(mServer.Endpoints().eventsUrl).bodyMatch { bodyJson -> try { @@ -221,15 +227,16 @@ class DataplanTest : BaseCleanInstallEachTest() { } false }, - latch + latch, ) MParticle.getInstance()?.logEvent(testingUtils.randomMPEventRich) MParticle.getInstance()?.logEvent(testingUtils.randomMPEventRich) MParticle.getInstance()?.logEvent(testingUtils.randomMPEventRich) MParticle.setInstance(null) startMParticle( - MParticleOptions.builder(mContext) - .dataplan("dataplan1", 2) + MParticleOptions + .builder(mContext) + .dataplan("dataplan1", 2), ) MParticle.getInstance()?.logEvent(testingUtils.randomMPEventRich) MParticle.getInstance()?.logEvent(testingUtils.randomMPEventRich) diff --git a/android-core/src/androidTest/kotlin/com.mparticle/MPUserTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/MPUserTest.kt index dce918116..663adecdb 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/MPUserTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/MPUserTest.kt @@ -8,7 +8,6 @@ import kotlin.test.assertNotNull import kotlin.test.assertTrue class MPUserTest : BaseCleanStartedEachTest() { - @Test fun testGetAttributeSyncWithAndroidHack() { MParticle.getInstance()!!.Identity().currentUser!!.apply { @@ -35,40 +34,44 @@ class MPUserTest : BaseCleanStartedEachTest() { this.userAttributes.put("fooNull", null) android_test_hack() - getUserAttributes(object : UserAttributeListener { - override fun onUserAttributesReceived( - userAttributes: Map?, - userAttributeLists: Map>?, - mpid: Long? - ) { - assertNotNull(userAttributes) - assertEquals(6, userAttributes.size) - assertEquals("bar", userAttributes["foo"]) - assertEquals("123", userAttributes["fooInt"]) - assertEquals("12345", userAttributes["fooLong"]) - assertEquals("10.15", userAttributes["fooDouble"]) - assertEquals("-10", userAttributes["fooNegInt"]) - assertEquals("-1010", userAttributes["fooNegLong"]) - assertEquals(null, userAttributes["fooNull"]) - } - }) - - getUserAttributes(object : TypedUserAttributeListener { - override fun onUserAttributesReceived( - userAttributes: Map, - userAttributeLists: Map?>, - mpid: Long - ) { - assertEquals(6, userAttributes.size) - assertEquals("bar", userAttributes["foo"]) - assertEquals(123, userAttributes["fooInt"]) - assertEquals(12345, userAttributes["fooLong"]) - assertEquals(10.15, userAttributes["fooDouble"]) - assertEquals(-10, userAttributes["fooNegInt"]) - assertEquals(-1010, userAttributes["fooNegLong"]) - assertEquals(null, userAttributes["fooNull"]) - } - }) + getUserAttributes( + object : UserAttributeListener { + override fun onUserAttributesReceived( + userAttributes: Map?, + userAttributeLists: Map>?, + mpid: Long?, + ) { + assertNotNull(userAttributes) + assertEquals(6, userAttributes.size) + assertEquals("bar", userAttributes["foo"]) + assertEquals("123", userAttributes["fooInt"]) + assertEquals("12345", userAttributes["fooLong"]) + assertEquals("10.15", userAttributes["fooDouble"]) + assertEquals("-10", userAttributes["fooNegInt"]) + assertEquals("-1010", userAttributes["fooNegLong"]) + assertEquals(null, userAttributes["fooNull"]) + } + }, + ) + + getUserAttributes( + object : TypedUserAttributeListener { + override fun onUserAttributesReceived( + userAttributes: Map, + userAttributeLists: Map?>, + mpid: Long, + ) { + assertEquals(6, userAttributes.size) + assertEquals("bar", userAttributes["foo"]) + assertEquals(123, userAttributes["fooInt"]) + assertEquals(12345, userAttributes["fooLong"]) + assertEquals(10.15, userAttributes["fooDouble"]) + assertEquals(-10, userAttributes["fooNegInt"]) + assertEquals(-1010, userAttributes["fooNegLong"]) + assertEquals(null, userAttributes["fooNull"]) + } + }, + ) } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/MParticleOptionsTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/MParticleOptionsTest.kt index dae8615ca..826b3139b 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/MParticleOptionsTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/MParticleOptionsTest.kt @@ -53,7 +53,8 @@ class MParticleOptionsTest : BaseAbstractTest() { clearStoredPreferences() thrown = false try { - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .credentials("", "") .build() } catch (ex: IllegalArgumentException) { @@ -63,7 +64,8 @@ class MParticleOptionsTest : BaseAbstractTest() { clearStoredPreferences() thrown = false try { - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .credentials("key", "") .build() } catch (ex: IllegalArgumentException) { @@ -73,7 +75,8 @@ class MParticleOptionsTest : BaseAbstractTest() { clearStoredPreferences() thrown = false try { - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .credentials("", "key") .build() } catch (ex: IllegalArgumentException) { @@ -92,7 +95,8 @@ class MParticleOptionsTest : BaseAbstractTest() { Assert.fail("MParticleOptions should build without credentials in a Production environment") } try { - MParticleOptions.builder(mProductionContext) + MParticleOptions + .builder(mProductionContext) .credentials("", "") .build() } catch (ex: IllegalArgumentException) { @@ -108,7 +112,10 @@ class MParticleOptionsTest : BaseAbstractTest() { .commit() } - private fun setStoredPreference(apiKey: String, apiSecret: String) { + private fun setStoredPreference( + apiKey: String, + apiSecret: String, + ) { credentialsPreferences .edit() .putString(Constants.PrefKeys.API_KEY, apiKey) @@ -125,13 +132,25 @@ class MParticleOptionsTest : BaseAbstractTest() { val key = UUID.randomUUID().toString() val secret = UUID.randomUUID().toString() startMParticle( - MParticleOptions.builder(mProductionContext) - .credentials(key, secret) + MParticleOptions + .builder(mProductionContext) + .credentials(key, secret), ) - Assert.assertEquals(MParticle.getInstance()?.mInternal?.configManager?.apiKey, key) Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.apiSecret, - secret + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.apiKey, + key, + ) + Assert.assertEquals( + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.apiSecret, + secret, ) } @@ -149,8 +168,9 @@ class MParticleOptionsTest : BaseAbstractTest() { // test androidIdDisabled == true MParticle.setInstance(null) startMParticle( - MParticleOptions.builder(mContext) - .androidIdDisabled(true) + MParticleOptions + .builder(mContext) + .androidIdDisabled(true), ) Assert.assertFalse(MParticle.isAndroidIdEnabled()) Assert.assertTrue(MParticle.isAndroidIdDisabled()) @@ -159,8 +179,9 @@ class MParticleOptionsTest : BaseAbstractTest() { // test androidIdEnabled == false MParticle.setInstance(null) startMParticle( - MParticleOptions.builder(mContext) - .androidIdEnabled(false) + MParticleOptions + .builder(mContext) + .androidIdEnabled(false), ) Assert.assertFalse(MParticle.isAndroidIdEnabled()) Assert.assertTrue(MParticle.isAndroidIdDisabled()) @@ -168,16 +189,18 @@ class MParticleOptionsTest : BaseAbstractTest() { // test androidIdDisabled == false startMParticle( - MParticleOptions.builder(mContext) - .androidIdDisabled(false) + MParticleOptions + .builder(mContext) + .androidIdDisabled(false), ) Assert.assertTrue(MParticle.isAndroidIdEnabled()) Assert.assertFalse(MParticle.isAndroidIdDisabled()) // test androidIdEnabled == true startMParticle( - MParticleOptions.builder(mContext) - .androidIdEnabled(true) + MParticleOptions + .builder(mContext) + .androidIdEnabled(true), ) Assert.assertTrue(MParticle.isAndroidIdEnabled()) Assert.assertFalse(MParticle.isAndroidIdDisabled()) @@ -190,14 +213,16 @@ class MParticleOptionsTest : BaseAbstractTest() { MParticle.getInstance()?.let { Assert.assertFalse(it.isDevicePerformanceMetricsDisabled) } MParticle.setInstance(null) startMParticle( - MParticleOptions.builder(mContext) - .devicePerformanceMetricsDisabled(false) + MParticleOptions + .builder(mContext) + .devicePerformanceMetricsDisabled(false), ) MParticle.getInstance()?.let { Assert.assertFalse(it.isDevicePerformanceMetricsDisabled) } MParticle.setInstance(null) startMParticle( - MParticleOptions.builder(mContext) - .devicePerformanceMetricsDisabled(true) + MParticleOptions + .builder(mContext) + .devicePerformanceMetricsDisabled(true), ) MParticle.getInstance()?.let { Assert.assertTrue(it.isDevicePerformanceMetricsDisabled) } MParticle.setInstance(null) @@ -209,12 +234,13 @@ class MParticleOptionsTest : BaseAbstractTest() { startMParticle() Assert.assertEquals(Logger.getMinLogLevel(), Logger.DEFAULT_MIN_LOG_LEVEL) startMParticle( - MParticleOptions.builder(mProductionContext) - .logLevel(MParticle.LogLevel.VERBOSE) + MParticleOptions + .builder(mProductionContext) + .logLevel(MParticle.LogLevel.VERBOSE), ) Assert.assertEquals(Logger.getMinLogLevel(), MParticle.LogLevel.VERBOSE) startMParticle( - MParticleOptions.builder(mProductionContext).logLevel(MParticle.LogLevel.ERROR) + MParticleOptions.builder(mProductionContext).logLevel(MParticle.LogLevel.ERROR), ) Assert.assertEquals(Logger.getMinLogLevel(), MParticle.LogLevel.ERROR) } @@ -225,11 +251,12 @@ class MParticleOptionsTest : BaseAbstractTest() { startMParticle() Assert.assertEquals( MParticle.getInstance()?.environment, - MParticle.Environment.Development + MParticle.Environment.Development, ) startMParticle( - MParticleOptions.builder(mProductionContext) - .environment(MParticle.Environment.Production) + MParticleOptions + .builder(mProductionContext) + .environment(MParticle.Environment.Production), ) Assert.assertEquals(MParticle.getInstance()?.environment, MParticle.Environment.Production) MParticle.setInstance(null) @@ -237,8 +264,9 @@ class MParticleOptionsTest : BaseAbstractTest() { val debuggable = MPUtility.isAppDebuggable(productionContext) Assert.assertFalse(debuggable) startMParticle( - MParticleOptions.builder(productionContext) - .environment(MParticle.Environment.AutoDetect) + MParticleOptions + .builder(productionContext) + .environment(MParticle.Environment.AutoDetect), ) Assert.assertEquals(MParticle.getInstance()?.environment, MParticle.Environment.Production) MParticle.setInstance(null) @@ -247,32 +275,36 @@ class MParticleOptionsTest : BaseAbstractTest() { @Test @Throws(Exception::class) fun testEnableUncaughtExceptionLogging() { - val options = MParticleOptions.builder(mProductionContext) - .credentials("key", "secret") - .build() + val options = + MParticleOptions + .builder(mProductionContext) + .credentials("key", "secret") + .build() MParticle.start(options) MParticle.getInstance()?.mInternal?.configManager?.let { Assert.assertFalse( - it.logUnhandledExceptions + it.logUnhandledExceptions, ) } MParticle.setInstance(null) startMParticle( - MParticleOptions.builder(mProductionContext) - .enableUncaughtExceptionLogging(true) + MParticleOptions + .builder(mProductionContext) + .enableUncaughtExceptionLogging(true), ) MParticle.getInstance()?.mInternal?.configManager?.logUnhandledExceptions?.let { Assert.assertTrue( - it + it, ) } startMParticle( - MParticleOptions.builder(mProductionContext) - .enableUncaughtExceptionLogging(false) + MParticleOptions + .builder(mProductionContext) + .enableUncaughtExceptionLogging(false), ) MParticle.getInstance()?.mInternal?.configManager?.let { Assert.assertFalse( - it.logUnhandledExceptions + it.logUnhandledExceptions, ) } MParticle.setInstance(null) @@ -283,32 +315,50 @@ class MParticleOptionsTest : BaseAbstractTest() { fun testSessionTimeout() { startMParticle() Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.sessionTimeout, - 60000 + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.sessionTimeout, + 60000, ) startMParticle( - MParticleOptions.builder(mProductionContext) - .sessionTimeout(-123) + MParticleOptions + .builder(mProductionContext) + .sessionTimeout(-123), ) Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.sessionTimeout, - 60000 + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.sessionTimeout, + 60000, ) MParticle.setInstance(null) startMParticle( - MParticleOptions.builder(mProductionContext) - .sessionTimeout(123) + MParticleOptions + .builder(mProductionContext) + .sessionTimeout(123), ) Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.sessionTimeout, - 123000 + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.sessionTimeout, + 123000, ) // make sure it resets if the session timeout is not specified startMParticle() Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.sessionTimeout, - 60000 + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.sessionTimeout, + 60000, ) MParticle.setInstance(null) } @@ -319,32 +369,35 @@ class MParticleOptionsTest : BaseAbstractTest() { startMParticle() Assert.assertEquals( AccessUtils.getInstallType(MParticle.getInstance()?.mMessageManager), - MParticle.InstallType.AutoDetect + MParticle.InstallType.AutoDetect, ) MParticle.setInstance(null) startMParticle( - MParticleOptions.builder(mProductionContext) - .installType(MParticle.InstallType.KnownInstall) + MParticleOptions + .builder(mProductionContext) + .installType(MParticle.InstallType.KnownInstall), ) Assert.assertEquals( AccessUtils.getInstallType(MParticle.getInstance()?.mMessageManager), - MParticle.InstallType.KnownInstall + MParticle.InstallType.KnownInstall, ) startMParticle( - MParticleOptions.builder(mProductionContext) - .installType(MParticle.InstallType.KnownUpgrade) + MParticleOptions + .builder(mProductionContext) + .installType(MParticle.InstallType.KnownUpgrade), ) Assert.assertEquals( AccessUtils.getInstallType(MParticle.getInstance()?.mMessageManager), - MParticle.InstallType.KnownUpgrade + MParticle.InstallType.KnownUpgrade, ) startMParticle( - MParticleOptions.builder(mProductionContext) - .installType(MParticle.InstallType.AutoDetect) + MParticleOptions + .builder(mProductionContext) + .installType(MParticle.InstallType.AutoDetect), ) Assert.assertEquals( AccessUtils.getInstallType(MParticle.getInstance()?.mMessageManager), - MParticle.InstallType.AutoDetect + MParticle.InstallType.AutoDetect, ) MParticle.setInstance(null) } @@ -355,34 +408,52 @@ class MParticleOptionsTest : BaseAbstractTest() { // default upload interval for production startMParticle() Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.uploadInterval, - 10000L + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.uploadInterval, + 10000L, ) MParticle.setInstance(null) // default upload interval for production startMParticle(MParticleOptions.builder(mProductionContext)) Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.uploadInterval, - 600000L + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.uploadInterval, + 600000L, ) MParticle.setInstance(null) startMParticle( - MParticleOptions.builder(mProductionContext) - .uploadInterval(123) + MParticleOptions + .builder(mProductionContext) + .uploadInterval(123), ) Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.uploadInterval, - 123000L + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.uploadInterval, + 123000L, ) MParticle.setInstance(null) startMParticle( - MParticleOptions.builder(mProductionContext) - .uploadInterval(-123) + MParticleOptions + .builder(mProductionContext) + .uploadInterval(-123), ) Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.uploadInterval, - 600000L + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.uploadInterval, + 600000L, ) MParticle.setInstance(null) } @@ -393,17 +464,22 @@ class MParticleOptionsTest : BaseAbstractTest() { startMParticle() Assert.assertNull(MParticle.getInstance()?.attributionListener) startMParticle( - MParticleOptions.builder(mContext) - .attributionListener(object : AttributionListener { - override fun onResult(result: AttributionResult) {} - override fun onError(error: AttributionError) {} - }) + MParticleOptions + .builder(mContext) + .attributionListener( + object : AttributionListener { + override fun onResult(result: AttributionResult) {} + + override fun onError(error: AttributionError) {} + }, + ), ) Assert.assertNotNull(MParticle.getInstance()?.attributionListener) MParticle.setInstance(null) startMParticle( - MParticleOptions.builder(mContext) - .attributionListener(null) + MParticleOptions + .builder(mContext) + .attributionListener(null), ) Assert.assertNull(MParticle.getInstance()?.attributionListener) } @@ -414,15 +490,17 @@ class MParticleOptionsTest : BaseAbstractTest() { val called = AndroidUtils.Mutable(false) val latch: CountDownLatch = MPLatch(1) startMParticle( - MParticleOptions.builder(mContext) - .operatingSystem(MParticle.OperatingSystem.FIRE_OS) + MParticleOptions + .builder(mContext) + .operatingSystem(MParticle.OperatingSystem.FIRE_OS), ) mServer.waitForVerify(Matcher(mServer.Endpoints().eventsUrl)) { request -> Assert.assertEquals("FireTV", request.bodyJson.optJSONObject("di")?.optString("dp")) called.value = true latch.countDown() } - MParticle.getInstance() + MParticle + .getInstance() ?.logEvent(MPEvent.Builder("event name", MParticle.EventType.Location).build()) MParticle.getInstance()?.upload() latch.await() @@ -440,7 +518,8 @@ class MParticleOptionsTest : BaseAbstractTest() { called.value = true latch1.countDown() } - MParticle.getInstance() + MParticle + .getInstance() ?.logEvent(MPEvent.Builder("event name", MParticle.EventType.Location).build()) MParticle.getInstance()?.upload() latch1.await() @@ -454,15 +533,17 @@ class MParticleOptionsTest : BaseAbstractTest() { @Throws(InterruptedException::class) fun testLocationTracking() { startMParticle( - MParticleOptions.builder(mContext) - .locationTrackingDisabled() + MParticleOptions + .builder(mContext) + .locationTrackingDisabled(), ) MParticle.getInstance()?.let { Assert.assertFalse(it.isLocationTrackingEnabled) } MParticle.setInstance(null) Assert.assertNull(MParticle.getInstance()) startMParticle( - MParticleOptions.builder(mContext) - .locationTrackingEnabled("passive", 100, 20) + MParticleOptions + .builder(mContext) + .locationTrackingEnabled("passive", 100, 20), ) MParticle.getInstance()?.let { Assert.assertTrue(it.isLocationTrackingEnabled) } MParticle.setInstance(null) @@ -475,117 +556,170 @@ class MParticleOptionsTest : BaseAbstractTest() { @Throws(InterruptedException::class) fun testTimeout() { startMParticle( - MParticleOptions.builder(mProductionContext) - .identityConnectionTimeout(-123) + MParticleOptions + .builder(mProductionContext) + .identityConnectionTimeout(-123), ) Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.identityConnectionTimeout, - (ConfigManager.DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000) + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.identityConnectionTimeout, + (ConfigManager.DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000), ) Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.connectionTimeout, - (ConfigManager.DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000) + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.connectionTimeout, + (ConfigManager.DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000), ) MParticle.setInstance(null) startMParticle( - MParticleOptions.builder(mProductionContext) - .identityConnectionTimeout(0) + MParticleOptions + .builder(mProductionContext) + .identityConnectionTimeout(0), ) Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.identityConnectionTimeout, - (ConfigManager.DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000) + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.identityConnectionTimeout, + (ConfigManager.DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000), ) Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.connectionTimeout, - (ConfigManager.DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000) + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.connectionTimeout, + (ConfigManager.DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000), ) MParticle.setInstance(null) startMParticle( - MParticleOptions.builder(mProductionContext) - .identityConnectionTimeout(123) + MParticleOptions + .builder(mProductionContext) + .identityConnectionTimeout(123), ) Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.identityConnectionTimeout, - 123000 + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.identityConnectionTimeout, + 123000, ) Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.connectionTimeout, - (ConfigManager.DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000) + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.connectionTimeout, + (ConfigManager.DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000), ) MParticle.setInstance(null) startMParticle(MParticleOptions.builder(mProductionContext)) Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.identityConnectionTimeout, - (ConfigManager.DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000) + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.identityConnectionTimeout, + (ConfigManager.DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000), ) Assert.assertEquals( - MParticle.getInstance()?.mInternal?.configManager?.connectionTimeout, - (ConfigManager.DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000) + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.connectionTimeout, + (ConfigManager.DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000), ) } @Test fun testNetworkOptions() { - val options = MParticleOptions.builder(mProductionContext) - .credentials("key", "secret") - .build() + val options = + MParticleOptions + .builder(mProductionContext) + .credentials("key", "secret") + .build() Assert.assertTrue( com.mparticle.networking.AccessUtils.equals( options.networkOptions, - com.mparticle.networking.AccessUtils.defaultNetworkOptions - ) + com.mparticle.networking.AccessUtils.defaultNetworkOptions, + ), ) } @Test fun testConfigStaleness() { // nothing set, should return null - var options = MParticleOptions.builder(mContext) - .credentials("key", "secret") - .build() + var options = + MParticleOptions + .builder(mContext) + .credentials("key", "secret") + .build() Assert.assertNull(options.configMaxAge) // 0 should return 0 - options = MParticleOptions.builder(mContext) - .credentials("key", "secret") - .configMaxAgeSeconds(0) - .build() + options = + MParticleOptions + .builder(mContext) + .credentials("key", "secret") + .configMaxAgeSeconds(0) + .build() Assert.assertEquals(0, options.configMaxAge) // positive number should return positive number val testValue = Math.abs(ran.nextInt()) - options = MParticleOptions.builder(mContext) - .credentials("key", "secret") - .configMaxAgeSeconds(testValue) - .build() + options = + MParticleOptions + .builder(mContext) + .credentials("key", "secret") + .configMaxAgeSeconds(testValue) + .build() Assert.assertEquals(testValue, options.configMaxAge) // negative number should get thrown out and return null - options = MParticleOptions.builder(mContext) - .credentials("key", "secret") - .configMaxAgeSeconds(-5) - .build() + options = + MParticleOptions + .builder(mContext) + .credentials("key", "secret") + .configMaxAgeSeconds(-5) + .build() Assert.assertNull(options.configMaxAge) } @Test fun testAndroidIdLogMessage() { val infoLogs = ArrayList() - Logger.setLogHandler(object : DefaultLogHandler() { - override fun log(priority: MParticle.LogLevel, error: Throwable?, messages: String) { - super.log(priority, error, messages) - if (priority == MParticle.LogLevel.INFO) { - infoLogs.add(messages) + Logger.setLogHandler( + object : DefaultLogHandler() { + override fun log( + priority: MParticle.LogLevel, + error: Throwable?, + messages: String, + ) { + super.log(priority, error, messages) + if (priority == MParticle.LogLevel.INFO) { + infoLogs.add(messages) + } } - } - }) - MParticleOptions.builder(mContext) + }, + ) + MParticleOptions + .builder(mContext) .credentials("this", "that") .androidIdDisabled(true) .build() Assert.assertTrue(infoLogs.contains("ANDROID_ID will not be collected based on MParticleOptions settings")) infoLogs.clear() - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .credentials("this", "that") .androidIdDisabled(false) .build() @@ -593,7 +727,8 @@ class MParticleOptionsTest : BaseAbstractTest() { infoLogs.clear() // test default - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .credentials("this", "that") .build() Assert.assertTrue(infoLogs.contains("ANDROID_ID will not be collected based on default settings")) @@ -604,20 +739,26 @@ class MParticleOptionsTest : BaseAbstractTest() { @Throws(InterruptedException::class) fun testBatchCreationCallback() { val listener = BatchCreationListener { batch -> batch } - var options = MParticleOptions.builder(mProductionContext) - .batchCreationListener(listener) - .credentials("this", "that") - .build() + var options = + MParticleOptions + .builder(mProductionContext) + .batchCreationListener(listener) + .credentials("this", "that") + .build() Assert.assertEquals(listener, options.batchCreationListener) - options = MParticleOptions.builder(mProductionContext) - .credentials("this", "that") - .batchCreationListener(listener) - .batchCreationListener(null) - .build() + options = + MParticleOptions + .builder(mProductionContext) + .credentials("this", "that") + .batchCreationListener(listener) + .batchCreationListener(null) + .build() Assert.assertNull(options.batchCreationListener) - options = MParticleOptions.builder(mProductionContext) - .credentials("this", "that") - .build() + options = + MParticleOptions + .builder(mProductionContext) + .credentials("this", "that") + .build() Assert.assertNull(options.batchCreationListener) } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/MParticleTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/MParticleTest.kt index 8e4a1aa30..71d0cf57c 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/MParticleTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/MParticleTest.kt @@ -47,9 +47,17 @@ class MParticleTest : BaseCleanStartedEachTest() { @Test fun testSessionEndsOnOptOut() { MParticle.getInstance()!!.mAppStateManager.ensureActiveSession() - Assert.assertTrue(MParticle.getInstance()!!.mAppStateManager.session.isActive) + Assert.assertTrue( + MParticle + .getInstance()!! + .mAppStateManager.session.isActive, + ) MParticle.getInstance()!!.optOut = true - Assert.assertFalse(MParticle.getInstance()!!.mAppStateManager.session.isActive) + Assert.assertFalse( + MParticle + .getInstance()!! + .mAppStateManager.session.isActive, + ) } @Test @@ -104,11 +112,12 @@ class MParticleTest : BaseCleanStartedEachTest() { @Throws(Exception::class) fun testCalledUpdateInstallReferrer() { val called = BooleanArray(2) - MParticle.getInstance()!!.mMessageManager = object : MessageManager() { - override fun installReferrerUpdated() { - called[0] = true + MParticle.getInstance()!!.mMessageManager = + object : MessageManager() { + override fun installReferrerUpdated() { + called[0] = true + } } - } MParticle.getInstance()!!.mKitManager = object : KitFrameworkWrapper(mContext, null, null, null, true, null) { override fun installReferrerUpdated() { @@ -143,17 +152,21 @@ class MParticleTest : BaseCleanStartedEachTest() { MParticle.setInstance(null) val token = mRandomUtils.getAlphaNumericString(15) mServer.setupConfigResponse( - JSONObject().put(ConfigManager.WORKSPACE_TOKEN, token).toString() + JSONObject().put(ConfigManager.WORKSPACE_TOKEN, token).toString(), ) startMParticle() val jsInterfaces: MutableMap = HashMap() val latch = MPLatch(1) Handler(Looper.getMainLooper()).post { - val webView: WebView = object : WebView(mContext) { - override fun addJavascriptInterface(`object`: Any, name: String) { - jsInterfaces[name] = `object` + val webView: WebView = + object : WebView(mContext) { + override fun addJavascriptInterface( + `object`: Any, + name: String, + ) { + jsInterfaces[name] = `object` + } } - } MParticle.getInstance()!!.registerWebView(webView) Assert.assertTrue(jsInterfaces[MParticleJSInterface.INTERFACE_BASE_NAME + "_" + token + "_v2"] is MParticleJSInterface) val clientToken = mRandomUtils.getAlphaNumericString(15) @@ -212,10 +225,11 @@ class MParticleTest : BaseCleanStartedEachTest() { @Throws(InterruptedException::class) fun testResetIdentityCall(resetRunnable: Runnable) { val called = BooleanArray(2) - val crashListener = IdentityStateListener { user, previousUser -> - Assert.assertTrue(called[0]) - throw IllegalStateException("Should not be getting callbacks after reset") - } + val crashListener = + IdentityStateListener { user, previousUser -> + Assert.assertTrue(called[0]) + throw IllegalStateException("Should not be getting callbacks after reset") + } mServer.setupHappyIdentify(ran.nextLong(), 100) MParticle.getInstance()!!.Identity().addIdentityStateListener(crashListener) MParticle.getInstance()!!.Identity().identify(IdentityApiRequest.withEmptyUser().build()) @@ -232,19 +246,41 @@ class MParticleTest : BaseCleanStartedEachTest() { startMParticle() MParticle.getInstance()!!.Messaging().enablePushNotifications(senderId) var fetchedSenderId: String? = - MParticle.getInstance()!!.mInternal.getConfigManager().getPushSenderId() + MParticle + .getInstance()!! + .mInternal + .getConfigManager() + .getPushSenderId() Assert.assertTrue( - MParticle.getInstance()!!.mInternal.getConfigManager().isPushEnabled() ?: false + MParticle + .getInstance()!! + .mInternal + .getConfigManager() + .isPushEnabled() ?: false, ) Assert.assertEquals(senderId, fetchedSenderId) val otherSenderId = "senderIdLogPushRegistration" MParticle.getInstance()!!.logPushRegistration("instanceId", otherSenderId) - fetchedSenderId = MParticle.getInstance()!!.mInternal.getConfigManager().getPushSenderId() + fetchedSenderId = + MParticle + .getInstance()!! + .mInternal + .getConfigManager() + .getPushSenderId() Assert.assertEquals(otherSenderId, fetchedSenderId) MParticle.getInstance()!!.Messaging().disablePushNotifications() - fetchedSenderId = MParticle.getInstance()!!.mInternal.getConfigManager().getPushSenderId() + fetchedSenderId = + MParticle + .getInstance()!! + .mInternal + .getConfigManager() + .getPushSenderId() Assert.assertFalse( - MParticle.getInstance()!!.mInternal.getConfigManager().isPushEnabled() ?: false + MParticle + .getInstance()!! + .mInternal + .getConfigManager() + .isPushEnabled() ?: false, ) Assert.assertNull(fetchedSenderId) } @@ -255,15 +291,17 @@ class MParticleTest : BaseCleanStartedEachTest() { val pushRegistrationTest = PushRegistrationTest().setServer(mServer) pushRegistrationTest.setContext(mContext) for (setPush in pushRegistrationTest.setPushes) { - val oldRegistration = PushRegistration( - mRandomUtils.getAlphaNumericString(10), - mRandomUtils.getAlphaNumericString(15) - ) + val oldRegistration = + PushRegistration( + mRandomUtils.getAlphaNumericString(10), + mRandomUtils.getAlphaNumericString(15), + ) setPush.setPushRegistration(oldRegistration) - val newPushRegistration = PushRegistration( - mRandomUtils.getAlphaNumericString(10), - mRandomUtils.getAlphaNumericString(15) - ) + val newPushRegistration = + PushRegistration( + mRandomUtils.getAlphaNumericString(10), + mRandomUtils.getAlphaNumericString(15), + ) val latch: CountDownLatch = MPLatch(1) val received = AndroidUtils.Mutable(false) mServer.waitForVerify( @@ -285,17 +323,17 @@ class MParticleTest : BaseCleanStartedEachTest() { Assert.assertEquals( failureMessage, oldRegistration.instanceId, - identityChange.getString("old_value") + identityChange.getString("old_value"), ) Assert.assertEquals( failureMessage, newPushRegistration.instanceId, - identityChange.getString("new_value") + identityChange.getString("new_value"), ) Assert.assertEquals( failureMessage, "push_token", - identityChange.getString("identity_type") + identityChange.getString("identity_type"), ) } catch (jse: JSONException) { jse.toString() @@ -303,13 +341,14 @@ class MParticleTest : BaseCleanStartedEachTest() { return@JSONMatch true } false - } - ) + }, + ), ) { received.value = true latch.countDown() } - MParticle.getInstance()!! + MParticle + .getInstance()!! .logPushRegistration(newPushRegistration.instanceId, newPushRegistration.senderId) latch.await() } @@ -432,14 +471,24 @@ class MParticleTest : BaseCleanStartedEachTest() { MParticle.getInstance()!!.logEvent(TestingUtils.getInstance().randomMPEventRich) } for (i in 0..9) { - MParticle.getInstance()!!.mInternal.getConfigManager() + MParticle + .getInstance()!! + .mInternal + .getConfigManager() .setMpid(ran.nextLong(), ran.nextBoolean()) } val databaseJson = getDatabaseContents(listOf("messages")) Assert.assertTrue(databaseJson.getJSONArray("messages").length() > 0) Assert.assertEquals(6, allTables.size.toLong()) Assert.assertTrue( - 10 < (MParticle.getInstance()!!.mInternal.getConfigManager().getMpids()?.size ?: 0) + 10 < ( + MParticle + .getInstance()!! + .mInternal + .getConfigManager() + .getMpids() + ?.size ?: 0 + ), ) // Set strict mode, so if we get any warning or error messages during the reset/restart phase, @@ -451,7 +500,7 @@ class MParticleTest : BaseCleanStartedEachTest() { // Restart the SDK, to the point where the initial Identity call returns, make sure there are no errors on startup. TestingUtils.setStrictMode( MParticle.LogLevel.WARNING, - "Failed to get MParticle instance, getInstance() called prior to start()." + "Failed to get MParticle instance, getInstance() called prior to start().", ) beforeBase() } @@ -472,9 +521,9 @@ class MParticleTest : BaseCleanStartedEachTest() { if (sharedPreferenceName != "WebViewChromiumPrefs" && sharedPreferenceName != "com.mparticle.test_preferences") { Assert.fail( """ - SharedPreference file failed to clear: - ${getSharedPrefsContents(sharedPreferenceName)} - """.trimIndent() + SharedPreference file failed to clear: + ${getSharedPrefsContents(sharedPreferenceName)} + """.trimIndent(), ) } } @@ -491,15 +540,14 @@ class MParticleTest : BaseCleanStartedEachTest() { } } - private fun getSharedPrefsContents(name: String): String { - return try { + private fun getSharedPrefsContents(name: String): String = + try { val prefs = mContext.getSharedPreferences(name, Context.MODE_PRIVATE) """ - $name: - ${JSONObject(prefs.all).toString(4)} + $name: + ${JSONObject(prefs.all).toString(4)} """.trimIndent() } catch (e: JSONException) { "error printing SharedPrefs :/" } - } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt index ab0ce5524..cddc693e3 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt @@ -47,23 +47,40 @@ class PushRegistrationTest : BaseCleanStartedEachTest() { fun testPushRegistrationSet() { Assert.assertEquals( mStartingMpid.toLong(), - MParticle.getInstance()?.Identity()?.currentUser?.id + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.id, ) for (setPush in setPushes) { - val pushRegistration = PushRegistration( - mRandomUtils.getAlphaNumericString(10), - mRandomUtils.getAlphaNumericString(15) - ) + val pushRegistration = + PushRegistration( + mRandomUtils.getAlphaNumericString(10), + mRandomUtils.getAlphaNumericString(15), + ) setPush.setPushRegistration(pushRegistration) for (getPush in getPushes) { val fetchedPushValue = getPush.pushRegistration val fetchedSenderId = fetchedPushValue.senderId val fetchedInstanceId = fetchedPushValue.instanceId if (pushRegistration.senderId != fetchedSenderId) { - Assert.fail("Mismatch! When push value of \"" + pushRegistration.senderId + "\" is set with: " + setPush.name + ". A different value \"" + fetchedSenderId + "\" is returned with:" + getPush.name) + Assert.fail( + "Mismatch! When push value of \"" + pushRegistration.senderId + "\" is set with: " + setPush.name + ". A different value \"" + fetchedSenderId + "\" is returned with:" + getPush.name, + ) } if (pushRegistration.instanceId != fetchedInstanceId) { - Assert.fail("Mismatch! When push value of \"" + pushRegistration.instanceId + "\" is set with: " + setPush.name + ". A different value \"" + fetchedInstanceId + "\" is returned with:" + getPush.name) + Assert.fail( + "Mismatch! When push value of \"" + pushRegistration.instanceId + "\" is set with: " + setPush.name + ". A different value \"" + fetchedInstanceId + "\" is returned with:" + getPush.name, + ) } } } @@ -72,17 +89,24 @@ class PushRegistrationTest : BaseCleanStartedEachTest() { @Test fun testPushRegistrationCleared() { for (setPush in setPushes) { - val pushRegistration = PushRegistration( - mRandomUtils.getAlphaNumericString(10), - mRandomUtils.getAlphaNumericString(15) - ) + val pushRegistration = + PushRegistration( + mRandomUtils.getAlphaNumericString(10), + mRandomUtils.getAlphaNumericString(15), + ) setPush.setPushRegistration(pushRegistration) for (clearPush in clearPushes) { clearPush.clearPush() for (getPush in getPushes) { val fetchedPushRegistration = getPush.pushRegistration if (fetchedPushRegistration.instanceId != null && fetchedPushRegistration.senderId != null) { - Assert.fail("Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name + ", and cleared with: " + clearPush.name + ", the value is not null when fetched with:" + getPush.name) + Assert.fail( + "Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name + ", and cleared with: " + clearPush.name + ", the value is not null when fetched with:" + getPush.name, + ) } } } @@ -92,21 +116,32 @@ class PushRegistrationTest : BaseCleanStartedEachTest() { @Test fun testPushRegistrationEnabledDisabled() { for (setPush in setPushes) { - val pushRegistration = PushRegistration( - mRandomUtils.getAlphaNumericString(10), - mRandomUtils.getAlphaNumericString(15) - ) + val pushRegistration = + PushRegistration( + mRandomUtils.getAlphaNumericString(10), + mRandomUtils.getAlphaNumericString(15), + ) setPush.setPushRegistration(pushRegistration) for (pushEnabled in pushEnableds) { if (!pushEnabled.isPushEnabled) { - Assert.fail("Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name + ", push IS NOT enabled with:" + pushEnabled.name) + Assert.fail( + "Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name + ", push IS NOT enabled with:" + pushEnabled.name, + ) } } for (clearPush in clearPushes) { clearPush.clearPush() for (pushEnabled in pushEnableds) { if (pushEnabled.isPushEnabled) { - Assert.fail("Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name + ", and cleared with: " + clearPush.name + ", push IS enabled with:" + pushEnabled.name) + Assert.fail( + "Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name + ", and cleared with: " + clearPush.name + ", push IS enabled with:" + pushEnabled.name, + ) } } } @@ -114,166 +149,213 @@ class PushRegistrationTest : BaseCleanStartedEachTest() { } @JvmField - var setPushes = arrayOf( - object : SetPush { - override fun setPushRegistration(pushRegistration: PushRegistration) { - MParticle.getInstance() - ?.logPushRegistration(pushRegistration.instanceId, pushRegistration.senderId) - } + var setPushes = + arrayOf( + object : SetPush { + override fun setPushRegistration(pushRegistration: PushRegistration) { + MParticle + .getInstance() + ?.logPushRegistration(pushRegistration.instanceId, pushRegistration.senderId) + } - override val name: String - get() = "MParticle.getInstance()?.logPushRegistration(senderId, instanceId)" - }, - object : SetPush { - override fun setPushRegistration(pushRegistration: PushRegistration) { - MParticle.getInstance()?.mInternal?.configManager?.pushRegistration = - pushRegistration - } + override val name: String + get() = "MParticle.getInstance()?.logPushRegistration(senderId, instanceId)" + }, + object : SetPush { + override fun setPushRegistration(pushRegistration: PushRegistration) { + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.pushRegistration = + pushRegistration + } - override val name: String - get() = "ConfigManager.setPushRegistration(pushRegistration())" - }, - object : SetPush { - override fun setPushRegistration(pushRegistration: PushRegistration) { - MParticle.getInstance()?.mInternal?.configManager?.pushSenderId = - pushRegistration.senderId - MParticle.getInstance()?.mInternal?.configManager?.pushInstanceId = - pushRegistration.instanceId - } + override val name: String + get() = "ConfigManager.setPushRegistration(pushRegistration())" + }, + object : SetPush { + override fun setPushRegistration(pushRegistration: PushRegistration) { + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.pushSenderId = + pushRegistration.senderId + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.pushInstanceId = + pushRegistration.instanceId + } - override val name: String - get() = "ConfigManager.setPushSenderId(senderId) + ConfigManager.setPushRegistration(instanceId)" - }, - object : SetPush { - override fun setPushRegistration(pushRegistration: PushRegistration) { - // For enablePushNotifications() to set the push registration, we need to mimic - // the Firebase dependency, and clear the push-fetched flags - TestingUtils.setFirebasePresent(true, pushRegistration.instanceId) - pushRegistration.senderId?.let { - MParticle.getInstance()?.Messaging()?.enablePushNotifications( - it - ) + override val name: String + get() = "ConfigManager.setPushSenderId(senderId) + ConfigManager.setPushRegistration(instanceId)" + }, + object : SetPush { + override fun setPushRegistration(pushRegistration: PushRegistration) { + // For enablePushNotifications() to set the push registration, we need to mimic + // the Firebase dependency, and clear the push-fetched flags + TestingUtils.setFirebasePresent(true, pushRegistration.instanceId) + pushRegistration.senderId?.let { + MParticle.getInstance()?.Messaging()?.enablePushNotifications( + it, + ) + } + // this method setting push is async, so wait for confirmation before continuing + val configManager = ConfigManager.getInstance(mContext) + while (!configManager.isPushEnabled) { + try { + Thread.sleep(10) + } catch (e: InterruptedException) { + e.printStackTrace() + } + } + TestingUtils.setFirebasePresent(false, null) } - // this method setting push is async, so wait for confirmation before continuing - val configManager = ConfigManager.getInstance(mContext) - while (!configManager.isPushEnabled) { + + override val name: String + get() = "MessagingApi.enablePushNotification(senderId)" + }, + object : SetPush { + override fun setPushRegistration(pushRegistration: PushRegistration) { + MParticle.setInstance(null) try { - Thread.sleep(10) + startMParticle( + pushRegistration.instanceId?.let { instanceId -> + pushRegistration.senderId?.let { senderId -> + MParticleOptions.builder(mContext).pushRegistration( + instanceId, + senderId, + ) + } + }, + ) } catch (e: InterruptedException) { - e.printStackTrace() + Assert.fail(e.message) } } - TestingUtils.setFirebasePresent(false, null) - } - override val name: String - get() = "MessagingApi.enablePushNotification(senderId)" - }, - object : SetPush { - override fun setPushRegistration(pushRegistration: PushRegistration) { - MParticle.setInstance(null) - try { - startMParticle( - pushRegistration.instanceId?.let { instanceId -> - pushRegistration.senderId?.let { senderId -> - MParticleOptions.builder(mContext).pushRegistration( - instanceId, - senderId - ) - } - } - ) - } catch (e: InterruptedException) { - Assert.fail(e.message) + override val name: String + get() = "MParticleOptions.pushRegistration(instanceId, senderId)" + }, + ) + var clearPushes = + arrayOf( + object : ClearPush { + override fun clearPush() { + MParticle.getInstance()?.Messaging()?.disablePushNotifications() } - } - - override val name: String - get() = "MParticleOptions.pushRegistration(instanceId, senderId)" - } - ) - var clearPushes = arrayOf( - object : ClearPush { - override fun clearPush() { - MParticle.getInstance()?.Messaging()?.disablePushNotifications() - } - override val name: String - get() = "MessagingApi.disablePushNotifications" - }, - object : ClearPush { - override fun clearPush() { - MParticle.getInstance()?.mInternal?.configManager?.pushSenderId = null - } - - override val name: String - get() = "ConfigManager.setPushSenderId(null)" - }, - object : ClearPush { - override fun clearPush() { - MParticle.getInstance()?.mInternal?.configManager?.pushRegistration = null - } + override val name: String + get() = "MessagingApi.disablePushNotifications" + }, + object : ClearPush { + override fun clearPush() { + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.pushSenderId = null + } - override val name: String - get() = "ConfigManager.setPushRegistration(null)" - }, - object : ClearPush { - override fun clearPush() { - MParticle.getInstance()?.mInternal?.configManager?.pushRegistration = - PushRegistration("instanceId", null) - } + override val name: String + get() = "ConfigManager.setPushSenderId(null)" + }, + object : ClearPush { + override fun clearPush() { + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.pushRegistration = null + } - override val name: String - get() = "ConfigManager.setPushRegistration(PushRegistration(\"instanceId\", null))" - }, - object : ClearPush { - override fun clearPush() { - MParticle.setInstance(null) - try { - startMParticle(MParticleOptions.builder(mContext).pushRegistration("", "")) - } catch (e: InterruptedException) { - Assert.fail(e.message) + override val name: String + get() = "ConfigManager.setPushRegistration(null)" + }, + object : ClearPush { + override fun clearPush() { + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.pushRegistration = + PushRegistration("instanceId", null) } - } - override val name: String - get() = "startMParticle(MParticleOptions.builder(mContext).pushRegistration(null, null))" - } - ) - var getPushes = arrayOf( - object : GetPush { - override val pushRegistration: PushRegistration - get() { - val senderId: String? = - MParticle.getInstance()?.mInternal?.configManager?.pushSenderId - val instanceId: String? = - MParticle.getInstance()?.mInternal?.configManager?.pushInstanceId - return PushRegistration(instanceId, senderId) + override val name: String + get() = "ConfigManager.setPushRegistration(PushRegistration(\"instanceId\", null))" + }, + object : ClearPush { + override fun clearPush() { + MParticle.setInstance(null) + try { + startMParticle(MParticleOptions.builder(mContext).pushRegistration("", "")) + } catch (e: InterruptedException) { + Assert.fail(e.message) + } } - override val name: String - get() = "ConfigManager.getPushSenderId() + ConfigManager.getPushInstanceId()" - }, - object : GetPush { - override val pushRegistration: PushRegistration - get() = PushRegistrationHelper.getLatestPushRegistration(mContext) - override val name: String - get() = "PushRegistrationHelper.getLatestPushRegistration(context)" - }, - object : GetPush { - override val pushRegistration: PushRegistration - get() = MParticle.getInstance()?.mInternal?.configManager?.pushRegistration!! - override val name: String - get() = "ConfigManager.getPushRegistration()" - } - ) - var pushEnableds = arrayOf( - object : PushEnabled { - override val isPushEnabled: Boolean - get() = MParticle.getInstance()?.mInternal?.configManager?.isPushEnabled == true - override val name: String - get() = "ConfigManager.isPushEnabled()" - } - ) + + override val name: String + get() = "startMParticle(MParticleOptions.builder(mContext).pushRegistration(null, null))" + }, + ) + var getPushes = + arrayOf( + object : GetPush { + override val pushRegistration: PushRegistration + get() { + val senderId: String? = + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.pushSenderId + val instanceId: String? = + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.pushInstanceId + return PushRegistration(instanceId, senderId) + } + override val name: String + get() = "ConfigManager.getPushSenderId() + ConfigManager.getPushInstanceId()" + }, + object : GetPush { + override val pushRegistration: PushRegistration + get() = PushRegistrationHelper.getLatestPushRegistration(mContext) + override val name: String + get() = "PushRegistrationHelper.getLatestPushRegistration(context)" + }, + object : GetPush { + override val pushRegistration: PushRegistration + get() = + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.pushRegistration!! + override val name: String + get() = "ConfigManager.getPushRegistration()" + }, + ) + var pushEnableds = + arrayOf( + object : PushEnabled { + override val isPushEnabled: Boolean + get() = + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.isPushEnabled == true + override val name: String + get() = "ConfigManager.isPushEnabled()" + }, + ) interface SynonymousMethod { val name: String diff --git a/android-core/src/androidTest/kotlin/com.mparticle/SessionMessagesTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/SessionMessagesTest.kt index 3cfcad24d..48c064066 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/SessionMessagesTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/SessionMessagesTest.kt @@ -38,22 +38,23 @@ class SessionMessagesTest : BaseCleanStartedEachTest() { Matcher(mServer.Endpoints().eventsUrl).bodyMatch( JSONMatch { jsonObject -> try { - val jsonArray = jsonObject.optJSONArray(Constants.MessageKey.MESSAGES) - ?: return@JSONMatch false + val jsonArray = + jsonObject.optJSONArray(Constants.MessageKey.MESSAGES) + ?: return@JSONMatch false for (i in 0 until jsonArray.length()) { val eventObject = jsonArray.getJSONObject(i) if (eventObject.getString("dt") == Constants.MessageType.SESSION_START) { Assert.assertEquals( eventObject.getLong("ct").toFloat(), mAppStateManager.fetchSession().mSessionStartTime.toFloat(), - 1000f + 1000f, ) Assert.assertEquals( """started sessionID = ${sessionId.value} current sessionId = ${mAppStateManager.fetchSession().mSessionID} sent sessionId = ${eventObject.getString("id")}""", mAppStateManager.fetchSession().mSessionID, - eventObject.getString("id") + eventObject.getString("id"), ) sessionStartReceived[0] = true return@JSONMatch true @@ -64,8 +65,8 @@ sent sessionId = ${eventObject.getString("id")}""", Assert.fail(e.message) } false - } - ) + }, + ), ) Assert.assertTrue(sessionStartReceived[0]) } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/UploadEventKotlinTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/UploadEventKotlinTest.kt index 351a56e58..aa738aa23 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/UploadEventKotlinTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/UploadEventKotlinTest.kt @@ -10,14 +10,20 @@ import kotlin.test.assertNotEquals class UploadEventKotlinTest : BaseCleanStartedEachTest() { @Test fun testMPEventUploadBypass() { - val event = MPEvent.Builder("Should Not Upload") - .shouldUploadEvent(false) - .build() - val event2 = MPEvent.Builder("Should Upload 1") - .shouldUploadEvent(true) - .build() - val event3 = MPEvent.Builder("Should Upload 2") - .build() + val event = + MPEvent + .Builder("Should Not Upload") + .shouldUploadEvent(false) + .build() + val event2 = + MPEvent + .Builder("Should Upload 1") + .shouldUploadEvent(true) + .build() + val event3 = + MPEvent + .Builder("Should Upload 2") + .build() MParticle.getInstance()?.logEvent(event) MParticle.getInstance()?.logEvent(event2) MParticle.getInstance()?.logEvent(event3) @@ -46,7 +52,7 @@ class UploadEventKotlinTest : BaseCleanStartedEachTest() { numUploadedEvents == 2 } } ?: false - } + }, ) } @@ -75,32 +81,46 @@ class UploadEventKotlinTest : BaseCleanStartedEachTest() { .any { val eventMessageName = messagesArray.getJSONObject(it).optString("n") assertNotEquals("Should Not Upload", eventMessageName) - if (eventMessageName == "Should Upload 1" || eventMessageName == "Should Upload 2" || eventMessageName == "Should Upload 3") { + if (eventMessageName == "Should Upload 1" || eventMessageName == "Should Upload 2" || + eventMessageName == "Should Upload 3" + ) { numUploadedEvents++ } numUploadedEvents == 3 } } ?: false - } + }, ) } @Test fun testCommerceEventUploadBypass() { - val product = Product.Builder("Should Not Upload", "sku1", 100.00) - .build() - val event = CommerceEvent.Builder(Product.ADD_TO_CART, product) - .shouldUploadEvent(false) - .build() - var product2 = Product.Builder("Should Upload 1", "sku2", 100.00) - .build() - val event2 = CommerceEvent.Builder(Product.ADD_TO_CART, product2) - .shouldUploadEvent(true) - .build() - var product3 = Product.Builder("Should Upload 2", "sku3", 100.00) - .build() - val event3 = CommerceEvent.Builder(Product.ADD_TO_CART, product3) - .build() + val product = + Product + .Builder("Should Not Upload", "sku1", 100.00) + .build() + val event = + CommerceEvent + .Builder(Product.ADD_TO_CART, product) + .shouldUploadEvent(false) + .build() + var product2 = + Product + .Builder("Should Upload 1", "sku2", 100.00) + .build() + val event2 = + CommerceEvent + .Builder(Product.ADD_TO_CART, product2) + .shouldUploadEvent(true) + .build() + var product3 = + Product + .Builder("Should Upload 2", "sku3", 100.00) + .build() + val event3 = + CommerceEvent + .Builder(Product.ADD_TO_CART, product3) + .build() MParticle.getInstance()?.logEvent(event) MParticle.getInstance()?.logEvent(event2) MParticle.getInstance()?.logEvent(event3) @@ -122,8 +142,12 @@ class UploadEventKotlinTest : BaseCleanStartedEachTest() { (0 until messagesArray.length()) .any { val eventProductName = - messagesArray.getJSONObject(it).optJSONObject("pd") - ?.optJSONArray("pl")?.optJSONObject(0)?.optString("nm") + messagesArray + .getJSONObject(it) + .optJSONObject("pd") + ?.optJSONArray("pl") + ?.optJSONObject(0) + ?.optString("nm") assertNotEquals("Should Not Upload", eventProductName) if (eventProductName == "Should Upload 1" || eventProductName == "Should Upload 2") { numUploadedEvents++ @@ -131,7 +155,7 @@ class UploadEventKotlinTest : BaseCleanStartedEachTest() { numUploadedEvents == 2 } } ?: false - } + }, ) } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/UploadMessageTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/UploadMessageTest.kt index 490c3529d..91e838f38 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/UploadMessageTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/UploadMessageTest.kt @@ -31,60 +31,69 @@ class UploadMessageTest : BaseCleanStartedEachTest() { val numberOfEvents = 3 val handler = Handler(Looper.getMainLooper()) val mpid = ran.nextLong() - MParticle.getInstance()?.mInternal?.configManager?.setMpid(mpid, ran.nextBoolean()) + MParticle + .getInstance() + ?.mInternal + ?.configManager + ?.setMpid(mpid, ran.nextBoolean()) val events: MutableMap = HashMap() val latch: CountDownLatch = MPLatch(numberOfEvents) val matchingJSONEvents: MutableMap> = HashMap() - AccessUtils.setMParticleApiClient(object : EmptyMParticleApiClient() { - @Throws(IOException::class, MPThrottleException::class, MPRampException::class) - override fun sendMessageBatch(message: String, uploadSettings: UploadSettings): Int { - handler.post { - try { - val jsonObject = JSONObject(message) - val jsonArray = jsonObject.optJSONArray(Constants.MessageKey.MESSAGES) - val mpid = java.lang.Long.valueOf(jsonObject.getString("mpid")) - var matchingMpidJSONEvents = matchingJSONEvents[mpid] - if (matchingMpidJSONEvents == null) { - matchingJSONEvents[mpid] = - HashMap().also { matchingMpidJSONEvents = it } - } - if (!MPUtility.isEmpty(jsonArray)) { - if (jsonArray != null) { - for (i in 0 until jsonArray.length()) { - val eventObject = jsonArray.getJSONObject(i) - if (eventObject.getString("dt") == Constants.MessageType.EVENT) { - val eventName = eventObject.getString("n") - val matchingEvent = events[eventName] - if (matchingEvent != null) { - val eventType = eventObject.getString("et") - if (matchingEvent.eventType.toString() == eventType) { - if (matchingMpidJSONEvents?.containsKey(eventName) == true) { - Assert.fail("Duplicate Event Message Sent") + AccessUtils.setMParticleApiClient( + object : EmptyMParticleApiClient() { + @Throws(IOException::class, MPThrottleException::class, MPRampException::class) + override fun sendMessageBatch( + message: String, + uploadSettings: UploadSettings, + ): Int { + handler.post { + try { + val jsonObject = JSONObject(message) + val jsonArray = jsonObject.optJSONArray(Constants.MessageKey.MESSAGES) + val mpid = java.lang.Long.valueOf(jsonObject.getString("mpid")) + var matchingMpidJSONEvents = matchingJSONEvents[mpid] + if (matchingMpidJSONEvents == null) { + matchingJSONEvents[mpid] = + HashMap().also { matchingMpidJSONEvents = it } + } + if (!MPUtility.isEmpty(jsonArray)) { + if (jsonArray != null) { + for (i in 0 until jsonArray.length()) { + val eventObject = jsonArray.getJSONObject(i) + if (eventObject.getString("dt") == Constants.MessageType.EVENT) { + val eventName = eventObject.getString("n") + val matchingEvent = events[eventName] + if (matchingEvent != null) { + val eventType = eventObject.getString("et") + if (matchingEvent.eventType.toString() == eventType) { + if (matchingMpidJSONEvents?.containsKey(eventName) == true) { + Assert.fail("Duplicate Event Message Sent") + } else { + matchingMpidJSONEvents?.set( + eventName, + eventObject, + ) + } } else { - matchingMpidJSONEvents?.set( - eventName, - eventObject - ) + Assert.fail("Unknown Event") } } else { Assert.fail("Unknown Event") } - } else { - Assert.fail("Unknown Event") + latch.countDown() } - latch.countDown() } } } + } catch (e: Exception) { + e.printStackTrace() + Assert.fail(e.toString()) } - } catch (e: Exception) { - e.printStackTrace() - Assert.fail(e.toString()) } + return 202 } - return 202 - } - }) + }, + ) var j = 0 while (j < 3) { val event = TestingUtils.getInstance().randomMPEventRich @@ -167,7 +176,10 @@ class UploadMessageTest : BaseCleanStartedEachTest() { // } @Throws(JSONException::class) - fun assertEventEquals(mpEvent: MPEvent, jsonObject: JSONObject) { + fun assertEventEquals( + mpEvent: MPEvent, + jsonObject: JSONObject, + ) { if (jsonObject.optString("n") !== mpEvent.eventName) { Assert.assertTrue(mpEvent.eventName == jsonObject.getString("n")) } @@ -210,7 +222,10 @@ class UploadMessageTest : BaseCleanStartedEachTest() { } @Throws(JSONException::class) - fun assertArraysEqual(jsonArray: JSONArray, list: MutableList) { + fun assertArraysEqual( + jsonArray: JSONArray, + list: MutableList, + ) { val jsonArrayList: MutableList = ArrayList() for (i in 0 until jsonArray.length()) { jsonArrayList.add(jsonArray.getString(i)) diff --git a/android-core/src/androidTest/kotlin/com.mparticle/commerce/CommerceApiTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/commerce/CommerceApiTest.kt index d5b2eb2b1..a99c1bae4 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/commerce/CommerceApiTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/commerce/CommerceApiTest.kt @@ -10,10 +10,14 @@ class CommerceApiTest : BaseCleanStartedEachTest() { @Test @Throws(InterruptedException::class) fun testCommerceProductEvent() { - val product = Product.Builder("name", "sku", 10.00) - .build() - val commerceEvent = CommerceEvent.Builder(Product.DETAIL, product) - .build() + val product = + Product + .Builder("name", "sku", 10.00) + .build() + val commerceEvent = + CommerceEvent + .Builder(Product.DETAIL, product) + .build() MParticle.getInstance()?.logEvent(commerceEvent) MParticle.getInstance()?.upload() verifyEventSent() @@ -23,11 +27,14 @@ class CommerceApiTest : BaseCleanStartedEachTest() { @Test @Throws(InterruptedException::class) fun testCommercePromotionEvent() { - val promotion = Promotion() - .setName("name") - .setId("123") - val commerceEvent = CommerceEvent.Builder(Promotion.CLICK, promotion) - .build() + val promotion = + Promotion() + .setName("name") + .setId("123") + val commerceEvent = + CommerceEvent + .Builder(Promotion.CLICK, promotion) + .build() MParticle.getInstance()?.logEvent(commerceEvent) MParticle.getInstance()?.upload() verifyEventSent() @@ -37,11 +44,15 @@ class CommerceApiTest : BaseCleanStartedEachTest() { @Test @Throws(InterruptedException::class) fun testCommerceImpressionEvent() { - val product = Product.Builder("name", "sku", 10.00) - .build() + val product = + Product + .Builder("name", "sku", 10.00) + .build() val impression = Impression("my impression", product) - val commerceEvent = CommerceEvent.Builder(impression) - .build() + val commerceEvent = + CommerceEvent + .Builder(impression) + .build() MParticle.getInstance()?.logEvent(commerceEvent) MParticle.getInstance()?.upload() verifyEventSent() @@ -66,7 +77,7 @@ class CommerceApiTest : BaseCleanStartedEachTest() { } } found - } + }, ) } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiOutgoingTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiOutgoingTest.kt index 6e5cea471..585187c89 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiOutgoingTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiOutgoingTest.kt @@ -16,11 +16,10 @@ class IdentityApiOutgoingTest : BaseCleanStartedEachTest() { Matcher(mServer.Endpoints().loginUrl).bodyMatch( object : IdentityMatcher() { - override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean { - return mStartingMpid == identityRequest.previousMpid - } - } - ) + override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean = + mStartingMpid == identityRequest.previousMpid + }, + ), ) } @@ -32,11 +31,10 @@ class IdentityApiOutgoingTest : BaseCleanStartedEachTest() { Matcher(mServer.Endpoints().loginUrl).bodyMatch( object : IdentityMatcher() { - override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean { - return mStartingMpid == identityRequest.previousMpid - } - } - ) + override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean = + mStartingMpid == identityRequest.previousMpid + }, + ), ) } @@ -48,11 +46,10 @@ class IdentityApiOutgoingTest : BaseCleanStartedEachTest() { Matcher(mServer.Endpoints().logoutUrl).bodyMatch( object : IdentityMatcher() { - override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean { - return mStartingMpid == identityRequest.previousMpid - } - } - ) + override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean = + mStartingMpid == identityRequest.previousMpid + }, + ), ) } @@ -64,11 +61,10 @@ class IdentityApiOutgoingTest : BaseCleanStartedEachTest() { Matcher(mServer.Endpoints().logoutUrl).bodyMatch( object : IdentityMatcher() { - override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean { - return mStartingMpid == identityRequest.previousMpid - } - } - ) + override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean = + mStartingMpid == identityRequest.previousMpid + }, + ), ) } @@ -76,8 +72,10 @@ class IdentityApiOutgoingTest : BaseCleanStartedEachTest() { @Throws(Exception::class) fun testModify() { MParticle.getInstance()?.Identity()?.modify( - IdentityApiRequest.withEmptyUser().customerId(ran.nextLong().toString() + "") - .build() + IdentityApiRequest + .withEmptyUser() + .customerId(ran.nextLong().toString() + "") + .build(), ) mServer.waitForVerify(Matcher(mServer.Endpoints().getModifyUrl(mStartingMpid))) } @@ -90,11 +88,10 @@ class IdentityApiOutgoingTest : BaseCleanStartedEachTest() { Matcher(mServer.Endpoints().identifyUrl).bodyMatch( object : IdentityMatcher() { - override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean { - return mStartingMpid == identityRequest.previousMpid - } - } - ) + override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean = + mStartingMpid == identityRequest.previousMpid + }, + ), ) } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiStartTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiStartTest.kt index 6117b4807..d148c0511 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiStartTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiStartTest.kt @@ -24,13 +24,16 @@ class IdentityApiStartTest : BaseCleanInstallEachTest() { @Throws(Exception::class) fun testInitialIdentitiesPresentWithAndroidId() { val identities = mRandomUtils.randomUserIdentities - val request = IdentityApiRequest.withEmptyUser() - .userIdentities(identities) - .build() + val request = + IdentityApiRequest + .withEmptyUser() + .userIdentities(identities) + .build() startMParticle( - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .androidIdEnabled(true) - .identify(request) + .identify(request), ) Assert.assertTrue(mServer.Requests().identify.size == 1) assertIdentitiesMatch(mServer.Requests().identify[0], identities, true) @@ -40,13 +43,16 @@ class IdentityApiStartTest : BaseCleanInstallEachTest() { @Throws(Exception::class) fun testInitialIdentitiesPresentWithoutAndroidId() { val identities = mRandomUtils.randomUserIdentities - val request = IdentityApiRequest.withEmptyUser() - .userIdentities(identities) - .build() + val request = + IdentityApiRequest + .withEmptyUser() + .userIdentities(identities) + .build() startMParticle( - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .androidIdEnabled(false) - .identify(request) + .identify(request), ) Assert.assertTrue(mServer.Requests().identify.size == 1) assertIdentitiesMatch(mServer.Requests().identify[0], identities, false) @@ -66,11 +72,16 @@ class IdentityApiStartTest : BaseCleanInstallEachTest() { val currentMpid = ran.nextLong() val identities = mRandomUtils.randomUserIdentities startMParticle() - MParticle.getInstance()?.Internal()?.configManager?.setMpid(currentMpid, ran.nextBoolean()) + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.setMpid(currentMpid, ran.nextBoolean()) for ((key, value) in identities) { AccessUtils.setUserIdentity(value, key, currentMpid) } - com.mparticle.internal.AccessUtils.awaitMessageHandler() + com.mparticle.internal.AccessUtils + .awaitMessageHandler() mServer = MockServer.getNewInstance(mContext) startMParticle() TestCase.assertEquals(mServer.Requests().identify.size, 1) @@ -91,7 +102,7 @@ class IdentityApiStartTest : BaseCleanInstallEachTest() { com.mparticle.internal.AccessUtils.setPushInPushRegistrationHelper( mContext, instanceId, - mRandomUtils.getAlphaNumericString(15) + mRandomUtils.getAlphaNumericString(15), ) val called = AndroidUtils.Mutable(false) var latch: CountDownLatch = MPLatch(1) @@ -110,7 +121,7 @@ class IdentityApiStartTest : BaseCleanInstallEachTest() { TestCase.assertEquals(instanceId, identityChange.getString("new_value")) TestCase.assertEquals( "push_token", - identityChange.getString("identity_type") + identityChange.getString("identity_type"), ) called.value = true } catch (jse: JSONException) { @@ -119,9 +130,9 @@ class IdentityApiStartTest : BaseCleanInstallEachTest() { return@JSONMatch true } false - } + }, ), - latch + latch, ) startMParticle() latch.await() @@ -132,7 +143,7 @@ class IdentityApiStartTest : BaseCleanInstallEachTest() { com.mparticle.internal.AccessUtils.setPushInPushRegistrationHelper( mContext, newInstanceId, - mRandomUtils.getAlphaNumericString(15) + mRandomUtils.getAlphaNumericString(15), ) latch = CountDownLatch(1) /** @@ -150,11 +161,11 @@ class IdentityApiStartTest : BaseCleanInstallEachTest() { TestCase.assertEquals(instanceId, identityChange.getString("old_value")) TestCase.assertEquals( newInstanceId, - identityChange.getString("new_value") + identityChange.getString("new_value"), ) TestCase.assertEquals( "push_token", - identityChange.getString("identity_type") + identityChange.getString("identity_type"), ) called.value = true } catch (jse: JSONException) { @@ -163,9 +174,9 @@ class IdentityApiStartTest : BaseCleanInstallEachTest() { return@JSONMatch true } false - } + }, ), - latch + latch, ) startMParticle() latch.await() @@ -176,7 +187,7 @@ class IdentityApiStartTest : BaseCleanInstallEachTest() { private fun assertIdentitiesMatch( request: Request, identities: Map, - androidIdEnabled: Boolean + androidIdEnabled: Boolean, ) { Assert.assertTrue(request is IdentityRequest) val identityRequest = request.asIdentityRequest() @@ -196,7 +207,7 @@ class IdentityApiStartTest : BaseCleanInstallEachTest() { val key = keys.next() TestCase.assertEquals( copy[MParticleIdentityClientImpl.getIdentityType(key)], - knownIdentities.getString(key) + knownIdentities.getString(key), ) } } @@ -221,21 +232,29 @@ class IdentityApiStartTest : BaseCleanInstallEachTest() { val identifyLatch: CountDownLatch = MPLatch(1) val modifyLatch: CountDownLatch = MPLatch(1) MParticle.start(MParticleOptions.builder(mContext).credentials("key", "value").build()) - MParticle.getInstance()?.Identity() - ?.addIdentityStateListener(object : IdentityStateListener { - override fun onUserIdentified(user: MParticleUser, previousUser: MParticleUser?) { - Assert.assertTrue(logPushRegistrationCalled.value) - identifyLatch.countDown() - MParticle.getInstance()?.Identity()?.removeIdentityStateListener(this) - } - }) + MParticle + .getInstance() + ?.Identity() + ?.addIdentityStateListener( + object : IdentityStateListener { + override fun onUserIdentified( + user: MParticleUser, + previousUser: MParticleUser?, + ) { + Assert.assertTrue(logPushRegistrationCalled.value) + identifyLatch.countDown() + MParticle.getInstance()?.Identity()?.removeIdentityStateListener(this) + } + }, + ) mServer.waitForVerify(Matcher(mServer.Endpoints().getModifyUrl(startingMpid)), modifyLatch) var pushRegistration: String? = null for (i in 0..4) { - MParticle.getInstance() + MParticle + .getInstance() ?.logPushRegistration( mRandomUtils.getAlphaString(12).also { pushRegistration = it }, - "senderId" + "senderId", ) } logPushRegistrationCalled.value = true @@ -260,15 +279,21 @@ class IdentityApiStartTest : BaseCleanInstallEachTest() { val called = AndroidUtils.Mutable(false) val latch: CountDownLatch = MPLatch(1) mServer.waitForVerify(Matcher(mServer.Endpoints().identifyUrl)) { request -> - TestCase.assertEquals("fire", request.asIdentityRequest().body.clientSdk.platform) + TestCase.assertEquals( + "fire", + request + .asIdentityRequest() + .body.clientSdk.platform, + ) called.value = true latch.countDown() } MParticle.start( - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .credentials("key", "secret") .operatingSystem(MParticle.OperatingSystem.FIRE_OS) - .build() + .build(), ) latch.await() Assert.assertTrue(called.value) @@ -276,15 +301,21 @@ class IdentityApiStartTest : BaseCleanInstallEachTest() { called.value = false val latch1: CountDownLatch = MPLatch(1) mServer.waitForVerify(Matcher(mServer.Endpoints().identifyUrl)) { request -> - TestCase.assertEquals("fire", request.asIdentityRequest().body.clientSdk.platform) + TestCase.assertEquals( + "fire", + request + .asIdentityRequest() + .body.clientSdk.platform, + ) called.value = true latch1.countDown() } MParticle.start( - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .credentials("key", "secret") .operatingSystem(MParticle.OperatingSystem.FIRE_OS) - .build() + .build(), ) latch1.await() Assert.assertTrue(called.value) @@ -303,7 +334,7 @@ class IdentityApiStartTest : BaseCleanInstallEachTest() { MParticleOptions .builder(mContext) .pushRegistration("instanceId", "senderId") - .environment(MParticle.Environment.Development) + .environment(MParticle.Environment.Development), ) Assert.assertTrue(MPUtility.isDevEnv()) } catch (e: Exception) { diff --git a/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiTest.kt index 5781b3128..c88de8d86 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiTest.kt @@ -61,7 +61,8 @@ class IdentityApiTest : BaseCleanStartedEachTest() { MParticle.getInstance()!!.Identity().addIdentityStateListener { user, previousUser -> if (user.id == mpid1) { try { - com.mparticle.internal.AccessUtils.awaitMessageHandler() + com.mparticle.internal.AccessUtils + .awaitMessageHandler() } catch (e: InterruptedException) { e.printStackTrace() } @@ -114,15 +115,19 @@ class IdentityApiTest : BaseCleanStartedEachTest() { Assert.assertEquals(identityApiResult.user.id, mpid1) Assert.assertEquals(identityApiResult.previousUser!!.id, mStartingMpid.toLong()) } - com.mparticle.internal.AccessUtils.awaitUploadHandler() + com.mparticle.internal.AccessUtils + .awaitUploadHandler() request = IdentityApiRequest.withEmptyUser().build() result = MParticle.getInstance()!!.Identity().identify(request) result.addSuccessListener { identityApiResult -> Assert.assertEquals(identityApiResult.user.id, mpid2) Assert.assertEquals( identityApiResult.user.id, - MParticle.getInstance()!! - .Identity().currentUser!!.id + MParticle + .getInstance()!! + .Identity() + .currentUser!! + .id, ) Assert.assertEquals(identityApiResult.previousUser!!.id, mpid1) latch.countDown() @@ -138,16 +143,23 @@ class IdentityApiTest : BaseCleanStartedEachTest() { fun testAddMultipleIdentityStateListeners() { mServer.addConditionalIdentityResponse(mStartingMpid, mpid1) val latch: CountDownLatch = MPLatch(6) - MParticle.getInstance()!!.Identity() + MParticle + .getInstance()!! + .Identity() .addIdentityStateListener { user, previousUser -> latch.countDown() } - MParticle.getInstance()!!.Identity() + MParticle + .getInstance()!! + .Identity() .addIdentityStateListener { user, previousUser -> latch.countDown() } - MParticle.getInstance()!!.Identity() + MParticle + .getInstance()!! + .Identity() .addIdentityStateListener { user, previousUser -> latch.countDown() } val request = IdentityApiRequest.withUser(MParticle.getInstance()!!.Identity().getUser(mpid1)).build() val result = MParticle.getInstance()!!.Identity().identify(request) - result.addSuccessListener { latch.countDown() } + result + .addSuccessListener { latch.countDown() } .addSuccessListener { latch.countDown() } .addSuccessListener { latch.countDown() } latch.await() @@ -156,33 +168,38 @@ class IdentityApiTest : BaseCleanStartedEachTest() { @Test @Throws(Exception::class) fun testRemoveIdentityStateListeners() { - mServer.addConditionalIdentityResponse(mStartingMpid, mpid1) + mServer + .addConditionalIdentityResponse(mStartingMpid, mpid1) .addConditionalIdentityResponse(mpid1, mpid2) val mpid1Latch: CountDownLatch = MPLatch(1) val mpid2Latch: CountDownLatch = MPLatch(1) - val keptIdStateListener = IdentityStateListener { user, previousUser -> - if (user.id == mpid1 && previousUser!!.id == mStartingMpid) { - mpid1Latch.countDown() - } - if (user.id == mpid2 && previousUser!!.id == mpid1) { - mpid2Latch.countDown() + val keptIdStateListener = + IdentityStateListener { user, previousUser -> + if (user.id == mpid1 && previousUser!!.id == mStartingMpid) { + mpid1Latch.countDown() + } + if (user.id == mpid2 && previousUser!!.id == mpid1) { + mpid2Latch.countDown() + } } - } - val removeIdStateListener1 = IdentityStateListener { user, previousUser -> - if (user.id != mpid1 || previousUser!!.id != mStartingMpid) { - Assert.fail("IdentityStateListener failed to be removed") + val removeIdStateListener1 = + IdentityStateListener { user, previousUser -> + if (user.id != mpid1 || previousUser!!.id != mStartingMpid) { + Assert.fail("IdentityStateListener failed to be removed") + } } - } - val removeIdStateListener2 = IdentityStateListener { user, previousUser -> - if (user.id != mpid1 || previousUser!!.id != mStartingMpid) { - Assert.fail("IdentityStateListener failed to be removed") + val removeIdStateListener2 = + IdentityStateListener { user, previousUser -> + if (user.id != mpid1 || previousUser!!.id != mStartingMpid) { + Assert.fail("IdentityStateListener failed to be removed") + } } - } - val removeIdStateListener3 = IdentityStateListener { user, previousUser -> - if (user.id != mpid1 || previousUser!!.id != mStartingMpid) { - Assert.fail("IdentityStateListener failed to be removed") + val removeIdStateListener3 = + IdentityStateListener { user, previousUser -> + if (user.id != mpid1 || previousUser!!.id != mStartingMpid) { + Assert.fail("IdentityStateListener failed to be removed") + } } - } MParticle.getInstance()!!.Identity().addIdentityStateListener(keptIdStateListener) MParticle.getInstance()!!.Identity().addIdentityStateListener(removeIdStateListener1) MParticle.getInstance()!!.Identity().addIdentityStateListener(removeIdStateListener2) @@ -214,13 +231,20 @@ class IdentityApiTest : BaseCleanStartedEachTest() { Assert.assertEquals(Looper.getMainLooper(), Looper.myLooper()) Assert.assertEquals( user.id, - MParticle.getInstance()!!.Identity().currentUser!! - .id + MParticle + .getInstance()!! + .Identity() + .currentUser!! + .id, ) called.value = true latch.countDown() } - MParticle.getInstance()!!.Internal().configManager.setMpid(mpid1, ran.nextBoolean()) + MParticle + .getInstance()!! + .Internal() + .configManager + .setMpid(mpid1, ran.nextBoolean()) } latch.await() Assert.assertTrue(called.value) @@ -253,26 +277,35 @@ class IdentityApiTest : BaseCleanStartedEachTest() { MParticle.getInstance()!!.Identity().addIdentityStateListener { user, previousUser -> Assert.assertEquals( mpid1, - MParticle.getInstance()!! - .Identity().currentUser!!.id + MParticle + .getInstance()!! + .Identity() + .currentUser!! + .id, ) Assert.assertEquals(mpid1, user.id) Assert.assertEquals(mStartingMpid.toLong(), previousUser!!.id) called1.value = true latch.countDown() } - MParticle.getInstance()!!.Identity().login() + MParticle + .getInstance()!! + .Identity() + .login() .addSuccessListener { result -> Assert.assertEquals( mpid1, - MParticle.getInstance()!! - .Identity().currentUser!!.id + MParticle + .getInstance()!! + .Identity() + .currentUser!! + .id, ) Assert.assertEquals(mpid1, result.user.id) Assert.assertEquals( mStartingMpid.toLong(), result.previousUser!! - .id + .id, ) called2.value = true latch.countDown() @@ -287,7 +320,7 @@ class IdentityApiTest : BaseCleanStartedEachTest() { mpid: Long, identityTypes: Map, userAttributes: Map?, - isLoggedIn: Boolean + isLoggedIn: Boolean, ) { Assert.assertTrue(dto1!!.id == mpid) if (userAttributes != null) { @@ -316,7 +349,11 @@ class IdentityApiTest : BaseCleanStartedEachTest() { fun testGetUser() { val identity = MParticle.getInstance()!!.Identity() Assert.assertNotNull(identity.currentUser) - MParticle.getInstance()!!.Internal().configManager.setMpid(mpid1, true) + MParticle + .getInstance()!! + .Internal() + .configManager + .setMpid(mpid1, true) Assert.assertEquals(identity.currentUser!!.id, mpid1) val mpid1UserAttributes: MutableMap = HashMap(mRandomUtils.getRandomAttributes(3)) @@ -325,9 +362,13 @@ class IdentityApiTest : BaseCleanStartedEachTest() { AccessUtils.setUserIdentities( mpid1UserIdentites, identity.currentUser!! - .id + .id, ) - MParticle.getInstance()!!.Internal().configManager.setMpid(mpid2, false) + MParticle + .getInstance()!! + .Internal() + .configManager + .setMpid(mpid2, false) val mpid2UserAttributes: MutableMap = HashMap(mRandomUtils.getRandomAttributes(3)) val mpid2UserIdentites = mRandomUtils.getRandomUserIdentities(3) @@ -335,9 +376,13 @@ class IdentityApiTest : BaseCleanStartedEachTest() { AccessUtils.setUserIdentities( mpid2UserIdentites, identity.currentUser!! - .id + .id, ) - MParticle.getInstance()!!.Internal().configManager.setMpid(mpid3, true) + MParticle + .getInstance()!! + .Internal() + .configManager + .setMpid(mpid3, true) val mpid3UserAttributes: MutableMap = HashMap(mRandomUtils.getRandomAttributes(3)) val mpid3UserIdentities = mRandomUtils.getRandomUserIdentities(2) @@ -345,12 +390,13 @@ class IdentityApiTest : BaseCleanStartedEachTest() { AccessUtils.setUserIdentities( mpid3UserIdentities, identity.currentUser!! - .id + .id, ) mpid1UserAttributes.remove(null) mpid2UserAttributes.remove(null) mpid3UserAttributes.remove(null) - com.mparticle.internal.AccessUtils.awaitMessageHandler() + com.mparticle.internal.AccessUtils + .awaitMessageHandler() // should return null for mpid = 0 Assert.assertNull(identity.getUser(0L)) @@ -362,21 +408,21 @@ class IdentityApiTest : BaseCleanStartedEachTest() { mpid1, mpid1UserIdentites, mpid1UserAttributes, - true + true, ) assertMParticleUserEquals( identity.getUser(mpid2), mpid2, mpid2UserIdentites, mpid2UserAttributes, - false + false, ) assertMParticleUserEquals( identity.getUser(mpid3), mpid3, mpid3UserIdentities, mpid3UserAttributes, - true + true, ) // should return null for unseen mpid's @@ -394,34 +440,65 @@ class IdentityApiTest : BaseCleanStartedEachTest() { fun testModifyConcurrentCalls() { Assert.assertEquals( mStartingMpid.toFloat(), - MParticle.getInstance()!! - .Identity().currentUser!!.id.toFloat(), - 0f + MParticle + .getInstance()!! + .Identity() + .currentUser!! + .id + .toFloat(), + 0f, ) val userIdentities = mRandomUtils.randomUserIdentities for (identity in userIdentities.keys) { AccessUtils.setUserIdentity(userIdentities[identity], identity, mStartingMpid) } - val request = IdentityApiRequest.withUser(MParticle.getInstance()!!.Identity().currentUser) - .customerId(mRandomUtils.getAlphaNumericString(24)).build() + val request = + IdentityApiRequest + .withUser(MParticle.getInstance()!!.Identity().currentUser) + .customerId(mRandomUtils.getAlphaNumericString(24)) + .build() val latch: CountDownLatch = MPLatch(1) mServer.waitForVerify(Matcher(mServer.Endpoints().getModifyUrl(mStartingMpid))) { request -> - Assert.assertEquals(1, request.asIdentityRequest().body.identity_changes.size.toLong()) + Assert.assertEquals( + 1, + request + .asIdentityRequest() + .body.identity_changes.size + .toLong(), + ) latch.countDown() } MParticle.getInstance()!!.Identity().modify(request) // change the mpid; // behind the scenes, this call will take place before the (above) modify request goes out, since // the modify request will be passed to a background thread before it is executed - MParticle.getInstance()!!.Internal().configManager.setMpid(mpid2, ran.nextBoolean()) + MParticle + .getInstance()!! + .Internal() + .configManager + .setMpid(mpid2, ran.nextBoolean()) latch.await() } @Test fun testGetUsersApi() { // test that by default there is only the starting user - Assert.assertEquals(MParticle.getInstance()!!.Identity().users.size.toLong(), 1) - Assert.assertEquals(MParticle.getInstance()!!.Identity().users[0].id, mStartingMpid) + Assert.assertEquals( + MParticle + .getInstance()!! + .Identity() + .users.size + .toLong(), + 1, + ) + Assert.assertEquals( + MParticle + .getInstance()!! + .Identity() + .users[0] + .id, + mStartingMpid, + ) // add 5 Users val mpids: MutableList = ArrayList() @@ -430,13 +507,21 @@ class IdentityApiTest : BaseCleanStartedEachTest() { mpids.add(ran.nextLong()) } for (mpid in mpids) { - MParticle.getInstance()!!.Internal().configManager.setMpid(mpid, ran.nextBoolean()) + MParticle + .getInstance()!! + .Internal() + .configManager + .setMpid(mpid, ran.nextBoolean()) } // test that there are now 6 users present in the getUsers() endpoint Assert.assertEquals( - MParticle.getInstance()!!.Identity().users.size.toLong(), - mpids.size.toLong() + MParticle + .getInstance()!! + .Identity() + .users.size + .toLong(), + mpids.size.toLong(), ) // test that they are the same users we added before @@ -446,11 +531,22 @@ class IdentityApiTest : BaseCleanStartedEachTest() { // remove 2 users for (i in 0..1) { - MParticle.getInstance()!!.Internal().configManager.deleteUserStorage(mpids.removeAt(i)) + MParticle + .getInstance()!! + .Internal() + .configManager + .deleteUserStorage(mpids.removeAt(i)) } // test that there are now 4 remaining users - Assert.assertEquals(MParticle.getInstance()!!.Identity().users.size.toLong(), 4) + Assert.assertEquals( + MParticle + .getInstance()!! + .Identity() + .users.size + .toLong(), + 4, + ) // test that they are the correct users for (mParticleUser in MParticle.getInstance()!!.Identity().users) { @@ -468,7 +564,11 @@ class IdentityApiTest : BaseCleanStartedEachTest() { for (user in MParticle.getInstance()!!.Identity().users) { Assert.assertNotSame(0, user.id) } - MParticle.getInstance()!!.Internal().configManager.setMpid(0L, ran.nextBoolean()) + MParticle + .getInstance()!! + .Internal() + .configManager + .setMpid(0L, ran.nextBoolean()) Assert.assertNull(MParticle.getInstance()!!.Identity().getUser(0L)) for (user in MParticle.getInstance()!!.Identity().users) { Assert.assertNotSame(0, user.id) @@ -495,26 +595,31 @@ class IdentityApiTest : BaseCleanStartedEachTest() { val latch: CountDownLatch = MPLatch(1) val currentUser = MParticle.getInstance()!!.Identity().currentUser val identityApi = MParticle.getInstance()!!.Identity() - val modifyRequest = IdentityApiRequest.withUser(currentUser) - .pushToken("new push", "old_push") - .build() - val taskSuccessListener = TaskSuccessListener { - identityApi.modify(modifyRequest) - mServer.waitForVerify( - Matcher(mServer.Endpoints().getModifyUrl(currentUser!!.id)) - ) { request -> - val identityChanges = request.asIdentityRequest().body.identity_changes - Assert.assertEquals(1, identityChanges.size.toLong()) - // make sure the customerId didn't change. it should not be included in the IdentityApiRequest - // since the request was built before customerId was set - Assert.assertTrue("customerid" != identityChanges[0].optString("identity_type")) - Assert.assertTrue("push_token" == identityChanges[0].optString("identity_type")) - latch.countDown() + val modifyRequest = + IdentityApiRequest + .withUser(currentUser) + .pushToken("new push", "old_push") + .build() + val taskSuccessListener = + TaskSuccessListener { + identityApi.modify(modifyRequest) + mServer.waitForVerify( + Matcher(mServer.Endpoints().getModifyUrl(currentUser!!.id)), + ) { request -> + val identityChanges = request.asIdentityRequest().body.identity_changes + Assert.assertEquals(1, identityChanges.size.toLong()) + // make sure the customerId didn't change. it should not be included in the IdentityApiRequest + // since the request was built before customerId was set + Assert.assertTrue("customerid" != identityChanges[0].optString("identity_type")) + Assert.assertTrue("push_token" == identityChanges[0].optString("identity_type")) + latch.countDown() + } } - } - val loginRequest = IdentityApiRequest.withUser(currentUser) - .customerId("my Id") - .build() + val loginRequest = + IdentityApiRequest + .withUser(currentUser) + .customerId("my Id") + .build() identityApi .login(loginRequest) .addSuccessListener(taskSuccessListener) @@ -527,26 +632,31 @@ class IdentityApiTest : BaseCleanStartedEachTest() { val latch: CountDownLatch = MPLatch(1) val currentUser = MParticle.getInstance()!!.Identity().currentUser val identityApi = MParticle.getInstance()!!.Identity() - val modifyRequest = IdentityApiRequest.withUser(currentUser) - .customerId("new customer ID") - .build() - val taskSuccessListener = TaskSuccessListener { - identityApi.modify(modifyRequest) - mServer.waitForVerify( - Matcher(mServer.Endpoints().getModifyUrl(currentUser!!.id)) - ) { request -> - val identityChanges = request.asIdentityRequest().body.identity_changes - Assert.assertEquals(1, identityChanges.size.toLong()) - // make sure the customerId used the correct "old" value - Assert.assertTrue("customerid" == identityChanges[0].optString("identity_type")) - Assert.assertEquals("new customer ID", identityChanges[0].optString("new_value")) - Assert.assertEquals("old customer ID", identityChanges[0].optString("old_value")) - latch.countDown() + val modifyRequest = + IdentityApiRequest + .withUser(currentUser) + .customerId("new customer ID") + .build() + val taskSuccessListener = + TaskSuccessListener { + identityApi.modify(modifyRequest) + mServer.waitForVerify( + Matcher(mServer.Endpoints().getModifyUrl(currentUser!!.id)), + ) { request -> + val identityChanges = request.asIdentityRequest().body.identity_changes + Assert.assertEquals(1, identityChanges.size.toLong()) + // make sure the customerId used the correct "old" value + Assert.assertTrue("customerid" == identityChanges[0].optString("identity_type")) + Assert.assertEquals("new customer ID", identityChanges[0].optString("new_value")) + Assert.assertEquals("old customer ID", identityChanges[0].optString("old_value")) + latch.countDown() + } } - } - val loginRequest = IdentityApiRequest.withUser(currentUser) - .customerId("old customer ID") - .build() + val loginRequest = + IdentityApiRequest + .withUser(currentUser) + .customerId("old customer ID") + .build() identityApi .login(loginRequest) .addSuccessListener(taskSuccessListener) @@ -560,11 +670,13 @@ class IdentityApiTest : BaseCleanStartedEachTest() { AccessUtils.setUserIdentity("facebook Id", IdentityType.Facebook, mStartingMpid) AccessUtils.setUserIdentity("other Id", IdentityType.Other2, mStartingMpid) val latch: CountDownLatch = MPLatch(1) - val request = IdentityApiRequest.withUser(MParticle.getInstance()!!.Identity().currentUser) - .customerId(null) - .userIdentity(IdentityType.Facebook, null) - .userIdentity(IdentityType.Other2, null) - .build() + val request = + IdentityApiRequest + .withUser(MParticle.getInstance()!!.Identity().currentUser) + .customerId(null) + .userIdentity(IdentityType.Facebook, null) + .userIdentity(IdentityType.Other2, null) + .build() MParticle.getInstance()!!.Identity().modify(request) mServer.waitForVerify(Matcher(mServer.Endpoints().getModifyUrl(mStartingMpid))) { request -> val identityChanges = request.asIdentityRequest().body.identity_changes @@ -572,7 +684,7 @@ class IdentityApiTest : BaseCleanStartedEachTest() { identityChanges.sortWith( Comparator { jsonObject, t1 -> jsonObject.optString("identity_type").compareTo(t1.optString("identity_type")) - } + }, ) // make sure the existing values were set to null diff --git a/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleIdentityClientImplTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleIdentityClientImplTest.kt index ffb3eecf2..4c40ea358 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleIdentityClientImplTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleIdentityClientImplTest.kt @@ -35,10 +35,15 @@ class MParticleIdentityClientImplTest : BaseCleanStartedEachTest() { val handler = Handler() handler.postDelayed({ Assert.fail("modify did not complete") }, (10 * 1000).toLong()) val called = AndroidUtils.Mutable(false) - MParticle.getInstance()?.Identity()?.modify(IdentityApiRequest.withEmptyUser().build()) + MParticle + .getInstance() + ?.Identity() + ?.modify(IdentityApiRequest.withEmptyUser().build()) ?.addSuccessListener { latch.countDown() - MParticle.getInstance()?.Identity() + MParticle + .getInstance() + ?.Identity() ?.modify(IdentityApiRequest.withEmptyUser().build()) ?.addSuccessListener { val currentModifyRequestCount = mServer.Requests().modify.size @@ -49,10 +54,8 @@ class MParticleIdentityClientImplTest : BaseCleanStartedEachTest() { // handler.removeCallbacks(null) called.value = true latch.countDown() - } - ?.addFailureListener { Assert.fail("task failed") } - } - ?.addFailureListener { Assert.fail("task failed") } + }?.addFailureListener { Assert.fail("task failed") } + }?.addFailureListener { Assert.fail("task failed") } latch.await() Assert.assertTrue(called.value) } @@ -65,43 +68,47 @@ class MParticleIdentityClientImplTest : BaseCleanStartedEachTest() { val userIdentities = mRandomUtils.randomUserIdentities val checked = MutableBoolean(false) val latch = CountDownLatch(1) - setApiClient(object : MockIdentityApiClient { - @Throws(IOException::class, JSONException::class) - override fun makeUrlRequest( - connection: MPConnection, - payload: String?, - mparticle: Boolean - ) { - if (connection.url.toString().contains("/identify")) { - val jsonObject = JSONObject(payload) - val knownIdentities = - jsonObject.getJSONObject(MParticleIdentityClientImpl.KNOWN_IDENTITIES) - Assert.assertNotNull(knownIdentities) - checkStaticsAndRemove(knownIdentities) - if (knownIdentities.length() != userIdentities.size) { - Assert.assertEquals( - knownIdentities.length().toLong(), - userIdentities.size.toLong() - ) - } - for ((key, value1) in userIdentities) { - val value = knownIdentities.getString( - MParticleIdentityClientImpl.getStringValue( - key + setApiClient( + object : MockIdentityApiClient { + @Throws(IOException::class, JSONException::class) + override fun makeUrlRequest( + connection: MPConnection, + payload: String?, + mparticle: Boolean, + ) { + if (connection.url.toString().contains("/identify")) { + val jsonObject = JSONObject(payload) + val knownIdentities = + jsonObject.getJSONObject(MParticleIdentityClientImpl.KNOWN_IDENTITIES) + Assert.assertNotNull(knownIdentities) + checkStaticsAndRemove(knownIdentities) + if (knownIdentities.length() != userIdentities.size) { + Assert.assertEquals( + knownIdentities.length().toLong(), + userIdentities.size.toLong(), ) - ) - Assert.assertEquals(value, value1) + } + for ((key, value1) in userIdentities) { + val value = + knownIdentities.getString( + MParticleIdentityClientImpl.getStringValue( + key, + ), + ) + Assert.assertEquals(value, value1) + } + checked.value = true + setApiClient(null) + latch.countDown() } - checked.value = true - setApiClient(null) - latch.countDown() } - } - }) + }, + ) mApiClient?.identify( - IdentityApiRequest.withEmptyUser() + IdentityApiRequest + .withEmptyUser() .userIdentities(userIdentities) - .build() + .build(), ) latch.await() Assert.assertTrue(checked.value) @@ -116,40 +123,44 @@ class MParticleIdentityClientImplTest : BaseCleanStartedEachTest() { val latch: CountDownLatch = MPLatch(1) val checked = MutableBoolean(false) val userIdentities = mRandomUtils.randomUserIdentities - setApiClient(object : MockIdentityApiClient { - @Throws(IOException::class, JSONException::class) - override fun makeUrlRequest( - connection: MPConnection, - payload: String?, - mparticle: Boolean - ) { - if (connection.url.toString().contains("/login")) { - val jsonObject = JSONObject(payload) - val knownIdentities = - jsonObject.getJSONObject(MParticleIdentityClientImpl.KNOWN_IDENTITIES) - Assert.assertNotNull(knownIdentities) - checkStaticsAndRemove(knownIdentities) - Assert.assertEquals( - knownIdentities.length().toLong(), - userIdentities.size.toLong() - ) - for ((key, value1) in userIdentities) { - val value = knownIdentities.getString( - MParticleIdentityClientImpl.getStringValue( - key - ) + setApiClient( + object : MockIdentityApiClient { + @Throws(IOException::class, JSONException::class) + override fun makeUrlRequest( + connection: MPConnection, + payload: String?, + mparticle: Boolean, + ) { + if (connection.url.toString().contains("/login")) { + val jsonObject = JSONObject(payload) + val knownIdentities = + jsonObject.getJSONObject(MParticleIdentityClientImpl.KNOWN_IDENTITIES) + Assert.assertNotNull(knownIdentities) + checkStaticsAndRemove(knownIdentities) + Assert.assertEquals( + knownIdentities.length().toLong(), + userIdentities.size.toLong(), ) - Assert.assertEquals(value, value1) + for ((key, value1) in userIdentities) { + val value = + knownIdentities.getString( + MParticleIdentityClientImpl.getStringValue( + key, + ), + ) + Assert.assertEquals(value, value1) + } + checked.value = true + latch.countDown() } - checked.value = true - latch.countDown() } - } - }) + }, + ) mApiClient?.login( - IdentityApiRequest.withEmptyUser() + IdentityApiRequest + .withEmptyUser() .userIdentities(userIdentities) - .build() + .build(), ) latch.await() Assert.assertTrue(checked.value) @@ -164,44 +175,48 @@ class MParticleIdentityClientImplTest : BaseCleanStartedEachTest() { val userIdentities = mRandomUtils.randomUserIdentities val latch: CountDownLatch = MPLatch(1) val checked = MutableBoolean(false) - setApiClient(object : MockIdentityApiClient { - @Throws(IOException::class, JSONException::class) - override fun makeUrlRequest( - connection: MPConnection, - payload: String?, - mparticle: Boolean - ) { - if (connection.url.toString().contains("/logout")) { - val jsonObject = payload?.let { JSONObject(it) } - val knownIdentities = - jsonObject?.getJSONObject(MParticleIdentityClientImpl.KNOWN_IDENTITIES) - Assert.assertNotNull(knownIdentities) - if (knownIdentities != null) { - checkStaticsAndRemove(knownIdentities) - } - if (knownIdentities != null) { - Assert.assertEquals( - knownIdentities.length().toLong(), - userIdentities.size.toLong() - ) - } - for ((key, value1) in userIdentities) { - val value = knownIdentities?.getString( - MParticleIdentityClientImpl.getStringValue( - key + setApiClient( + object : MockIdentityApiClient { + @Throws(IOException::class, JSONException::class) + override fun makeUrlRequest( + connection: MPConnection, + payload: String?, + mparticle: Boolean, + ) { + if (connection.url.toString().contains("/logout")) { + val jsonObject = payload?.let { JSONObject(it) } + val knownIdentities = + jsonObject?.getJSONObject(MParticleIdentityClientImpl.KNOWN_IDENTITIES) + Assert.assertNotNull(knownIdentities) + if (knownIdentities != null) { + checkStaticsAndRemove(knownIdentities) + } + if (knownIdentities != null) { + Assert.assertEquals( + knownIdentities.length().toLong(), + userIdentities.size.toLong(), ) - ) - Assert.assertEquals(value, value1) + } + for ((key, value1) in userIdentities) { + val value = + knownIdentities?.getString( + MParticleIdentityClientImpl.getStringValue( + key, + ), + ) + Assert.assertEquals(value, value1) + } + checked.value = true + latch.countDown() } - checked.value = true - latch.countDown() } - } - }) + }, + ) mApiClient?.logout( - IdentityApiRequest.withEmptyUser() + IdentityApiRequest + .withEmptyUser() .userIdentities(userIdentities) - .build() + .build(), ) latch.await() Assert.assertTrue(checked.value) @@ -217,67 +232,74 @@ class MParticleIdentityClientImplTest : BaseCleanStartedEachTest() { val oldUserIdentities = mRandomUtils.randomUserIdentities val newUserIdentities = mRandomUtils.randomUserIdentities ( - MParticle.getInstance() - ?.Identity()?.currentUser as MParticleUserImpl? - )?.userIdentities = oldUserIdentities + MParticle + .getInstance() + ?.Identity() + ?.currentUser as MParticleUserImpl? + )?.userIdentities = oldUserIdentities val latch: CountDownLatch = MPLatch(1) val checked = MutableBoolean(false) - setApiClient(object : MockIdentityApiClient { - @Throws(IOException::class, JSONException::class) - override fun makeUrlRequest( - connection: MPConnection, - payload: String?, - mparticle: Boolean - ) { - if (connection.url.toString() - .contains(MParticleIdentityClientImpl.MODIFY_PATH) + setApiClient( + object : MockIdentityApiClient { + @Throws(IOException::class, JSONException::class) + override fun makeUrlRequest( + connection: MPConnection, + payload: String?, + mparticle: Boolean, ) { - val jsonObject = payload?.let { JSONObject(it) } - val changedIdentities = - jsonObject?.getJSONArray(MParticleIdentityClientImpl.IDENTITY_CHANGES) - if (changedIdentities != null) { - for (i in 0 until changedIdentities.length()) { - val changeJson = changedIdentities.getJSONObject(i) - val newValue: Any = - changeJson.getString(MParticleIdentityClientImpl.NEW_VALUE) - val oldValue: Any = - changeJson.getString(MParticleIdentityClientImpl.OLD_VALUE) - val identityType = MParticleIdentityClientImpl.getIdentityType( - changeJson.getString(MParticleIdentityClientImpl.IDENTITY_TYPE) - ) - val nullString = JSONObject.NULL.toString() - if (oldUserIdentities[identityType] == null) { - if (oldValue != JSONObject.NULL.toString()) { - Assert.fail() + if (connection.url + .toString() + .contains(MParticleIdentityClientImpl.MODIFY_PATH) + ) { + val jsonObject = payload?.let { JSONObject(it) } + val changedIdentities = + jsonObject?.getJSONArray(MParticleIdentityClientImpl.IDENTITY_CHANGES) + if (changedIdentities != null) { + for (i in 0 until changedIdentities.length()) { + val changeJson = changedIdentities.getJSONObject(i) + val newValue: Any = + changeJson.getString(MParticleIdentityClientImpl.NEW_VALUE) + val oldValue: Any = + changeJson.getString(MParticleIdentityClientImpl.OLD_VALUE) + val identityType = + MParticleIdentityClientImpl.getIdentityType( + changeJson.getString(MParticleIdentityClientImpl.IDENTITY_TYPE), + ) + val nullString = JSONObject.NULL.toString() + if (oldUserIdentities[identityType] == null) { + if (oldValue != JSONObject.NULL.toString()) { + Assert.fail() + } + } else { + Assert.assertEquals( + oldValue, + oldUserIdentities[identityType], + ) } - } else { - Assert.assertEquals( - oldValue, - oldUserIdentities[identityType] - ) - } - if (newUserIdentities[identityType] == null) { - if (newValue != nullString) { - Assert.fail() + if (newUserIdentities[identityType] == null) { + if (newValue != nullString) { + Assert.fail() + } + } else { + Assert.assertEquals( + newValue, + newUserIdentities[identityType], + ) } - } else { - Assert.assertEquals( - newValue, - newUserIdentities[identityType] - ) } } + setApiClient(null) + checked.value = true + latch.countDown() } - setApiClient(null) - checked.value = true - latch.countDown() } - } - }) + }, + ) mApiClient?.modify( - IdentityApiRequest.withEmptyUser() + IdentityApiRequest + .withEmptyUser() .userIdentities(newUserIdentities) - .build() + .build(), ) latch.await() Assert.assertTrue(checked.value) @@ -285,28 +307,29 @@ class MParticleIdentityClientImplTest : BaseCleanStartedEachTest() { } private fun setApiClient(identityClient: MockIdentityApiClient?) { - mApiClient = object : MParticleIdentityClientImpl( - mContext, - mConfigManager, - MParticle.OperatingSystem.ANDROID - ) { - @Throws(IOException::class) - override fun makeUrlRequest( - endpoint: Endpoint, - connection: MPConnection, - payload: String, - identity: Boolean - ): MPConnection { - try { - identityClient?.makeUrlRequest(connection, payload, identity) - } catch (e: JSONException) { - e.printStackTrace() - Assert.fail(e.message) + mApiClient = + object : MParticleIdentityClientImpl( + mContext, + mConfigManager, + MParticle.OperatingSystem.ANDROID, + ) { + @Throws(IOException::class) + override fun makeUrlRequest( + endpoint: Endpoint, + connection: MPConnection, + payload: String, + identity: Boolean, + ): MPConnection { + try { + identityClient?.makeUrlRequest(connection, payload, identity) + } catch (e: JSONException) { + e.printStackTrace() + Assert.fail(e.message) + } + (connection as MPConnectionTestImpl).responseCode = 202 + return connection } - (connection as MPConnectionTestImpl).responseCode = 202 - return connection } - } MParticle.getInstance()?.Identity()?.apiClient = mApiClient } @@ -315,20 +338,21 @@ class MParticleIdentityClientImplTest : BaseCleanStartedEachTest() { if (knowIdentites.has(MParticleIdentityClientImpl.ANDROID_AAID)) { Assert.assertEquals( MPUtility.getAdIdInfo(mContext)?.id, - knowIdentites.getString(MParticleIdentityClientImpl.ANDROID_AAID) + knowIdentites.getString(MParticleIdentityClientImpl.ANDROID_AAID), ) knowIdentites.remove(MParticleIdentityClientImpl.ANDROID_AAID) } else { Assert.assertTrue( - MPUtility.getAdIdInfo(mContext) == null || MPUtility.isEmpty( - MPUtility.getAdIdInfo(mContext)?.id - ) + MPUtility.getAdIdInfo(mContext) == null || + MPUtility.isEmpty( + MPUtility.getAdIdInfo(mContext)?.id, + ), ) } if (knowIdentites.has(MParticleIdentityClientImpl.ANDROID_UUID)) { Assert.assertEquals( MPUtility.getAndroidID(mContext), - knowIdentites.getString(MParticleIdentityClientImpl.ANDROID_UUID) + knowIdentites.getString(MParticleIdentityClientImpl.ANDROID_UUID), ) knowIdentites.remove(MParticleIdentityClientImpl.ANDROID_UUID) } else { @@ -337,7 +361,7 @@ class MParticleIdentityClientImplTest : BaseCleanStartedEachTest() { if (knowIdentites.has(MParticleIdentityClientImpl.PUSH_TOKEN)) { Assert.assertEquals( mConfigManager?.pushInstanceId, - knowIdentites.getString(MParticleIdentityClientImpl.PUSH_TOKEN) + knowIdentites.getString(MParticleIdentityClientImpl.PUSH_TOKEN), ) knowIdentites.remove(MParticleIdentityClientImpl.PUSH_TOKEN) } else { @@ -346,13 +370,17 @@ class MParticleIdentityClientImplTest : BaseCleanStartedEachTest() { Assert.assertTrue(knowIdentites.has(MParticleIdentityClientImpl.DEVICE_APPLICATION_STAMP)) Assert.assertEquals( mConfigManager?.deviceApplicationStamp, - knowIdentites[MParticleIdentityClientImpl.DEVICE_APPLICATION_STAMP] + knowIdentites[MParticleIdentityClientImpl.DEVICE_APPLICATION_STAMP], ) knowIdentites.remove(MParticleIdentityClientImpl.DEVICE_APPLICATION_STAMP) } internal interface MockIdentityApiClient { @Throws(IOException::class, JSONException::class) - fun makeUrlRequest(connection: MPConnection, payload: String?, mparticle: Boolean) + fun makeUrlRequest( + connection: MPConnection, + payload: String?, + mparticle: Boolean, + ) } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleUserDelegateITest.kt b/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleUserDelegateITest.kt index 23e507f99..890b288b3 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleUserDelegateITest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleUserDelegateITest.kt @@ -71,7 +71,7 @@ class MParticleUserDelegateITest : BaseCleanStartedEachTest() { for (j in 0..2) { val key = mRandomUtils.getAlphaNumericString(mRandomUtils.randomInt(1, 55)).uppercase( - Locale.getDefault() + Locale.getDefault(), ) val value = mRandomUtils.getAlphaNumericString(mRandomUtils.randomInt(1, 55)) Assert.assertTrue(mUserDelegate.setUserAttribute(key, value, mpid, false)) @@ -123,12 +123,21 @@ class MParticleUserDelegateITest : BaseCleanStartedEachTest() { mUserDelegate.setConsentState(builder.build(), mpid2) builder.setCCPAConsentState(CCPAConsent.builder(false).build()) mUserDelegate.setConsentState(builder.build(), mpid2) - Assert.assertEquals(1, mUserDelegate.getConsentState(mpid).gdprConsentState.size.toLong()) + Assert.assertEquals( + 1, + mUserDelegate + .getConsentState(mpid) + .gdprConsentState.size + .toLong(), + ) Assert.assertTrue(mUserDelegate.getConsentState(mpid).gdprConsentState.containsKey("foo")) Assert.assertNull(mUserDelegate.getConsentState(mpid).ccpaConsentState) Assert.assertEquals( 2, - mUserDelegate.getConsentState(mpid2).gdprConsentState.size.toLong() + mUserDelegate + .getConsentState(mpid2) + .gdprConsentState.size + .toLong(), ) Assert.assertTrue(mUserDelegate.getConsentState(mpid2).gdprConsentState.containsKey("foo")) Assert.assertTrue(mUserDelegate.getConsentState(mpid2).gdprConsentState.containsKey("foo2")) @@ -147,11 +156,23 @@ class MParticleUserDelegateITest : BaseCleanStartedEachTest() { builder.addGDPRConsentState("foo", GDPRConsent.builder(true).build()) builder.setCCPAConsentState(CCPAConsent.builder(true).build()) mUserDelegate.setConsentState(builder.build(), mpid) - Assert.assertEquals(1, mUserDelegate.getConsentState(mpid).gdprConsentState.size.toLong()) + Assert.assertEquals( + 1, + mUserDelegate + .getConsentState(mpid) + .gdprConsentState.size + .toLong(), + ) Assert.assertNotNull(mUserDelegate.getConsentState(mpid).ccpaConsentState) Assert.assertTrue(mUserDelegate.getConsentState(mpid).gdprConsentState.containsKey("foo")) mUserDelegate.setConsentState(null, mpid) - Assert.assertEquals(0, mUserDelegate.getConsentState(mpid).gdprConsentState.size.toLong()) + Assert.assertEquals( + 0, + mUserDelegate + .getConsentState(mpid) + .gdprConsentState.size + .toLong(), + ) Assert.assertNull(mUserDelegate.getConsentState(mpid).ccpaConsentState) } @@ -179,7 +200,7 @@ class MParticleUserDelegateITest : BaseCleanStartedEachTest() { userAttributesResults.value = userAttributes userAttributeListResults.value = userAttributeLists }, - mStartingMpid + mStartingMpid, ) assertMapEquals(attributeSingles, userAttributesResults.value) assertMapEquals(attributeLists, userAttributeListResults.value) @@ -195,7 +216,7 @@ class MParticleUserDelegateITest : BaseCleanStartedEachTest() { userAttributeListResults.value = userAttributeLists latch.countDown() }, - mStartingMpid + mStartingMpid, ) } latch.await() @@ -203,15 +224,17 @@ class MParticleUserDelegateITest : BaseCleanStartedEachTest() { assertMapEquals(attributeLists, userAttributeListResults.value) } - private fun assertMapEquals(map1: Map<*, *>, map2: Map<*, *>?) { + private fun assertMapEquals( + map1: Map<*, *>, + map2: Map<*, *>?, + ) { Assert.assertEquals( """ - $map1 - - vs$map2 + $map1 + vs$map2 """.trimIndent(), map1.size.toLong(), - map2?.size?.toLong() + map2?.size?.toLong(), ) for (obj in map1.entries) { val (key, value) = obj diff --git a/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleUserTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleUserTest.kt index 0f8a51fe9..4e8aca888 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleUserTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleUserTest.kt @@ -17,7 +17,7 @@ class MParticleUserTest : BaseCleanStartedEachTest() { Assert.assertEquals( it.toFloat(), System.currentTimeMillis().toFloat(), - 10f + 10f, ) } if (user != null) { @@ -26,7 +26,10 @@ class MParticleUserTest : BaseCleanStartedEachTest() { val newMpid = ran.nextLong() mServer.addConditionalLoginResponse(mStartingMpid, newMpid) val latch = MPLatch(1) - MParticle.getInstance()?.Identity()?.login() + MParticle + .getInstance() + ?.Identity() + ?.login() ?.addFailureListener { Assert.fail("Identity Request Failed") } ?.addSuccessListener { latch.countDown() } latch.await() @@ -40,7 +43,7 @@ class MParticleUserTest : BaseCleanStartedEachTest() { Assert.assertEquals( user1.lastSeenTime.toFloat(), System.currentTimeMillis().toFloat(), - 10f + 10f, ) } Assert.assertEquals(userFirstSeen, user?.firstSeenTime) diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/AppStateManagerInstrumentedTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/AppStateManagerInstrumentedTest.kt index ff2182fe9..9648a9dfb 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/AppStateManagerInstrumentedTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/AppStateManagerInstrumentedTest.kt @@ -23,7 +23,11 @@ class AppStateManagerInstrumentedTest : BaseCleanStartedEachTest() { @Throws(Exception::class) fun before() { mAppStateManager = MParticle.getInstance()?.Internal()?.appStateManager - MParticle.getInstance()?.Internal()?.configManager?.setMpid(Constants.TEMPORARY_MPID, false) + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.setMpid(Constants.TEMPORARY_MPID, false) } @Test @@ -56,7 +60,7 @@ class AppStateManagerInstrumentedTest : BaseCleanStartedEachTest() { e.printStackTrace() } } - } + }, ) mAppStateManager?.endSession() latch.await() @@ -96,7 +100,7 @@ class AppStateManagerInstrumentedTest : BaseCleanStartedEachTest() { e.printStackTrace() } } - } + }, ) mAppStateManager?.endSession() latch.await() @@ -105,22 +109,25 @@ class AppStateManagerInstrumentedTest : BaseCleanStartedEachTest() { @Test @Throws(InterruptedException::class) - fun testOnApplicationForeground() = runTest(StandardTestDispatcher()) { - val latch: CountDownLatch = MPLatch(2) - val kitManagerTester = KitManagerTester(mContext, latch) - com.mparticle.AccessUtils.setKitManager(kitManagerTester) - goToBackground() - Assert.assertNull(mAppStateManager?.currentActivity) - Thread.sleep(AppStateManager.ACTIVITY_DELAY + 100) - goToForeground() - Assert.assertNotNull(mAppStateManager?.currentActivity?.get()) - latch.await() - Assert.assertTrue(kitManagerTester.onApplicationBackgroundCalled) - Assert.assertTrue(kitManagerTester.onApplicationForegroundCalled) - } + fun testOnApplicationForeground() = + runTest(StandardTestDispatcher()) { + val latch: CountDownLatch = MPLatch(2) + val kitManagerTester = KitManagerTester(mContext, latch) + com.mparticle.AccessUtils.setKitManager(kitManagerTester) + goToBackground() + Assert.assertNull(mAppStateManager?.currentActivity) + Thread.sleep(AppStateManager.ACTIVITY_DELAY + 100) + goToForeground() + Assert.assertNotNull(mAppStateManager?.currentActivity?.get()) + latch.await() + Assert.assertTrue(kitManagerTester.onApplicationBackgroundCalled) + Assert.assertTrue(kitManagerTester.onApplicationForegroundCalled) + } - internal inner class KitManagerTester(context: Context?, var latch: CountDownLatch) : - KitFrameworkWrapper( + internal inner class KitManagerTester( + context: Context?, + var latch: CountDownLatch, + ) : KitFrameworkWrapper( context, object : ReportingManager { override fun log(message: JsonReportingMessage) { @@ -133,10 +140,11 @@ class AppStateManagerInstrumentedTest : BaseCleanStartedEachTest() { }, MParticle.getInstance()?.Internal()?.configManager, MParticle.getInstance()?.Internal()?.appStateManager, - MParticleOptions.builder(mContext).credentials("some", "key").build() + MParticleOptions.builder(mContext).credentials("some", "key").build(), ) { var onApplicationBackgroundCalled = false var onApplicationForegroundCalled = false + override fun onApplicationBackground() { Assert.assertNull(currentActivity) onApplicationBackgroundCalled = true diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/ApplicationContextWrapperITest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/ApplicationContextWrapperITest.kt index 52c923913..701d22c79 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/ApplicationContextWrapperITest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/ApplicationContextWrapperITest.kt @@ -10,7 +10,6 @@ import org.junit.Assert.assertNull import org.junit.Test class ApplicationContextWrapperITest { - /** * This test specifically addresses a problem we had where a callback was being registered on a * new thread which was not initialized as a looper. This setup (not extending BaseAbstractTest) @@ -19,10 +18,13 @@ class ApplicationContextWrapperITest { @OrchestratorOnly @Test fun testRegisterListenerBackgroundThread() { - val applicationContextWrapper = ApplicationContextWrapper( - InstrumentationRegistry.getInstrumentation() - .getContext().applicationContext as Application - ) + val applicationContextWrapper = + ApplicationContextWrapper( + InstrumentationRegistry + .getInstrumentation() + .getContext() + .applicationContext as Application, + ) var exception: Exception? = null assertNull(Looper.myLooper()) try { @@ -37,11 +39,23 @@ class ApplicationContextWrapperITest { class MockCallbacks : Application.ActivityLifecycleCallbacks { override fun onActivityPaused(p0: Activity) {} + override fun onActivityResumed(p0: Activity) {} + override fun onActivityStarted(p0: Activity) {} + override fun onActivityDestroyed(p0: Activity) {} - override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {} + + override fun onActivitySaveInstanceState( + p0: Activity, + p1: Bundle, + ) {} + override fun onActivityStopped(p0: Activity) {} - override fun onActivityCreated(p0: Activity, savedInstanceState: Bundle?) {} + + override fun onActivityCreated( + p0: Activity, + savedInstanceState: Bundle?, + ) {} } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/BatchSessionInfoTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/BatchSessionInfoTest.kt index 23d47fead..f3f4a18a4 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/BatchSessionInfoTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/BatchSessionInfoTest.kt @@ -11,12 +11,10 @@ import kotlin.test.assertEquals import kotlin.test.assertNotEquals class BatchSessionInfoTest : BaseCleanStartedEachTest() { - override fun useInMemoryDatabase() = true - override fun transformMParticleOptions(builder: MParticleOptions.Builder): MParticleOptions.Builder { - return builder.logLevel(MParticle.LogLevel.INFO) - } + override fun transformMParticleOptions(builder: MParticleOptions.Builder): MParticleOptions.Builder = + builder.logLevel(MParticle.LogLevel.INFO) /** * This test is in response to a bug where, when many messages (> 1 batch worth) @@ -60,7 +58,7 @@ class BatchSessionInfoTest : BaseCleanStartedEachTest() { assertEquals("111", version) MParticle.getInstance()?.upload() messageCount >= 150 - } + }, ) MParticle.getInstance()?.apply { @@ -73,7 +71,7 @@ class BatchSessionInfoTest : BaseCleanStartedEachTest() { it.getJSONObject("ai").getString(Constants.MessageKey.INSTALL_REFERRER) assertEquals("222", version) true - } + }, ) } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigManagerInstrumentedTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigManagerInstrumentedTest.kt index cd4680d43..9faaebaf5 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigManagerInstrumentedTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigManagerInstrumentedTest.kt @@ -26,56 +26,89 @@ class ConfigManagerInstrumentedTest : BaseAbstractTest() { val configManager = MParticle.getInstance()?.Internal()?.configManager TestCase.assertEquals( mStartingMpid.toLong(), - MParticle.getInstance() - ?.Identity()?.currentUser?.id + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.id, ) TestCase.assertEquals(mStartingMpid.toLong(), configManager?.mpid) configManager?.setMpid(mpid1, ran.nextBoolean()) TestCase.assertEquals( mpid1, - MParticle.getInstance() - ?.Identity()?.currentUser?.id + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.id, ) - val newIsLoggedIn = !MParticle.getInstance() - ?.Identity()?.currentUser?.isLoggedIn!! + val newIsLoggedIn = + !MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.isLoggedIn!! configManager?.setMpid(mpid1, newIsLoggedIn) TestCase.assertEquals( mpid1, - MParticle.getInstance() - ?.Identity()?.currentUser?.id + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.id, ) TestCase.assertEquals( newIsLoggedIn, - MParticle.getInstance() - ?.Identity()?.currentUser?.isLoggedIn + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.isLoggedIn, ) configManager?.setMpid(mpid2, false) TestCase.assertEquals( mpid2, - MParticle.getInstance() - ?.Identity()?.currentUser?.id + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.id, ) MParticle.getInstance()?.Identity()?.currentUser?.isLoggedIn?.let { TestCase.assertFalse( - it + it, ) } configManager?.setMpid(mpid2, true) TestCase.assertEquals( mpid2, - MParticle.getInstance() - ?.Identity()?.currentUser?.id + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.id, ) - MParticle.getInstance() - ?.Identity()?.currentUser?.isLoggedIn?.let { TestCase.assertTrue(it) } + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.isLoggedIn + ?.let { TestCase.assertTrue(it) } configManager?.setMpid(mpid3, true) TestCase.assertEquals( mpid3, - MParticle.getInstance() - ?.Identity()?.currentUser?.id + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.id, ) - MParticle.getInstance() - ?.Identity()?.currentUser?.isLoggedIn?.let { TestCase.assertTrue(it) } + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.isLoggedIn + ?.let { TestCase.assertTrue(it) } } @Test @@ -83,24 +116,34 @@ class ConfigManagerInstrumentedTest : BaseAbstractTest() { fun testConfigResponseParsing() { val token = mRandomUtils.getAlphaNumericString(20) val aliasMaxWindow = ran.nextInt() - val config = JSONObject() - .put("wst", token) - .put(ConfigManager.ALIAS_MAX_WINDOW, aliasMaxWindow) + val config = + JSONObject() + .put("wst", token) + .put(ConfigManager.ALIAS_MAX_WINDOW, aliasMaxWindow) mServer.setupConfigResponse(config.toString()) var configLoadedListener = BothConfigsLoadedListener() var latch = configLoadedListener.latch startMParticle( - MParticleOptions.builder(mContext) - .configuration(AddConfigListener(configLoadedListener)) + MParticleOptions + .builder(mContext) + .configuration(AddConfigListener(configLoadedListener)), ) latch.await() TestCase.assertEquals( token, - MParticle.getInstance()?.Internal()?.configManager?.workspaceToken + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.workspaceToken, ) TestCase.assertEquals( aliasMaxWindow, - MParticle.getInstance()?.Internal()?.configManager?.aliasMaxWindow + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.aliasMaxWindow, ) // test set defaults when fields are not present @@ -109,17 +152,26 @@ class ConfigManagerInstrumentedTest : BaseAbstractTest() { configLoadedListener = BothConfigsLoadedListener() latch = configLoadedListener.latch startMParticle( - MParticleOptions.builder(mContext) - .configuration(AddConfigListener(configLoadedListener)) + MParticleOptions + .builder(mContext) + .configuration(AddConfigListener(configLoadedListener)), ) latch.await() TestCase.assertEquals( "", - MParticle.getInstance()?.Internal()?.configManager?.workspaceToken + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.workspaceToken, ) TestCase.assertEquals( 90, - MParticle.getInstance()?.Internal()?.configManager?.aliasMaxWindow + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.aliasMaxWindow, ) } @@ -131,40 +183,44 @@ class ConfigManagerInstrumentedTest : BaseAbstractTest() { val loadedKitLocal = AndroidUtils.Mutable(false) setCachedConfig(simpleConfigWithKits) mServer.setupConfigDeferred() - val configLoadedListener = ConfigLoadedListener { configType, isNew -> - if (!isNew) { - when (configType) { - ConfigType.CORE -> { - if (loadedCoreLocal.value) { - Assert.fail("core config already loaded") - } else { - Logger.error("LOADED CACHED Core") - loadedCoreLocal.value = true - } - if (loadedKitLocal.value) { - Assert.fail("kit config already loaded") - } else { - Logger.error("LOADED CACHED Kit") - loadedKitLocal.value = true + val configLoadedListener = + ConfigLoadedListener { configType, isNew -> + if (!isNew) { + when (configType) { + ConfigType.CORE -> { + if (loadedCoreLocal.value) { + Assert.fail("core config already loaded") + } else { + Logger.error("LOADED CACHED Core") + loadedCoreLocal.value = true + } + if (loadedKitLocal.value) { + Assert.fail("kit config already loaded") + } else { + Logger.error("LOADED CACHED Kit") + loadedKitLocal.value = true + } } - } - ConfigType.KIT -> if (loadedKitLocal.value) { - Assert.fail("kit config already loaded") - } else { - Logger.error("LOADED CACHED Kit") - loadedKitLocal.value = true + ConfigType.KIT -> + if (loadedKitLocal.value) { + Assert.fail("kit config already loaded") + } else { + Logger.error("LOADED CACHED Kit") + loadedKitLocal.value = true + } } } + if (loadedCoreLocal.value && loadedKitLocal.value) { + latch.countDown() + } + Logger.error("KIT = " + loadedKitLocal.value + " Core: " + loadedCoreLocal.value) } - if (loadedCoreLocal.value && loadedKitLocal.value) { - latch.countDown() - } - Logger.error("KIT = " + loadedKitLocal.value + " Core: " + loadedCoreLocal.value) - } - val options = MParticleOptions.builder(mContext) - .credentials("key", "secret") - .configuration(AddConfigListener(configLoadedListener)) - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials("key", "secret") + .configuration(AddConfigListener(configLoadedListener)) + .build() MParticle.start(options) // wait until both local configs are loaded @@ -183,13 +239,14 @@ class ConfigManagerInstrumentedTest : BaseAbstractTest() { val bothConfigsLoadedListener = BothConfigsLoadedListener() val reloadLatch = bothConfigsLoadedListener.latch MParticle.getInstance()?.Internal()?.configManager?.addConfigUpdatedListener( - bothConfigsLoadedListener + bothConfigsLoadedListener, ) reloadLatch.await() } - internal inner class BothConfigsLoadedListener(vararg configTypes: ConfigType) : - ConfigLoadedListener { + internal inner class BothConfigsLoadedListener( + vararg configTypes: ConfigType, + ) : ConfigLoadedListener { private var types: MutableSet var latch = MPLatch(1) @@ -201,7 +258,10 @@ class ConfigManagerInstrumentedTest : BaseAbstractTest() { types = HashSet(listOf(*configTypes)) } - override fun onConfigUpdated(configType: ConfigType, isNew: Boolean) { + override fun onConfigUpdated( + configType: ConfigType, + isNew: Boolean, + ) { if (isNew) { types.remove(configType) } @@ -211,11 +271,10 @@ class ConfigManagerInstrumentedTest : BaseAbstractTest() { } } - internal inner class AddConfigListener(private var configLoadedListener: ConfigLoadedListener) : - Configuration { - override fun configures(): Class { - return ConfigManager::class.java - } + internal inner class AddConfigListener( + private var configLoadedListener: ConfigLoadedListener, + ) : Configuration { + override fun configures(): Class = ConfigManager::class.java override fun apply(configManager: ConfigManager?) { configManager?.addConfigUpdatedListener(configLoadedListener) diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigMigrationTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigMigrationTest.kt index 7d4587905..c465ac1bf 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigMigrationTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigMigrationTest.kt @@ -72,7 +72,8 @@ class ConfigMigrationTest : BaseCleanInstallEachTest() { assertOldConfigState(oldConfig) - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .credentials("key", "secret") .configMaxAgeSeconds(0) .build() @@ -105,7 +106,8 @@ class ConfigMigrationTest : BaseCleanInstallEachTest() { assertOldConfigState(oldConfig) - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .credentials("key", "secret") .configMaxAgeSeconds(Integer.MAX_VALUE) .build() @@ -124,30 +126,39 @@ class ConfigMigrationTest : BaseCleanInstallEachTest() { } private fun setOldConfigState(config: JSONObject) { - ConfigManager.getInstance(mContext).getKitConfigPreferences().edit() + ConfigManager + .getInstance(mContext) + .getKitConfigPreferences() + .edit() .remove(ConfigManager.KIT_CONFIG_KEY) - ConfigManager.getPreferences(mContext).edit() - .putString(oldConfigSharedprefsKey, config.toString()).apply() + ConfigManager + .getPreferences(mContext) + .edit() + .putString(oldConfigSharedprefsKey, config.toString()) + .apply() } private fun assertOldConfigState(config: JSONObject) { assertEquals( config.toString(), - ConfigManager.getPreferences(mContext) - .getString(oldConfigSharedprefsKey, JSONArray().toString()) + ConfigManager + .getPreferences(mContext) + .getString(oldConfigSharedprefsKey, JSONArray().toString()), ) } private fun assertNewConfigState(config: JSONObject) { - val configString = ConfigManager.getPreferences(mContext) - .getString(ConfigManager.CONFIG_JSON, JSONArray().toString()) + val configString = + ConfigManager + .getPreferences(mContext) + .getString(ConfigManager.CONFIG_JSON, JSONArray().toString()) assertNull(JSONObject(configString).optJSONArray(ConfigManager.KEY_EMBEDDED_KITS)) assertEquals( config.optString(ConfigManager.KEY_EMBEDDED_KITS, JSONArray().toString()), ConfigManager.getInstance(mContext).kitConfigPreferences.getString( ConfigManager.KIT_CONFIG_KEY, - JSONArray().toString() - ) + JSONArray().toString(), + ), ) } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigRequestTests.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigRequestTests.kt index 84c22bac6..a82c6f7ce 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigRequestTests.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigRequestTests.kt @@ -12,7 +12,6 @@ import kotlin.test.assertFalse import kotlin.test.assertTrue class ConfigRequestTests : BaseCleanInstallEachTest() { - @Test fun testConfigRequestWithDataplanIdAndVersion() { MParticleOptions @@ -94,7 +93,10 @@ class ConfigRequestTests : BaseCleanInstallEachTest() { mServer.waitForVerify(Matcher(mServer.Endpoints().configUrl)) { request -> assertTrue { MPUtility.isEmpty( - MParticle.getInstance()!!.Internal().configManager.latestKitConfiguration + MParticle + .getInstance()!! + .Internal() + .configManager.latestKitConfiguration, ) } latch.countDown() @@ -103,7 +105,12 @@ class ConfigRequestTests : BaseCleanInstallEachTest() { latch.await() assertEquals( simpleConfigWithKits[ConfigManager.KEY_EMBEDDED_KITS].toString(), - MParticle.getInstance()?.Internal()?.configManager?.latestKitConfiguration.toString() + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.latestKitConfiguration + .toString(), ) } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigStalenessCheckTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigStalenessCheckTest.kt index 907ec80ea..238c9d34a 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigStalenessCheckTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigStalenessCheckTest.kt @@ -13,16 +13,23 @@ import kotlin.test.assertTrue class ConfigStalenessCheckTest : BaseCleanInstallEachTest() { val configManager: ConfigManager - get() = MParticle.getInstance()?.Internal()?.configManager.assertNotNull() + get() = + MParticle + .getInstance() + ?.Internal() + ?.configManager + .assertNotNull() @Test fun testNeverStale() { val config1 = randomJson(4) val config2 = randomJson(4) var latch = MPLatch(1) - val options = MParticleOptions.builder(mContext) - .addCredentials() - .build() + val options = + MParticleOptions + .builder(mContext) + .addCredentials() + .build() mServer.setupConfigResponse(config1.toString()) @@ -51,7 +58,14 @@ class ConfigStalenessCheckTest : BaseCleanInstallEachTest() { configManager.onNewConfig { latch.countDown() } latch.await() - assertEquals(config2.toString(), MParticle.getInstance()?.Internal()?.configManager?.config) + assertEquals( + config2.toString(), + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.config, + ) } @Test @@ -59,10 +73,12 @@ class ConfigStalenessCheckTest : BaseCleanInstallEachTest() { val config1 = randomJson(4) val config2 = randomJson(4) var latch = MPLatch(1) - val options = MParticleOptions.builder(mContext) - .addCredentials() - .configMaxAgeSeconds(1) - .build() + val options = + MParticleOptions + .builder(mContext) + .addCredentials() + .configMaxAgeSeconds(1) + .build() mServer.setupConfigResponse(config1.toString()) @@ -71,7 +87,14 @@ class ConfigStalenessCheckTest : BaseCleanInstallEachTest() { configManager.onNewConfig { latch.countDown() } latch.await() - assertEquals(config1.toString(), MParticle.getInstance()?.Internal()?.configManager?.config) + assertEquals( + config1.toString(), + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.config, + ) MParticle.setInstance(null) @@ -92,7 +115,14 @@ class ConfigStalenessCheckTest : BaseCleanInstallEachTest() { latch.await() // after config has been fetched, we should see config2 - assertEquals(config2.toString(), MParticle.getInstance()?.Internal()?.configManager?.config) + assertEquals( + config2.toString(), + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.config, + ) } @Test @@ -100,10 +130,12 @@ class ConfigStalenessCheckTest : BaseCleanInstallEachTest() { val config1 = randomJson(4) val config2 = randomJson(4) var latch = MPLatch(1) - val options = MParticleOptions.builder(mContext) - .addCredentials() - .configMaxAgeSeconds(100) - .build() + val options = + MParticleOptions + .builder(mContext) + .addCredentials() + .configMaxAgeSeconds(100) + .build() mServer.setupConfigResponse(config1.toString()) @@ -132,7 +164,14 @@ class ConfigStalenessCheckTest : BaseCleanInstallEachTest() { configManager.onNewConfig { latch.countDown() } latch.await() - assertEquals(config2.toString(), MParticle.getInstance()?.Internal()?.configManager?.config) + assertEquals( + config2.toString(), + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.config, + ) } @Test @@ -140,10 +179,12 @@ class ConfigStalenessCheckTest : BaseCleanInstallEachTest() { val config1 = randomJson(4) val config2 = randomJson(4) var latch = MPLatch(1) - val options = MParticleOptions.builder(mContext) - .addCredentials() - .configMaxAgeSeconds(0) - .build() + val options = + MParticleOptions + .builder(mContext) + .addCredentials() + .configMaxAgeSeconds(0) + .build() mServer.setupConfigResponse(config1.toString()) @@ -152,7 +193,14 @@ class ConfigStalenessCheckTest : BaseCleanInstallEachTest() { configManager.onNewConfig { latch.countDown() } latch.await() - assertEquals(config1.toString(), MParticle.getInstance()?.Internal()?.configManager?.config) + assertEquals( + config1.toString(), + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.config, + ) MParticle.setInstance(null) diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/DeviceAttributesTests.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/DeviceAttributesTests.kt index 34b400d26..0e0e6d275 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/DeviceAttributesTests.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/DeviceAttributesTests.kt @@ -18,19 +18,23 @@ class DeviceAttributesTests : BaseCleanInstallEachTest() { Assert.assertFalse(attributes.has(Constants.MessageKey.DEVICE_ANID)) Assert.assertFalse(attributes.has(Constants.MessageKey.DEVICE_OPEN_UDID)) Assert.assertFalse(attributes.has(Constants.MessageKey.DEVICE_ID)) - var options = MParticleOptions.builder(context) - .androidIdEnabled(false) - .credentials("key", "secret") - .build() + var options = + MParticleOptions + .builder(context) + .androidIdEnabled(false) + .credentials("key", "secret") + .build() MParticle.start(options) var newAttributes = JSONObject() DeviceAttributes.addAndroidId(newAttributes, context) Assert.assertTrue(newAttributes.length() == 0) MParticle.setInstance(null) - options = MParticleOptions.builder(context) - .androidIdEnabled(true) - .credentials("key", "secret") - .build() + options = + MParticleOptions + .builder(context) + .androidIdEnabled(true) + .credentials("key", "secret") + .build() MParticle.start(options) newAttributes = JSONObject() val androidId = MPUtility.getAndroidID(context) @@ -38,7 +42,7 @@ class DeviceAttributesTests : BaseCleanInstallEachTest() { Assert.assertTrue(newAttributes.length() == 3) Assert.assertEquals(newAttributes.getString(Constants.MessageKey.DEVICE_ANID), androidId) Assert.assertTrue( - newAttributes.getString(Constants.MessageKey.DEVICE_OPEN_UDID).isNotEmpty() + newAttributes.getString(Constants.MessageKey.DEVICE_OPEN_UDID).isNotEmpty(), ) Assert.assertEquals(newAttributes.getString(Constants.MessageKey.DEVICE_ID), androidId) } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/KitFrameworkWrapperTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/KitFrameworkWrapperTest.kt index 5981389ff..0f34933a6 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/KitFrameworkWrapperTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/KitFrameworkWrapperTest.kt @@ -15,7 +15,8 @@ import java.util.concurrent.CountDownLatch class KitFrameworkWrapperTest : BaseCleanStartedEachTest() { private fun setKitManager(kitManager: KitFrameworkWrapper) { AccessUtils.setKitManager(kitManager) - com.mparticle.identity.AccessUtils.setKitManager(kitManager) + com.mparticle.identity.AccessUtils + .setKitManager(kitManager) } @Test @@ -24,16 +25,21 @@ class KitFrameworkWrapperTest : BaseCleanStartedEachTest() { val mpid = ran.nextLong() val latch: CountDownLatch = MPLatch(1) val called = MutableBoolean(false) - setKitManager(object : StubKitManager(mContext) { - override fun onIdentifyCompleted(user: MParticleUser, request: IdentityApiRequest) { - if (user.id == mStartingMpid) { - return + setKitManager( + object : StubKitManager(mContext) { + override fun onIdentifyCompleted( + user: MParticleUser, + request: IdentityApiRequest, + ) { + if (user.id == mStartingMpid) { + return + } + Assert.assertEquals(mpid, user.id) + called.value = true + latch.countDown() } - Assert.assertEquals(mpid, user.id) - called.value = true - latch.countDown() - } - }) + }, + ) mServer.setupHappyIdentify(mpid) MParticle.getInstance()?.Identity()?.identify(IdentityApiRequest.withEmptyUser().build()) latch.await() @@ -46,16 +52,21 @@ class KitFrameworkWrapperTest : BaseCleanStartedEachTest() { val mpid = ran.nextLong() val latch: CountDownLatch = MPLatch(1) val called = MutableBoolean(false) - setKitManager(object : StubKitManager(mContext) { - override fun onLoginCompleted(user: MParticleUser, request: IdentityApiRequest) { - if (user.id == mStartingMpid) { - return + setKitManager( + object : StubKitManager(mContext) { + override fun onLoginCompleted( + user: MParticleUser, + request: IdentityApiRequest, + ) { + if (user.id == mStartingMpid) { + return + } + Assert.assertEquals(mpid, user.id) + called.value = true + latch.countDown() } - Assert.assertEquals(mpid, user.id) - called.value = true - latch.countDown() - } - }) + }, + ) mServer.setupHappyLogin(mpid) MParticle.getInstance()?.Identity()?.login(IdentityApiRequest.withEmptyUser().build()) latch.await() @@ -68,16 +79,21 @@ class KitFrameworkWrapperTest : BaseCleanStartedEachTest() { val mpid = ran.nextLong() val latch: CountDownLatch = MPLatch(1) val called = MutableBoolean(false) - setKitManager(object : StubKitManager(mContext) { - override fun onLogoutCompleted(user: MParticleUser, request: IdentityApiRequest) { - if (user.id == mStartingMpid) { - return + setKitManager( + object : StubKitManager(mContext) { + override fun onLogoutCompleted( + user: MParticleUser, + request: IdentityApiRequest, + ) { + if (user.id == mStartingMpid) { + return + } + Assert.assertEquals(mpid, user.id) + called.value = true + latch.countDown() } - Assert.assertEquals(mpid, user.id) - called.value = true - latch.countDown() - } - }) + }, + ) mServer.setupHappyLogout(mpid) MParticle.getInstance()?.Identity()?.logout(IdentityApiRequest.withEmptyUser().build()) latch.await() @@ -89,17 +105,25 @@ class KitFrameworkWrapperTest : BaseCleanStartedEachTest() { fun testModify() { val latch: CountDownLatch = MPLatch(1) val called = MutableBoolean(false) - setKitManager(object : StubKitManager(mContext) { - override fun onModifyCompleted(user: MParticleUser, request: IdentityApiRequest) { - Assert.assertEquals(mStartingMpid.toLong(), user.id) - called.value = true - latch.countDown() - } - }) - MParticle.getInstance() - ?.Identity()?.modify( - IdentityApiRequest.withUser(MParticle.getInstance()?.Identity()?.currentUser) - .build() + setKitManager( + object : StubKitManager(mContext) { + override fun onModifyCompleted( + user: MParticleUser, + request: IdentityApiRequest, + ) { + Assert.assertEquals(mStartingMpid.toLong(), user.id) + called.value = true + latch.countDown() + } + }, + ) + MParticle + .getInstance() + ?.Identity() + ?.modify( + IdentityApiRequest + .withUser(MParticle.getInstance()?.Identity()?.currentUser) + .build(), ) latch.await() Assert.assertTrue(called.value) @@ -110,43 +134,65 @@ class KitFrameworkWrapperTest : BaseCleanStartedEachTest() { fun testModifyUserChanged() { val latch: CountDownLatch = MPLatch(1) val called = MutableBoolean(false) - setKitManager(object : StubKitManager(mContext) { - override fun onModifyCompleted(user: MParticleUser, request: IdentityApiRequest) { - Assert.assertEquals(mStartingMpid.toLong(), user.id) - called.value = true - latch.countDown() - } - }) + setKitManager( + object : StubKitManager(mContext) { + override fun onModifyCompleted( + user: MParticleUser, + request: IdentityApiRequest, + ) { + Assert.assertEquals(mStartingMpid.toLong(), user.id) + called.value = true + latch.countDown() + } + }, + ) MParticle.getInstance()?.Identity()?.modify(IdentityApiRequest.withEmptyUser().build()) - MParticle.getInstance()?.Internal()?.configManager?.setMpid(0, ran.nextBoolean()) + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.setMpid(0, ran.nextBoolean()) latch.await() val latch2: CountDownLatch = MPLatch(1) val mpid2 = ran.nextLong() - MParticle.getInstance()?.Internal()?.configManager?.setMpid(mpid2, ran.nextBoolean()) + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.setMpid(mpid2, ran.nextBoolean()) Assert.assertTrue(called.value) called.value = false - setKitManager(object : StubKitManager(mContext) { - override fun onModifyCompleted(user: MParticleUser, request: IdentityApiRequest) { - Assert.assertEquals(mpid2, user.id) - called.value = true - latch2.countDown() - } - }) - MParticle.getInstance() - ?.Identity()?.modify( - IdentityApiRequest.withUser(MParticle.getInstance()?.Identity()?.currentUser) - .build() + setKitManager( + object : StubKitManager(mContext) { + override fun onModifyCompleted( + user: MParticleUser, + request: IdentityApiRequest, + ) { + Assert.assertEquals(mpid2, user.id) + called.value = true + latch2.countDown() + } + }, + ) + MParticle + .getInstance() + ?.Identity() + ?.modify( + IdentityApiRequest + .withUser(MParticle.getInstance()?.Identity()?.currentUser) + .build(), ) MParticle.getInstance()?.Internal()?.configManager?.setMpid( ran.nextLong(), - ran.nextBoolean() + ran.nextBoolean(), ) latch2.await() Assert.assertTrue(called.value) } - internal open class StubKitManager(context: Context?) : - KitFrameworkWrapper(context, null, null, null, true, null) { + internal open class StubKitManager( + context: Context?, + ) : KitFrameworkWrapper(context, null, null, null, true, null) { init { setKitManager(null) } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/MessageManagerTests.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/MessageManagerTests.kt index 00413ab7e..5564440d0 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/MessageManagerTests.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/MessageManagerTests.kt @@ -71,21 +71,23 @@ class MessageManagerTests : BaseCleanInstallEachTest() { session.start(mContext) messageManager.startSession(session) AccessUtils.awaitMessageHandler() - var message = messageManager.mParticleDBManager.getSessionForSessionEndMessage( - session.mSessionID, - null, - session.mpids - ) + var message = + messageManager.mParticleDBManager.getSessionForSessionEndMessage( + session.mSessionID, + null, + session.mpids, + ) junit.framework.Assert.assertNotNull(message) messageManager.mParticleDBManager.updateSessionStatus( session.mSessionID, - SessionTable.SessionTableColumns.STATUS - ) - message = messageManager.mParticleDBManager.getSessionForSessionEndMessage( - session.mSessionID, - null, - session.mpids + SessionTable.SessionTableColumns.STATUS, ) + message = + messageManager.mParticleDBManager.getSessionForSessionEndMessage( + session.mSessionID, + null, + session.mpids, + ) junit.framework.Assert.assertNull(message) } @@ -143,17 +145,23 @@ class MessageManagerTests : BaseCleanInstallEachTest() { * simulates the install state to settings pre 5.0.9 || pre 4.17.1 * @param firstRun */ - private fun setFirstRunLegacy(firstRun: Boolean, key: String) { + private fun setFirstRunLegacy( + firstRun: Boolean, + key: String, + ) { val sharedPreferences = mContext.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE) - sharedPreferences.edit() + sharedPreferences + .edit() .remove(Constants.PrefKeys.FIRSTRUN_AST + key) .remove(Constants.PrefKeys.FIRSTRUN_MESSAGE + key) .apply() if (firstRun) { sharedPreferences.edit().remove(Constants.PrefKeys.FIRSTRUN_OBSELETE + key).apply() } else { - sharedPreferences.edit().putBoolean(Constants.PrefKeys.FIRSTRUN_OBSELETE + key, false) + sharedPreferences + .edit() + .putBoolean(Constants.PrefKeys.FIRSTRUN_OBSELETE + key, false) .apply() } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/UpdateAdIdIdentityTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/UpdateAdIdIdentityTest.kt index 2f97af378..087d4a143 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/UpdateAdIdIdentityTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/UpdateAdIdIdentityTest.kt @@ -11,17 +11,17 @@ import kotlin.test.assertEquals import kotlin.test.assertNull class UpdateAdIdIdentityTest : BaseCleanInstallEachTest() { - @Test fun testAdIdModifyNoUser() { // setup mock server so initial identity request will not set mpid mServer.setupHappyIdentify(0) val latch = MPLatch(1) MParticle.start( - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .credentials("key", "secret") .identifyTask(BaseIdentityTask().addSuccessListener { latch.countDown() }) - .build() + .build(), ) // execute CheckAdIdRunnable without a current user @@ -35,21 +35,26 @@ class UpdateAdIdIdentityTest : BaseCleanInstallEachTest() { // force a modify request to ensure that the modify request from the CheckAdIdRunnable is completed val latch2 = MPLatch(1) - MParticle.getInstance()!!.Identity() + MParticle + .getInstance()!! + .Identity() .modify(IdentityApiRequest.withEmptyUser().customerId("someId").build()) .addSuccessListener { latch2.countDown() } latch2.await() // check that modify request from CheckAdIdRunnable executed when current user was set - mServer.Requests().modify.count { request -> - request.asIdentityRequest().body.identity_changes.let { - it.size == 1 && - it[0].let { identityChange -> - identityChange["new_value"] == "someId" - } + mServer + .Requests() + .modify + .count { request -> + request.asIdentityRequest().body.identity_changes.let { + it.size == 1 && + it[0].let { identityChange -> + identityChange["new_value"] == "someId" + } + } + }.let { + assertEquals(1, it) } - }.let { - assertEquals(1, it) - } } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/TestSQLiteOpenHelper.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/TestSQLiteOpenHelper.kt index b3b06bd1a..3ea5dd384 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/TestSQLiteOpenHelper.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/TestSQLiteOpenHelper.kt @@ -7,41 +7,51 @@ import com.mparticle.internal.database.services.SQLiteOpenHelperWrapper import com.mparticle.testutils.MPLatch import java.util.concurrent.CountDownLatch -class TestSQLiteOpenHelper @JvmOverloads constructor( - var helper: SQLiteOpenHelperWrapper, - databaseName: String?, - version: Int = 1 -) : SQLiteOpenHelper( - InstrumentationRegistry.getInstrumentation().context, - databaseName, - null, - version -) { - @JvmField - var onCreateLatch: CountDownLatch = MPLatch(1) - - @JvmField - var onUpgradeLatch: CountDownLatch = MPLatch(1) - - @JvmField - var onDowngradeLatch: CountDownLatch = MPLatch(1) - - init { - writableDatabase +class TestSQLiteOpenHelper + @JvmOverloads + constructor( + var helper: SQLiteOpenHelperWrapper, + databaseName: String?, + version: Int = 1, + ) : SQLiteOpenHelper( + InstrumentationRegistry.getInstrumentation().context, + databaseName, + null, + version, + ) { + @JvmField + var onCreateLatch: CountDownLatch = MPLatch(1) + + @JvmField + var onUpgradeLatch: CountDownLatch = MPLatch(1) + + @JvmField + var onDowngradeLatch: CountDownLatch = MPLatch(1) + + init { + writableDatabase + } + + override fun onCreate(db: SQLiteDatabase) { + helper.onCreate(db) + onCreateLatch.countDown() + } + + override fun onUpgrade( + db: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) { + helper.onUpgrade(db, oldVersion, newVersion) + onUpgradeLatch.countDown() + } + + override fun onDowngrade( + db: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) { + helper.onDowngrade(db, oldVersion, newVersion) + onDowngradeLatch.countDown() + } } - - override fun onCreate(db: SQLiteDatabase) { - helper.onCreate(db) - onCreateLatch.countDown() - } - - override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { - helper.onUpgrade(db, oldVersion, newVersion) - onUpgradeLatch.countDown() - } - - override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { - helper.onDowngrade(db, oldVersion, newVersion) - onDowngradeLatch.countDown() - } -} diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeMessageTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeMessageTableTest.kt index 63b1b29ec..bd7767494 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeMessageTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeMessageTableTest.kt @@ -22,19 +22,23 @@ class UpgradeMessageTableTest : BaseTableTest() { helper.onCreate(database) } - override fun onUpgrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) { + override fun onUpgrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) { helper.onUpgrade(database, oldVersion, newVersion) } override fun onDowngrade( database: SQLiteDatabase, oldVersion: Int, - newVersion: Int + newVersion: Int, ) { helper.onDowngrade(database, oldVersion, newVersion) } }, - 9 + 9, ) deleteTestingDatabase() @@ -44,16 +48,16 @@ class UpgradeMessageTableTest : BaseTableTest() { companion object { const val CREATE_MESSAGES_DDL = - "CREATE TABLE IF NOT EXISTS " + MessageTable.MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID + - " INTEGER PRIMARY KEY AUTOINCREMENT, " + - MessageTable.MessageTableColumns.SESSION_ID + " STRING NOT NULL, " + - MessageTable.MessageTableColumns.API_KEY + " STRING NOT NULL, " + - MessageTable.MessageTableColumns.MESSAGE + " TEXT, " + - MessageTable.MessageTableColumns.STATUS + " INTEGER, " + - MessageTable.MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " + - MessageTable.MessageTableColumns.MESSAGE_TYPE + " TEXT, " + - MessageTable.MessageTableColumns.CF_UUID + " TEXT, " + - MessageTable.MessageTableColumns.MP_ID + " INTEGER" + + "CREATE TABLE IF NOT EXISTS " + MessageTable.MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + MessageTable.MessageTableColumns.SESSION_ID + " STRING NOT NULL, " + MessageTable.MessageTableColumns.API_KEY + " STRING NOT NULL, " + MessageTable.MessageTableColumns.MESSAGE + " TEXT, " + MessageTable.MessageTableColumns.STATUS + " INTEGER, " + MessageTable.MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " + MessageTable.MessageTableColumns.MESSAGE_TYPE + " TEXT, " + MessageTable.MessageTableColumns.CF_UUID + " TEXT, " + MessageTable.MessageTableColumns.MP_ID + " INTEGER" ");" } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeVersionTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeVersionTest.kt index 4a6d64850..8b80cb5e7 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeVersionTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeVersionTest.kt @@ -54,19 +54,23 @@ class UpgradeVersionTest : BaseTableTest() { helper.onCreate(database) } - override fun onUpgrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) { + override fun onUpgrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) { helper.onUpgrade(database, oldVersion, newVersion) } override fun onDowngrade( database: SQLiteDatabase, oldVersion: Int, - newVersion: Int + newVersion: Int, ) { helper.onDowngrade(database, oldVersion, newVersion) } }, - 7 + 7, ) deleteTestingDatabase() @@ -88,10 +92,14 @@ class UpgradeVersionTest : BaseTableTest() { ReportingService.insertReportingMessage( db, TestingUtils.getInstance().getRandomReportingMessage("123"), - 1L + 1L, ) SessionService.insertSession(db, message, "key", "", "", 1L) - UploadService.insertAliasRequest(db, JSONObject().put("key", "value"), UploadSettings("apiKey", "secret", NetworkOptions.builder().build(), "", "")) + UploadService.insertAliasRequest( + db, + JSONObject().put("key", "value"), + UploadSettings("apiKey", "secret", NetworkOptions.builder().build(), "", ""), + ) UserAttributesService.insertAttribute(db, "key", "value", 1L, false, 1L) // test to make sure there are values in the database @@ -103,7 +111,7 @@ class UpgradeVersionTest : BaseTableTest() { Assert.assertEquals( tableName, 1, - databaseJSON.getJSONArray(tableName).length().toLong() + databaseJSON.getJSONArray(tableName).length().toLong(), ) } @@ -120,7 +128,7 @@ class UpgradeVersionTest : BaseTableTest() { Assert.assertEquals( tableName, 1, - databaseJSON.getJSONArray(tableName).length().toLong() + databaseJSON.getJSONArray(tableName).length().toLong(), ) } @@ -139,7 +147,7 @@ class UpgradeVersionTest : BaseTableTest() { Assert.assertEquals( tableName, 0, - databaseJSON.getJSONArray(tableName).length().toLong() + databaseJSON.getJSONArray(tableName).length().toLong(), ) } } @@ -147,23 +155,32 @@ class UpgradeVersionTest : BaseTableTest() { @Test @Throws(InterruptedException::class, JSONException::class) fun testAddMpidColumns() { - val sqLiteOpenHelperWrapper: SQLiteOpenHelperWrapper = object : SQLiteOpenHelperWrapper { - override fun onCreate(db: SQLiteDatabase) { - db.execSQL(SessionTableTest.old_CREATE_SESSION_DDL) - db.execSQL(MessageTableTest.old_no_mpid_CREATE_MESSAGES_DDL) - db.execSQL(BreadcrumbTableTest.old_CREATE_BREADCRUMBS_DDL) - db.execSQL(ReportingTableTest.old_CREATE_REPORTING_DDL) - db.execSQL(UserAttributeTableTest.old_CREATE_USER_ATTRIBUTES_DDL) - } + val sqLiteOpenHelperWrapper: SQLiteOpenHelperWrapper = + object : SQLiteOpenHelperWrapper { + override fun onCreate(db: SQLiteDatabase) { + db.execSQL(SessionTableTest.old_CREATE_SESSION_DDL) + db.execSQL(MessageTableTest.old_no_mpid_CREATE_MESSAGES_DDL) + db.execSQL(BreadcrumbTableTest.old_CREATE_BREADCRUMBS_DDL) + db.execSQL(ReportingTableTest.old_CREATE_REPORTING_DDL) + db.execSQL(UserAttributeTableTest.old_CREATE_USER_ATTRIBUTES_DDL) + } - override fun onUpgrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) { - helper.onUpgrade(database, oldVersion, newVersion) - } + override fun onUpgrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) { + helper.onUpgrade(database, oldVersion, newVersion) + } - override fun onDowngrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) { - helper.onDowngrade(database, oldVersion, newVersion) + override fun onDowngrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) { + helper.onDowngrade(database, oldVersion, newVersion) + } } - } var sqLiteOpenHelper = TestSQLiteOpenHelper(sqLiteOpenHelperWrapper, DB_NAME, 6) sqLiteOpenHelper.onCreateLatch.await() var databaseContents = getDatabaseSchema(sqLiteOpenHelper.writableDatabase) @@ -183,7 +200,7 @@ class UpgradeVersionTest : BaseTableTest() { Assert.assertTrue(databaseContents.getJSONObject(key).has(MpIdDependentTable.MP_ID)) } else { Assert.assertFalse( - databaseContents.getJSONObject(key).has(MpIdDependentTable.MP_ID) + databaseContents.getJSONObject(key).has(MpIdDependentTable.MP_ID), ) } } @@ -191,15 +208,15 @@ class UpgradeVersionTest : BaseTableTest() { companion object { const val CREATE_GCM_MSG_DDL = - "CREATE TABLE IF NOT EXISTS " + FcmMessageTableColumns.TABLE_NAME + " (" + FcmMessageTableColumns.CONTENT_ID + - " INTEGER PRIMARY KEY, " + - FcmMessageTableColumns.PAYLOAD + " TEXT NOT NULL, " + - FcmMessageTableColumns.APPSTATE + " TEXT NOT NULL, " + - FcmMessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " + - FcmMessageTableColumns.EXPIRATION + " INTEGER NOT NULL, " + - FcmMessageTableColumns.BEHAVIOR + " INTEGER NOT NULL," + - FcmMessageTableColumns.CAMPAIGN_ID + " TEXT NOT NULL, " + - FcmMessageTableColumns.DISPLAYED_AT + " INTEGER NOT NULL " + + "CREATE TABLE IF NOT EXISTS " + FcmMessageTableColumns.TABLE_NAME + " (" + FcmMessageTableColumns.CONTENT_ID + " INTEGER PRIMARY KEY, " + FcmMessageTableColumns.PAYLOAD + " TEXT NOT NULL, " + FcmMessageTableColumns.APPSTATE + " TEXT NOT NULL, " + FcmMessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " + FcmMessageTableColumns.EXPIRATION + " INTEGER NOT NULL, " + FcmMessageTableColumns.BEHAVIOR + " INTEGER NOT NULL," + FcmMessageTableColumns.CAMPAIGN_ID + " TEXT NOT NULL, " + FcmMessageTableColumns.DISPLAYED_AT + " INTEGER NOT NULL " ");" } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/BaseMPServiceTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/BaseMPServiceTest.kt index 3e42fb943..1f4a9d72b 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/BaseMPServiceTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/BaseMPServiceTest.kt @@ -16,10 +16,11 @@ abstract class BaseMPServiceTest : BaseCleanInstallEachTest() { @Before @Throws(Exception::class) fun beforeBaseMPService() { - val openHelper: SQLiteOpenHelper = TestSQLiteOpenHelper( - MParticleDatabaseHelper(mContext), - MParticleDatabaseHelper.getDbName() - ) + val openHelper: SQLiteOpenHelper = + TestSQLiteOpenHelper( + MParticleDatabaseHelper(mContext), + MParticleDatabaseHelper.getDbName(), + ) database = MPDatabaseImpl(openHelper.writableDatabase) } @@ -28,26 +29,28 @@ abstract class BaseMPServiceTest : BaseCleanInstallEachTest() { get() = getMpMessage(UUID.randomUUID().toString()) @Throws(JSONException::class) - fun getMpMessage(sessionId: String?): BaseMPMessage { - return getMpMessage(sessionId, mRandomUtils.randomLong(Long.MIN_VALUE, Long.MAX_VALUE)) - } + fun getMpMessage(sessionId: String?): BaseMPMessage = getMpMessage(sessionId, mRandomUtils.randomLong(Long.MIN_VALUE, Long.MAX_VALUE)) @Throws(JSONException::class) - fun getMpMessage(sessionId: String?, mpid: Long): BaseMPMessage { + fun getMpMessage( + sessionId: String?, + mpid: Long, + ): BaseMPMessage { val session = InternalSession() session.mSessionID = sessionId - return BaseMPMessage.Builder( - mRandomUtils.getAlphaNumericString( - mRandomUtils.randomInt( - 20, - 48 - ) + return BaseMPMessage + .Builder( + mRandomUtils.getAlphaNumericString( + mRandomUtils.randomInt( + 20, + 48, + ), + ), + ).build( + session, + Location(mRandomUtils.getAlphaNumericString(mRandomUtils.randomInt(1, 55))), + mpid, ) - ).build( - session, - Location(mRandomUtils.getAlphaNumericString(mRandomUtils.randomInt(1, 55))), - mpid - ) } companion object { diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/BreadcrumbServiceTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/BreadcrumbServiceTest.kt index b8a2c5132..41333022e 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/BreadcrumbServiceTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/BreadcrumbServiceTest.kt @@ -69,26 +69,26 @@ class BreadcrumbServiceTest : BaseMPServiceTest() { } Assert.assertEquals( BreadcrumbService.getBreadcrumbs(database, mContext, 1L).length().toLong(), - expectedCount.toLong() + expectedCount.toLong(), ) Assert.assertEquals( BreadcrumbService.getBreadcrumbs(database, mContext, 2L).length().toLong(), - 0 + 0, ) for (i in 0 until expectedCount - 1) { BreadcrumbService.insertBreadcrumb(database, mContext, message, "apiKey", 2L) } Assert.assertEquals( BreadcrumbService.getBreadcrumbs(database, mContext, 1L).length().toLong(), - expectedCount.toLong() + expectedCount.toLong(), ) Assert.assertEquals( BreadcrumbService.getBreadcrumbs(database, mContext, 2L).length().toLong(), - (expectedCount - 1).toLong() + (expectedCount - 1).toLong(), ) Assert.assertEquals( BreadcrumbService.getBreadcrumbs(database, mContext, 3L).length().toLong(), - 0 + 0, ) } @@ -103,8 +103,8 @@ class BreadcrumbServiceTest : BaseMPServiceTest() { mContext, message, "apiKey", - 10L - ) + 10L, + ), ) } @@ -113,7 +113,7 @@ class BreadcrumbServiceTest : BaseMPServiceTest() { Assert.assertEquals(deleted.size, 10) Assert.assertEquals( BreadcrumbService.getBreadcrumbs(database, mContext, 10L).length(), - breadCrumbLimit + breadCrumbLimit, ) } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/MParticleDBManagerTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/MParticleDBManagerTest.kt index 9b180d231..c92e293db 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/MParticleDBManagerTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/MParticleDBManagerTest.kt @@ -95,33 +95,32 @@ class MParticleDBManagerTest : BaseCleanInstallEachTest() { fun testGetUserAttributesAsync() { startMParticle() val dbAccessThread = AndroidUtils.Mutable(null) - val manager: MParticleDBManager = object : MParticleDBManager() { - override fun getUserAttributeSingles(mpId: Long): Map? { - dbAccessThread.value = Thread.currentThread() - return null - } + val manager: MParticleDBManager = + object : MParticleDBManager() { + override fun getUserAttributeSingles(mpId: Long): Map? { + dbAccessThread.value = Thread.currentThread() + return null + } - override fun getUserAttributeLists(mpId: Long): TreeMap>? { - return null + override fun getUserAttributeLists(mpId: Long): TreeMap>? = null } - } val latch = AndroidUtils.Mutable(MPLatch(1)) val callbackThread = AndroidUtils.Mutable(null) // when not on the main thread, it should callback on the current thread, and access the DB on the same thread Assert.assertNotEquals("main", Thread.currentThread().name) - val listener: TypedUserAttributeListener = object : TypedUserAttributeListener { - - override fun onUserAttributesReceived( - userAttributes: Map, - userAttributeLists: Map?>, - mpid: Long - ) { - callbackThread.value = Thread.currentThread() - latch.value.countDown() + val listener: TypedUserAttributeListener = + object : TypedUserAttributeListener { + override fun onUserAttributesReceived( + userAttributes: Map, + userAttributeLists: Map?>, + mpid: Long, + ) { + callbackThread.value = Thread.currentThread() + latch.value.countDown() + } } - } manager.getUserAttributes(UserAttributeListenerWrapper(listener), 1) Assert.assertNotNull(callbackThread.value) Assert.assertEquals(Thread.currentThread().name, callbackThread.value?.name) @@ -131,20 +130,21 @@ class MParticleDBManagerTest : BaseCleanInstallEachTest() { latch.value = MPLatch(1) // when run from the main thread, it should be called back on the main thread, but NOT access the DB on the same thread - val listener1: TypedUserAttributeListener = object : TypedUserAttributeListener { - override fun onUserAttributesReceived( - userAttributes: Map, - userAttributeLists: Map?>, - mpid: Long - ) { - callbackThread.value = Thread.currentThread() - latch.value.countDown() + val listener1: TypedUserAttributeListener = + object : TypedUserAttributeListener { + override fun onUserAttributesReceived( + userAttributes: Map, + userAttributeLists: Map?>, + mpid: Long, + ) { + callbackThread.value = Thread.currentThread() + latch.value.countDown() + } } - } Handler(Looper.getMainLooper()).post { manager.getUserAttributes( UserAttributeListenerWrapper(listener), - 1 + 1, ) } latch.value.await() diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/MessageServiceTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/MessageServiceTest.kt index 0283795ef..9b1db3a01 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/MessageServiceTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/MessageServiceTest.kt @@ -35,24 +35,28 @@ class MessageServiceTest : BaseMPServiceTest() { mpMessage, mpid1, null, - null + null, ) } Assert.assertEquals( - MessageService.getMessagesForUpload( - database, - true, - mpid1 - ).size.toLong(), - 20 + MessageService + .getMessagesForUpload( + database, + true, + mpid1, + ).size + .toLong(), + 20, ) Assert.assertEquals( - MessageService.getMessagesForUpload( - database, - true, - Constants.TEMPORARY_MPID - ).size.toLong(), - 0 + MessageService + .getMessagesForUpload( + database, + true, + Constants.TEMPORARY_MPID, + ).size + .toLong(), + 0, ) Assert.assertEquals(MessageService.getMessagesForUpload(database).size.toLong(), 20) for (i in 0..29) { @@ -62,32 +66,38 @@ class MessageServiceTest : BaseMPServiceTest() { mpMessage, Constants.TEMPORARY_MPID, null, - null + null, ) } Assert.assertEquals( - MessageService.getMessagesForUpload( - database, - true, - mpid1 - ).size.toLong(), - 20 + MessageService + .getMessagesForUpload( + database, + true, + mpid1, + ).size + .toLong(), + 20, ) Assert.assertEquals( - MessageService.getMessagesForUpload( - database, - true, - mpid2 - ).size.toLong(), - 0 + MessageService + .getMessagesForUpload( + database, + true, + mpid2, + ).size + .toLong(), + 0, ) Assert.assertEquals( - MessageService.getMessagesForUpload( - database, - true, - Constants.TEMPORARY_MPID - ).size.toLong(), - 30 + MessageService + .getMessagesForUpload( + database, + true, + Constants.TEMPORARY_MPID, + ).size + .toLong(), + 30, ) Assert.assertEquals(MessageService.getMessagesForUpload(database).size.toLong(), 20) for (i in 0..34) { @@ -97,61 +107,73 @@ class MessageServiceTest : BaseMPServiceTest() { mpMessage, mpid2, null, - null + null, ) } Assert.assertEquals( - MessageService.getMessagesForUpload( - database, - true, - mpid1 - ).size.toLong(), - 20 + MessageService + .getMessagesForUpload( + database, + true, + mpid1, + ).size + .toLong(), + 20, ) Assert.assertEquals( - MessageService.getMessagesForUpload( - database, - true, - mpid2 - ).size.toLong(), - 35 + MessageService + .getMessagesForUpload( + database, + true, + mpid2, + ).size + .toLong(), + 35, ) Assert.assertEquals( - MessageService.getMessagesForUpload( - database, - true, - Constants.TEMPORARY_MPID - ).size.toLong(), - 30 + MessageService + .getMessagesForUpload( + database, + true, + Constants.TEMPORARY_MPID, + ).size + .toLong(), + 30, ) Assert.assertEquals(MessageService.getMessagesForUpload(database).size.toLong(), 55) Assert.assertEquals( MessageService.markMessagesAsUploaded(database, Int.MAX_VALUE).toLong(), - 55 + 55, ) Assert.assertEquals( - MessageService.getMessagesForUpload( - database, - true, - mpid1 - ).size.toLong(), - 0 + MessageService + .getMessagesForUpload( + database, + true, + mpid1, + ).size + .toLong(), + 0, ) Assert.assertEquals( - MessageService.getMessagesForUpload( - database, - true, - mpid2 - ).size.toLong(), - 0 + MessageService + .getMessagesForUpload( + database, + true, + mpid2, + ).size + .toLong(), + 0, ) Assert.assertEquals( - MessageService.getMessagesForUpload( - database, - true, - Constants.TEMPORARY_MPID - ).size.toLong(), - 30 + MessageService + .getMessagesForUpload( + database, + true, + Constants.TEMPORARY_MPID, + ).size + .toLong(), + 30, ) Assert.assertEquals(MessageService.getMessagesForUpload(database).size.toLong(), 0) } @@ -168,7 +190,7 @@ class MessageServiceTest : BaseMPServiceTest() { getMpMessage(currentSession), mpid1, null, - null + null, ) } for (i in 0..29) { @@ -178,7 +200,7 @@ class MessageServiceTest : BaseMPServiceTest() { getMpMessage(currentSession), Constants.TEMPORARY_MPID, null, - null + null, ) } for (i in 0..34) { @@ -188,55 +210,65 @@ class MessageServiceTest : BaseMPServiceTest() { getMpMessage(currentSession), mpid2, null, - null + null, ) } Assert.assertEquals( MessageService.markMessagesAsUploaded(database, Int.MAX_VALUE).toLong(), - 55 + 55, ) Assert.assertEquals( - MessageService.getSessionHistory( - database, - previousSession - ).size.toLong(), - 55 + MessageService + .getSessionHistory( + database, + previousSession, + ).size + .toLong(), + 55, ) Assert.assertEquals( - MessageService.getSessionHistory( - database, - previousSession, - true, - mpid1 - ).size.toLong(), - 20 + MessageService + .getSessionHistory( + database, + previousSession, + true, + mpid1, + ).size + .toLong(), + 20, ) Assert.assertEquals( - MessageService.getSessionHistory( - database, - previousSession, - true, - mpid2 - ).size.toLong(), - 35 + MessageService + .getSessionHistory( + database, + previousSession, + true, + mpid2, + ).size + .toLong(), + 35, ) Assert.assertEquals( - MessageService.getSessionHistory( - database, - previousSession, - false, - mpid1 - ).size.toLong(), - 35 + MessageService + .getSessionHistory( + database, + previousSession, + false, + mpid1, + ).size + .toLong(), + 35, ) Assert.assertEquals( - MessageService.getSessionHistory( - database, - previousSession, - false, - Constants.TEMPORARY_MPID - ).size.toLong(), - 55 + MessageService + .getSessionHistory( + database, + previousSession, + false, + Constants.TEMPORARY_MPID, + ).size + .toLong(), + 55, ) } @@ -259,19 +291,20 @@ class MessageServiceTest : BaseMPServiceTest() { testMessage, testMpid, null, - null + null, ) } Assert.assertEquals( MessageService.markMessagesAsUploaded(database, Int.MAX_VALUE).toLong(), - 100 - ) - val readyMessages = MessageService.getSessionHistory( - database, - previousSession, - false, - Constants.TEMPORARY_MPID + 100, ) + val readyMessages = + MessageService.getSessionHistory( + database, + previousSession, + false, + Constants.TEMPORARY_MPID, + ) Assert.assertEquals(readyMessages.size.toLong(), testMessages.size.toLong()) for (readyMessage in readyMessages) { val message = testMessages[readyMessage.message] @@ -330,7 +363,7 @@ class MessageServiceTest : BaseMPServiceTest() { getMpMessage(currentSession), 1, null, - null + null, ) } Assert.assertEquals(MessageService.markMessagesAsUploaded(database, 10).toLong(), 10) @@ -338,7 +371,7 @@ class MessageServiceTest : BaseMPServiceTest() { MessageService.deleteOldMessages(database, currentSession) Assert.assertEquals( MessageService.getSessionHistory(database, newSession).size.toLong(), - 10 + 10, ) MessageService.deleteOldMessages(database, newSession) Assert.assertEquals(MessageService.getSessionHistory(database, newSession).size.toLong(), 0) @@ -355,8 +388,10 @@ class MessageServiceTest : BaseMPServiceTest() { for (i in 0 until Constants.LIMIT_MAX_MESSAGE_SIZE) { builder.append("ab") } - val message = BaseMPMessage.Builder(builder.toString()) - .build(InternalSession(), Location("New York City"), 1) + val message = + BaseMPMessage + .Builder(builder.toString()) + .build(InternalSession(), Location("New York City"), 1) MessageService.insertMessage(database, "apiKey", message, 1, "b", 2) Assert.assertEquals(MessageService.getMessagesForUpload(database).size.toLong(), 10) for (i in 0..9) { diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/ReportingServiceTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/ReportingServiceTest.kt index bb10d9883..7751e5e77 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/ReportingServiceTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/ReportingServiceTest.kt @@ -17,16 +17,18 @@ class ReportingServiceTest : BaseMPServiceTest() { ReportingService.insertReportingMessage(database, reportingMessage, 2L) } Assert.assertEquals( - ReportingService.getReportingMessagesForUpload( - database, - true, - 2L - ).size.toLong(), - 20 + ReportingService + .getReportingMessagesForUpload( + database, + true, + 2L, + ).size + .toLong(), + 20, ) Assert.assertEquals( ReportingService.getReportingMessagesForUpload(database).size.toLong(), - 20 + 20, ) } @@ -37,114 +39,136 @@ class ReportingServiceTest : BaseMPServiceTest() { ReportingService.insertReportingMessage(database, reportingMessage, 2L) } Assert.assertEquals( - ReportingService.getReportingMessagesForUpload( - database, - true, - 2L - ).size.toLong(), - 2 + ReportingService + .getReportingMessagesForUpload( + database, + true, + 2L, + ).size + .toLong(), + 2, ) Assert.assertEquals( - ReportingService.getReportingMessagesForUpload( - database, - true, - 3L - ).size.toLong(), - 0 + ReportingService + .getReportingMessagesForUpload( + database, + true, + 3L, + ).size + .toLong(), + 0, ) Assert.assertEquals( - ReportingService.getReportingMessagesForUpload( - database, - true, - 4L - ).size.toLong(), - 0 + ReportingService + .getReportingMessagesForUpload( + database, + true, + 4L, + ).size + .toLong(), + 0, ) Assert.assertEquals( ReportingService.getReportingMessagesForUpload(database).size.toLong(), - 2 + 2, ) for (reportingMessage in getNReportingMessages(3, "123")) { ReportingService.insertReportingMessage(database, reportingMessage, 3L) } Assert.assertEquals( - ReportingService.getReportingMessagesForUpload( - database, - true, - 2L - ).size.toLong(), - 2 + ReportingService + .getReportingMessagesForUpload( + database, + true, + 2L, + ).size + .toLong(), + 2, ) Assert.assertEquals( - ReportingService.getReportingMessagesForUpload( - database, - true, - 3L - ).size.toLong(), - 3 + ReportingService + .getReportingMessagesForUpload( + database, + true, + 3L, + ).size + .toLong(), + 3, ) Assert.assertEquals( - ReportingService.getReportingMessagesForUpload( - database, - false, - 4L - ).size.toLong(), - 5 + ReportingService + .getReportingMessagesForUpload( + database, + false, + 4L, + ).size + .toLong(), + 5, ) Assert.assertEquals( - ReportingService.getReportingMessagesForUpload( - database, - true, - 4L - ).size.toLong(), - 0 + ReportingService + .getReportingMessagesForUpload( + database, + true, + 4L, + ).size + .toLong(), + 0, ) Assert.assertEquals( ReportingService.getReportingMessagesForUpload(database).size.toLong(), - 5 + 5, ) for (reportingMessage in getNReportingMessages(3, "123")) { ReportingService.insertReportingMessage( database, reportingMessage, - Constants.TEMPORARY_MPID + Constants.TEMPORARY_MPID, ) } Assert.assertEquals( - ReportingService.getReportingMessagesForUpload( - database, - true, - 2L - ).size.toLong(), - 2 + ReportingService + .getReportingMessagesForUpload( + database, + true, + 2L, + ).size + .toLong(), + 2, ) Assert.assertEquals( - ReportingService.getReportingMessagesForUpload( - database, - true, - 3L - ).size.toLong(), - 3 + ReportingService + .getReportingMessagesForUpload( + database, + true, + 3L, + ).size + .toLong(), + 3, ) Assert.assertEquals( - ReportingService.getReportingMessagesForUpload( - database, - true, - Constants.TEMPORARY_MPID - ).size.toLong(), - 3 + ReportingService + .getReportingMessagesForUpload( + database, + true, + Constants.TEMPORARY_MPID, + ).size + .toLong(), + 3, ) Assert.assertEquals( - ReportingService.getReportingMessagesForUpload( - database, - false, - 4L - ).size.toLong(), - 8 + ReportingService + .getReportingMessagesForUpload( + database, + false, + 4L, + ).size + .toLong(), + 8, ) Assert.assertEquals( ReportingService.getReportingMessagesForUpload(database).size.toLong(), - 5 + 5, ) } @@ -185,25 +209,28 @@ class ReportingServiceTest : BaseMPServiceTest() { reportingMessages, Comparator { o1, o2 -> try { - return@Comparator o1.msgObject.getInt("a random Number") + return@Comparator o1.msgObject + .getInt("a random Number") .compareTo(o2.msgObject.getInt("a random Number")) } catch (e: JSONException) { e.printStackTrace() } -1 - } + }, ) Collections.sort( jsonReportingMessages, Comparator { o1, o2 -> try { - return@Comparator o1.toJson().getInt("a random Number") + return@Comparator o1 + .toJson() + .getInt("a random Number") .compareTo(o2.toJson().getInt("a random Number")) } catch (e: JSONException) { e.printStackTrace() } -1 - } + }, ) Assert.assertEquals(jsonReportingMessages.size.toLong(), reportingMessages.size.toLong()) var i = 0 @@ -213,16 +240,18 @@ class ReportingServiceTest : BaseMPServiceTest() { } } - private fun getNReportingMessages(n: Int): List { - return getNReportingMessages(n, null) - } + private fun getNReportingMessages(n: Int): List = getNReportingMessages(n, null) - private fun getNReportingMessages(n: Int, sessionId: String?): List { + private fun getNReportingMessages( + n: Int, + sessionId: String?, + ): List { val reportingMessages: MutableList = ArrayList() for (i in 0 until n) { reportingMessages.add( - TestingUtils.getInstance() - .getRandomReportingMessage(sessionId ?: ran.nextInt().toString()) + TestingUtils + .getInstance() + .getRandomReportingMessage(sessionId ?: ran.nextInt().toString()), ) } return reportingMessages @@ -230,7 +259,7 @@ class ReportingServiceTest : BaseMPServiceTest() { private fun equals( jsonReportingMessage: JsonReportingMessage, - reportingMessage: ReportingService.ReportingMessage + reportingMessage: ReportingService.ReportingMessage, ): Boolean { val reportingString = reportingMessage.msgObject.toString() val origString = jsonReportingMessage.toJson().toString() diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/SessionServiceTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/SessionServiceTest.kt index c1326a0f7..4a3a5b849 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/SessionServiceTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/SessionServiceTest.kt @@ -24,7 +24,7 @@ class SessionServiceTest : BaseMPServiceTest() { "foo-app-key", fooObject.toString(), fooObject.toString(), - 1 + 1, ) fooObject = JSONObject() val randomId = UUID.randomUUID().toString() @@ -76,17 +76,16 @@ class SessionServiceTest : BaseMPServiceTest() { } } - internal inner class MockMessageBatch(var id: Int) : MessageBatch() { - override fun equals(other: Any?): Boolean { - return if (other is MockMessageBatch) { + internal inner class MockMessageBatch( + var id: Int, + ) : MessageBatch() { + override fun equals(other: Any?): Boolean = + if (other is MockMessageBatch) { id == other.id } else { super.equals(other) } - } - override fun hashCode(): Int { - return id - } + override fun hashCode(): Int = id } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/UserAttributesServiceTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/UserAttributesServiceTest.kt index ef5f50f75..60358a734 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/UserAttributesServiceTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/UserAttributesServiceTest.kt @@ -13,36 +13,44 @@ class UserAttributesServiceTest : BaseMPServiceTest() { ran.nextInt().toString(), System.currentTimeMillis(), false, - 3L + 3L, ) } Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 3L - ).size.toLong(), - 20 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 4L - ).size.toLong(), - 0 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 3L - ).size.toLong(), - 0 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 4L - ).size.toLong(), - 0 + UserAttributesService + .getUserAttributesSingles( + database, + 3L, + ).size + .toLong(), + 20, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesSingles( + database, + 4L, + ).size + .toLong(), + 0, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 3L, + ).size + .toLong(), + 0, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 4L, + ).size + .toLong(), + 0, ) for (i in 0..29) { UserAttributesService.insertAttribute( @@ -51,36 +59,44 @@ class UserAttributesServiceTest : BaseMPServiceTest() { ran.nextInt().toString(), System.currentTimeMillis(), false, - 4L + 4L, ) } Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 3L - ).size.toLong(), - 20 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 4L - ).size.toLong(), - 30 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 3L - ).size.toLong(), - 0 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 4L - ).size.toLong(), - 0 + UserAttributesService + .getUserAttributesSingles( + database, + 3L, + ).size + .toLong(), + 20, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesSingles( + database, + 4L, + ).size + .toLong(), + 30, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 3L, + ).size + .toLong(), + 0, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 4L, + ).size + .toLong(), + 0, ) for (i in 0..14) { UserAttributesService.insertAttribute( @@ -89,36 +105,44 @@ class UserAttributesServiceTest : BaseMPServiceTest() { ran.nextInt().toString(), System.currentTimeMillis(), true, - 3L + 3L, ) } Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 3L - ).size.toLong(), - 20 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 4L - ).size.toLong(), - 30 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 3L - ).size.toLong(), - 15 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 4L - ).size.toLong(), - 0 + UserAttributesService + .getUserAttributesSingles( + database, + 3L, + ).size + .toLong(), + 20, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesSingles( + database, + 4L, + ).size + .toLong(), + 30, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 3L, + ).size + .toLong(), + 15, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 4L, + ).size + .toLong(), + 0, ) for (i in 0..29) { UserAttributesService.insertAttribute( @@ -127,43 +151,53 @@ class UserAttributesServiceTest : BaseMPServiceTest() { ran.nextInt().toString(), System.currentTimeMillis(), true, - 5L + 5L, ) } Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 3L - ).size.toLong(), - 20 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 4L - ).size.toLong(), - 30 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 3L - ).size.toLong(), - 15 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 4L - ).size.toLong(), - 0 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 5L - ).size.toLong(), - 30 + UserAttributesService + .getUserAttributesSingles( + database, + 3L, + ).size + .toLong(), + 20, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesSingles( + database, + 4L, + ).size + .toLong(), + 30, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 3L, + ).size + .toLong(), + 15, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 4L, + ).size + .toLong(), + 0, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 5L, + ).size + .toLong(), + 30, ) } @@ -180,7 +214,7 @@ class UserAttributesServiceTest : BaseMPServiceTest() { ran.nextInt().toString(), System.currentTimeMillis(), false, - 2L + 2L, ) } for (i in 0..2) { @@ -190,7 +224,7 @@ class UserAttributesServiceTest : BaseMPServiceTest() { ran.nextInt().toString(), System.currentTimeMillis(), false, - 3L + 3L, ) } for (i in 3..5) { @@ -200,7 +234,7 @@ class UserAttributesServiceTest : BaseMPServiceTest() { ran.nextInt().toString(), System.currentTimeMillis(), true, - 2L + 2L, ) } for (i in 3..5) { @@ -210,128 +244,160 @@ class UserAttributesServiceTest : BaseMPServiceTest() { ran.nextInt().toString(), System.currentTimeMillis(), true, - 3L + 3L, ) } Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 2L - ).size.toLong(), - 3 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 3L - ).size.toLong(), - 3 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 2L - ).size.toLong(), - 3 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 3L - ).size.toLong(), - 3 + UserAttributesService + .getUserAttributesSingles( + database, + 2L, + ).size + .toLong(), + 3, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesSingles( + database, + 3L, + ).size + .toLong(), + 3, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 2L, + ).size + .toLong(), + 3, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 3L, + ).size + .toLong(), + 3, ) UserAttributesService.deleteAttributes(database, "key1", 2L) UserAttributesService.deleteAttributes(database, "key4", 3L) Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 2L - ).size.toLong(), - 2 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 3L - ).size.toLong(), - 3 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 2L - ).size.toLong(), - 3 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 3L - ).size.toLong(), - 2 + UserAttributesService + .getUserAttributesSingles( + database, + 2L, + ).size + .toLong(), + 2, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesSingles( + database, + 3L, + ).size + .toLong(), + 3, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 2L, + ).size + .toLong(), + 3, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 3L, + ).size + .toLong(), + 2, ) for (i in 0..5) { UserAttributesService.deleteAttributes(database, "key$i", 2L) } Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 2L - ).size.toLong(), - 0 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 3L - ).size.toLong(), - 3 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 2L - ).size.toLong(), - 0 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 3L - ).size.toLong(), - 2 + UserAttributesService + .getUserAttributesSingles( + database, + 2L, + ).size + .toLong(), + 0, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesSingles( + database, + 3L, + ).size + .toLong(), + 3, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 2L, + ).size + .toLong(), + 0, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 3L, + ).size + .toLong(), + 2, ) for (i in 0..5) { UserAttributesService.deleteAttributes(database, "key$i", 3L) } Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 2L - ).size.toLong(), - 0 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesSingles( - database, - 3L - ).size.toLong(), - 0 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 2L - ).size.toLong(), - 0 - ) - Assert.assertEquals( - UserAttributesService.getUserAttributesLists( - database, - 3L - ).size.toLong(), - 0 + UserAttributesService + .getUserAttributesSingles( + database, + 2L, + ).size + .toLong(), + 0, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesSingles( + database, + 3L, + ).size + .toLong(), + 0, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 2L, + ).size + .toLong(), + 0, + ) + Assert.assertEquals( + UserAttributesService + .getUserAttributesLists( + database, + 3L, + ).size + .toLong(), + 0, ) // easy way to test to make sure that insert is working properly after delete, just run the same test again diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BaseTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BaseTableTest.kt index cc2e08af2..18acfea35 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BaseTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BaseTableTest.kt @@ -13,7 +13,10 @@ open class BaseTableTest : BaseCleanInstallEachTest() { var onUpgradeLatch: CountDownLatch = MPLatch(1) @Throws(InterruptedException::class) - protected fun runTest(helper: SQLiteOpenHelperWrapper?, oldVersion: Int = 6) { + protected fun runTest( + helper: SQLiteOpenHelperWrapper?, + oldVersion: Int = 6, + ) { InstrumentationRegistry.getInstrumentation().targetContext.deleteDatabase(DB_NAME) var openHelper = helper?.let { TestSQLiteOpenHelper(it, DB_NAME, oldVersion) } openHelper?.writableDatabase diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BreadcrumbTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BreadcrumbTableTest.kt index 517e22709..f317644a9 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BreadcrumbTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BreadcrumbTableTest.kt @@ -9,25 +9,36 @@ class BreadcrumbTableTest : BaseTableTest() { @Test @Throws(InterruptedException::class) fun createTableTest() { - runTest(object : SQLiteOpenHelperWrapper { - override fun onCreate(database: SQLiteDatabase) { - database.execSQL(BreadcrumbTable.CREATE_BREADCRUMBS_DDL) - } + runTest( + object : SQLiteOpenHelperWrapper { + override fun onCreate(database: SQLiteDatabase) { + database.execSQL(BreadcrumbTable.CREATE_BREADCRUMBS_DDL) + } - override fun onUpgrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {} - override fun onDowngrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {} - }) + override fun onUpgrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) {} + + override fun onDowngrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) {} + }, + ) } companion object { const val old_CREATE_BREADCRUMBS_DDL = - "CREATE TABLE IF NOT EXISTS " + BreadcrumbTable.BreadcrumbTableColumns.TABLE_NAME + " (" + BaseColumns._ID + - " INTEGER PRIMARY KEY AUTOINCREMENT, " + - BreadcrumbTable.BreadcrumbTableColumns.SESSION_ID + " STRING NOT NULL, " + - BreadcrumbTable.BreadcrumbTableColumns.API_KEY + " STRING NOT NULL, " + - BreadcrumbTable.BreadcrumbTableColumns.MESSAGE + " TEXT, " + - BreadcrumbTable.BreadcrumbTableColumns.CREATED_AT + " INTEGER NOT NULL, " + - BreadcrumbTable.BreadcrumbTableColumns.CF_UUID + " TEXT" + + "CREATE TABLE IF NOT EXISTS " + BreadcrumbTable.BreadcrumbTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + BreadcrumbTable.BreadcrumbTableColumns.SESSION_ID + " STRING NOT NULL, " + BreadcrumbTable.BreadcrumbTableColumns.API_KEY + " STRING NOT NULL, " + BreadcrumbTable.BreadcrumbTableColumns.MESSAGE + " TEXT, " + BreadcrumbTable.BreadcrumbTableColumns.CREATED_AT + " INTEGER NOT NULL, " + BreadcrumbTable.BreadcrumbTableColumns.CF_UUID + " TEXT" ");" } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/MessageTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/MessageTableTest.kt index 237179db9..e3af25531 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/MessageTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/MessageTableTest.kt @@ -9,59 +9,79 @@ class MessageTableTest : BaseTableTest() { @Test @Throws(InterruptedException::class) fun createTableTest() { - runTest(object : SQLiteOpenHelperWrapper { - override fun onCreate(database: SQLiteDatabase) { - database.execSQL(MessageTable.CREATE_MESSAGES_DDL) - } + runTest( + object : SQLiteOpenHelperWrapper { + override fun onCreate(database: SQLiteDatabase) { + database.execSQL(MessageTable.CREATE_MESSAGES_DDL) + } - override fun onUpgrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) { - // do nothing - } + override fun onUpgrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) { + // do nothing + } - override fun onDowngrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {} - }) + override fun onDowngrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) {} + }, + ) } @Test @Throws(InterruptedException::class) fun addDataplanColumnsTest() { - runTest(object : SQLiteOpenHelperWrapper { - override fun onCreate(database: SQLiteDatabase) { - database.execSQL(old_no_dp_CREATE_MESSAGES_DDL) - } + runTest( + object : SQLiteOpenHelperWrapper { + override fun onCreate(database: SQLiteDatabase) { + database.execSQL(old_no_dp_CREATE_MESSAGES_DDL) + } - override fun onUpgrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) { - database.execSQL(MessageTable.ADD_DATAPLAN_ID_COLUMN) - database.execSQL(MessageTable.ADD_DATAPLAN_VERSION_COLUMN) - } + override fun onUpgrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) { + database.execSQL(MessageTable.ADD_DATAPLAN_ID_COLUMN) + database.execSQL(MessageTable.ADD_DATAPLAN_VERSION_COLUMN) + } - override fun onDowngrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {} - }) + override fun onDowngrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) {} + }, + ) } companion object { const val old_no_mpid_CREATE_MESSAGES_DDL = - "CREATE TABLE IF NOT EXISTS " + MessageTable.MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID + - " INTEGER PRIMARY KEY AUTOINCREMENT, " + - MessageTable.MessageTableColumns.SESSION_ID + " STRING NOT NULL, " + - MessageTable.MessageTableColumns.API_KEY + " STRING NOT NULL, " + - MessageTable.MessageTableColumns.MESSAGE + " TEXT, " + - MessageTable.MessageTableColumns.STATUS + " INTEGER, " + - MessageTable.MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " + - MessageTable.MessageTableColumns.MESSAGE_TYPE + " TEXT, " + - MessageTable.MessageTableColumns.CF_UUID + " TEXT" + + "CREATE TABLE IF NOT EXISTS " + MessageTable.MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + MessageTable.MessageTableColumns.SESSION_ID + " STRING NOT NULL, " + MessageTable.MessageTableColumns.API_KEY + " STRING NOT NULL, " + MessageTable.MessageTableColumns.MESSAGE + " TEXT, " + MessageTable.MessageTableColumns.STATUS + " INTEGER, " + MessageTable.MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " + MessageTable.MessageTableColumns.MESSAGE_TYPE + " TEXT, " + MessageTable.MessageTableColumns.CF_UUID + " TEXT" ");" private const val old_no_dp_CREATE_MESSAGES_DDL = - "CREATE TABLE IF NOT EXISTS " + MessageTable.MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID + - " INTEGER PRIMARY KEY AUTOINCREMENT, " + - MessageTable.MessageTableColumns.SESSION_ID + " STRING NOT NULL, " + - MessageTable.MessageTableColumns.API_KEY + " STRING NOT NULL, " + - MessageTable.MessageTableColumns.MESSAGE + " TEXT, " + - MessageTable.MessageTableColumns.STATUS + " INTEGER, " + - MessageTable.MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " + - MessageTable.MessageTableColumns.MESSAGE_TYPE + " TEXT, " + - MessageTable.MessageTableColumns.CF_UUID + " TEXT, " + - MessageTable.MessageTableColumns.MP_ID + " INTEGER " + + "CREATE TABLE IF NOT EXISTS " + MessageTable.MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + MessageTable.MessageTableColumns.SESSION_ID + " STRING NOT NULL, " + MessageTable.MessageTableColumns.API_KEY + " STRING NOT NULL, " + MessageTable.MessageTableColumns.MESSAGE + " TEXT, " + MessageTable.MessageTableColumns.STATUS + " INTEGER, " + MessageTable.MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " + MessageTable.MessageTableColumns.MESSAGE_TYPE + " TEXT, " + MessageTable.MessageTableColumns.CF_UUID + " TEXT, " + MessageTable.MessageTableColumns.MP_ID + " INTEGER " ");" } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/ReportingTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/ReportingTableTest.kt index c8f3a5799..40e4e8a76 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/ReportingTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/ReportingTableTest.kt @@ -9,24 +9,35 @@ class ReportingTableTest : BaseTableTest() { @Test @Throws(InterruptedException::class) fun createTableTest() { - runTest(object : SQLiteOpenHelperWrapper { - override fun onCreate(database: SQLiteDatabase) { - database.execSQL(ReportingTable.CREATE_REPORTING_DDL) - } + runTest( + object : SQLiteOpenHelperWrapper { + override fun onCreate(database: SQLiteDatabase) { + database.execSQL(ReportingTable.CREATE_REPORTING_DDL) + } - override fun onUpgrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {} - override fun onDowngrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {} - }) + override fun onUpgrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) {} + + override fun onDowngrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) {} + }, + ) } companion object { const val old_CREATE_REPORTING_DDL = - "CREATE TABLE IF NOT EXISTS " + ReportingTable.ReportingTableColumns.TABLE_NAME + " (" + BaseColumns._ID + - " INTEGER PRIMARY KEY AUTOINCREMENT, " + - ReportingTable.ReportingTableColumns.MODULE_ID + " INTEGER NOT NULL, " + - ReportingTable.ReportingTableColumns.MESSAGE + " TEXT NOT NULL, " + - ReportingTable.ReportingTableColumns.SESSION_ID + " STRING NOT NULL, " + - ReportingTable.ReportingTableColumns.CREATED_AT + " INTEGER NOT NULL" + + "CREATE TABLE IF NOT EXISTS " + ReportingTable.ReportingTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ReportingTable.ReportingTableColumns.MODULE_ID + " INTEGER NOT NULL, " + ReportingTable.ReportingTableColumns.MESSAGE + " TEXT NOT NULL, " + ReportingTable.ReportingTableColumns.SESSION_ID + " STRING NOT NULL, " + ReportingTable.ReportingTableColumns.CREATED_AT + " INTEGER NOT NULL" ");" } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/SessionTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/SessionTableTest.kt index 6ed42687f..96e3eeb9b 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/SessionTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/SessionTableTest.kt @@ -9,29 +9,40 @@ class SessionTableTest : BaseTableTest() { @Test @Throws(InterruptedException::class) fun createTableTest() { - runTest(object : SQLiteOpenHelperWrapper { - override fun onCreate(database: SQLiteDatabase) { - database.execSQL(SessionTable.CREATE_SESSIONS_DDL) - } + runTest( + object : SQLiteOpenHelperWrapper { + override fun onCreate(database: SQLiteDatabase) { + database.execSQL(SessionTable.CREATE_SESSIONS_DDL) + } - override fun onUpgrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {} - override fun onDowngrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {} - }) + override fun onUpgrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) {} + + override fun onDowngrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) {} + }, + ) } companion object { const val old_CREATE_SESSION_DDL = - "CREATE TABLE IF NOT EXISTS " + SessionTable.SessionTableColumns.TABLE_NAME + " (" + BaseColumns._ID + - " INTEGER PRIMARY KEY AUTOINCREMENT, " + - SessionTable.SessionTableColumns.SESSION_ID + " STRING NOT NULL, " + - SessionTable.SessionTableColumns.API_KEY + " STRING NOT NULL, " + - SessionTable.SessionTableColumns.START_TIME + " INTEGER NOT NULL," + - SessionTable.SessionTableColumns.END_TIME + " INTEGER NOT NULL," + - SessionTable.SessionTableColumns.SESSION_FOREGROUND_LENGTH + " INTEGER NOT NULL," + - SessionTable.SessionTableColumns.ATTRIBUTES + " TEXT, " + - SessionTable.SessionTableColumns.STATUS + " TEXT," + - SessionTable.SessionTableColumns.APP_INFO + " TEXT, " + - SessionTable.SessionTableColumns.DEVICE_INFO + " TEXT" + + "CREATE TABLE IF NOT EXISTS " + SessionTable.SessionTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + SessionTable.SessionTableColumns.SESSION_ID + " STRING NOT NULL, " + SessionTable.SessionTableColumns.API_KEY + " STRING NOT NULL, " + SessionTable.SessionTableColumns.START_TIME + " INTEGER NOT NULL," + SessionTable.SessionTableColumns.END_TIME + " INTEGER NOT NULL," + SessionTable.SessionTableColumns.SESSION_FOREGROUND_LENGTH + " INTEGER NOT NULL," + SessionTable.SessionTableColumns.ATTRIBUTES + " TEXT, " + SessionTable.SessionTableColumns.STATUS + " TEXT," + SessionTable.SessionTableColumns.APP_INFO + " TEXT, " + SessionTable.SessionTableColumns.DEVICE_INFO + " TEXT" ");" } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UploadTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UploadTableTest.kt index 0d31217fa..5a11c70bc 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UploadTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UploadTableTest.kt @@ -8,16 +8,26 @@ class UploadTableTest : BaseTableTest() { @Test @Throws(InterruptedException::class) fun createTableTest() { - runTest(object : SQLiteOpenHelperWrapper { - override fun onCreate(database: SQLiteDatabase) { - database.execSQL(UploadTable.CREATE_UPLOADS_DDL) - } + runTest( + object : SQLiteOpenHelperWrapper { + override fun onCreate(database: SQLiteDatabase) { + database.execSQL(UploadTable.CREATE_UPLOADS_DDL) + } - override fun onUpgrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) { - // do nothing - } + override fun onUpgrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) { + // do nothing + } - override fun onDowngrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {} - }) + override fun onDowngrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) {} + }, + ) } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UserAttributeTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UserAttributeTableTest.kt index 0c6aa71e3..3b938ccf6 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UserAttributeTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UserAttributeTableTest.kt @@ -9,24 +9,35 @@ class UserAttributeTableTest : BaseTableTest() { @Test @Throws(InterruptedException::class) fun createTableTest() { - runTest(object : SQLiteOpenHelperWrapper { - override fun onCreate(database: SQLiteDatabase) { - database.execSQL(UserAttributesTable.CREATE_USER_ATTRIBUTES_DDL) - } + runTest( + object : SQLiteOpenHelperWrapper { + override fun onCreate(database: SQLiteDatabase) { + database.execSQL(UserAttributesTable.CREATE_USER_ATTRIBUTES_DDL) + } - override fun onUpgrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {} - override fun onDowngrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {} - }) + override fun onUpgrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) {} + + override fun onDowngrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) {} + }, + ) } companion object { const val old_CREATE_USER_ATTRIBUTES_DDL = - "CREATE TABLE IF NOT EXISTS " + UserAttributesTable.UserAttributesTableColumns.TABLE_NAME + " (" + BaseColumns._ID + - " INTEGER PRIMARY KEY AUTOINCREMENT, " + - UserAttributesTable.UserAttributesTableColumns.ATTRIBUTE_KEY + " COLLATE NOCASE NOT NULL, " + - UserAttributesTable.UserAttributesTableColumns.ATTRIBUTE_VALUE + " TEXT, " + - UserAttributesTable.UserAttributesTableColumns.IS_LIST + " INTEGER NOT NULL, " + - UserAttributesTable.UserAttributesTableColumns.CREATED_AT + " INTEGER NOT NULL " + + "CREATE TABLE IF NOT EXISTS " + UserAttributesTable.UserAttributesTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + UserAttributesTable.UserAttributesTableColumns.ATTRIBUTE_KEY + " COLLATE NOCASE NOT NULL, " + UserAttributesTable.UserAttributesTableColumns.ATTRIBUTE_VALUE + " TEXT, " + UserAttributesTable.UserAttributesTableColumns.IS_LIST + " INTEGER NOT NULL, " + UserAttributesTable.UserAttributesTableColumns.CREATED_AT + " INTEGER NOT NULL " ");" } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/networking/AccessUtils.kt b/android-core/src/androidTest/kotlin/com.mparticle/networking/AccessUtils.kt index 17191bddf..b618fbbbe 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/networking/AccessUtils.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/networking/AccessUtils.kt @@ -4,7 +4,10 @@ object AccessUtils { val defaultNetworkOptions: NetworkOptions get() = NetworkOptionsManager.defaultNetworkOptions() - fun equals(networkOptions1: NetworkOptions, networkOptions2: NetworkOptions): Boolean { + fun equals( + networkOptions1: NetworkOptions, + networkOptions2: NetworkOptions, + ): Boolean { if (networkOptions1 === networkOptions2) { return true } @@ -20,7 +23,10 @@ object AccessUtils { return true } - fun equals(domainMapping1: DomainMapping, domainMapping2: DomainMapping): Boolean { + fun equals( + domainMapping1: DomainMapping, + domainMapping2: DomainMapping, + ): Boolean { if (domainMapping1 === domainMapping2) { return true } @@ -34,13 +40,16 @@ object AccessUtils { return true } - fun equals(certificate1: Certificate, certificate2: Certificate): Boolean { + fun equals( + certificate1: Certificate, + certificate2: Certificate, + ): Boolean { if (certificate1 == certificate2) { return true } return ( (certificate1.certificate === certificate2.certificate || certificate1.certificate == certificate2.certificate) && (certificate1.alias === certificate2.alias || certificate1.alias == certificate2.alias) - ) + ) } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/networking/MParticleBaseClientImplTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/networking/MParticleBaseClientImplTest.kt index 5a634f2e8..349a4faa4 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/networking/MParticleBaseClientImplTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/networking/MParticleBaseClientImplTest.kt @@ -25,7 +25,12 @@ class MParticleBaseClientImplTest : BaseCleanInstallEachTest() { val baseClientImpl = AccessUtils.getApiClient() as MParticleBaseClientImpl for (endpoint in MParticleBaseClientImpl.Endpoint.values()) { defaultUrls[endpoint] = - baseClientImpl.getUrl(endpoint, endpoint.name, null, UploadSettings(apiKey, "secret", NetworkOptions.builder().build(), "", "")) + baseClientImpl.getUrl( + endpoint, + endpoint.name, + null, + UploadSettings(apiKey, "secret", NetworkOptions.builder().build(), "", ""), + ) } MParticle.setInstance(null) } @@ -37,26 +42,28 @@ class MParticleBaseClientImplTest : BaseCleanInstallEachTest() { val configUrl = mRandomUtils.getAlphaString(20) val audienceUrl = mRandomUtils.getAlphaString(20) val eventsUrl = mRandomUtils.getAlphaString(20) - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .networkOptions( - NetworkOptions.builder() - .addDomainMapping( - DomainMapping.audienceMapping(audienceUrl) - .build() - ) - .addDomainMapping( - DomainMapping.configMapping(configUrl) - .build() - ) - .addDomainMapping( - DomainMapping.identityMapping(identityUrl) - .build() - ) - .addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) - .build() - ) - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .networkOptions( + NetworkOptions + .builder() + .addDomainMapping( + DomainMapping + .audienceMapping(audienceUrl) + .build(), + ).addDomainMapping( + DomainMapping + .configMapping(configUrl) + .build(), + ).addDomainMapping( + DomainMapping + .identityMapping(identityUrl) + .build(), + ).addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) + .build(), + ).build() MParticle.start(options) val baseClientImpl = AccessUtils.getApiClient() as MParticleBaseClientImpl val url = @@ -71,26 +78,28 @@ class MParticleBaseClientImplTest : BaseCleanInstallEachTest() { val configUrl = mRandomUtils.getAlphaString(20) val audienceUrl = mRandomUtils.getAlphaString(20) val eventsUrl = mRandomUtils.getAlphaString(20) - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .networkOptions( - NetworkOptions.builder() - .addDomainMapping( - DomainMapping.audienceMapping(audienceUrl) - .build() - ) - .addDomainMapping( - DomainMapping.configMapping(configUrl) - .build() - ) - .addDomainMapping( - DomainMapping.identityMapping(identityUrl) - .build() - ) - .addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) - .build() - ) - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .networkOptions( + NetworkOptions + .builder() + .addDomainMapping( + DomainMapping + .audienceMapping(audienceUrl) + .build(), + ).addDomainMapping( + DomainMapping + .configMapping(configUrl) + .build(), + ).addDomainMapping( + DomainMapping + .identityMapping(identityUrl) + .build(), + ).addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) + .build(), + ).build() MParticle.start(options) val baseClientImpl = AccessUtils.getApiClient() as MParticleBaseClientImpl val url = @@ -100,53 +109,57 @@ class MParticleBaseClientImplTest : BaseCleanInstallEachTest() { @Test fun testAllPrefixes() { - val mConfigManager = ConfigManager( - mContext, - MParticle.Environment.Production, - "some api key", - "some api secret", - null, - null, - null, - null, - null, - null - ) + val mConfigManager = + ConfigManager( + mContext, + MParticle.Environment.Production, + "some api key", + "some api secret", + null, + null, + null, + null, + null, + null, + ) // Following are the fake APIs for testing purposes. - val map = mapOf( - Pair("us1-1vc4gbp24cdtx6e31s58icnymzy83f1uf", "us1"), - Pair("us2-v2p8lr3w2g90vtpaumbq21zy05cl50qm3", "us2"), - Pair("eu1-bkabfno0b8zpv5bwi2zm2mfa1kfml19al", "eu1"), - Pair("au1-iermuj83dbeoshm0n32f10feotclq6i4a", "au1"), - Pair("st1-k77ivhkbbqf4ce0s3y12zpcthyn1ixfyu", "st1"), - Pair("us3-w1y2y8yj8q58d5bx9u2dvtxzl4cpa7cuf", "us3"), - Pair("kajsdhasdiuyaiudiashhadjhdasjk", "us1") - ) + val map = + mapOf( + Pair("us1-1vc4gbp24cdtx6e31s58icnymzy83f1uf", "us1"), + Pair("us2-v2p8lr3w2g90vtpaumbq21zy05cl50qm3", "us2"), + Pair("eu1-bkabfno0b8zpv5bwi2zm2mfa1kfml19al", "eu1"), + Pair("au1-iermuj83dbeoshm0n32f10feotclq6i4a", "au1"), + Pair("st1-k77ivhkbbqf4ce0s3y12zpcthyn1ixfyu", "st1"), + Pair("us3-w1y2y8yj8q58d5bx9u2dvtxzl4cpa7cuf", "us3"), + Pair("kajsdhasdiuyaiudiashhadjhdasjk", "us1"), + ) val identityUrl = mRandomUtils.getAlphaString(20) val configUrl = mRandomUtils.getAlphaString(20) val audienceUrl = mRandomUtils.getAlphaString(20) val eventsUrl = mRandomUtils.getAlphaString(20) - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .networkOptions( - NetworkOptions.builder() - .addDomainMapping( - DomainMapping.audienceMapping(audienceUrl) - .build() - ) - .addDomainMapping( - DomainMapping.configMapping(configUrl) - .build() - ) - .addDomainMapping( - DomainMapping.identityMapping(identityUrl) - .build() - ) - .addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) - .build() - ) - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .networkOptions( + NetworkOptions + .builder() + .addDomainMapping( + DomainMapping + .audienceMapping(audienceUrl) + .build(), + ).addDomainMapping( + DomainMapping + .configMapping(configUrl) + .build(), + ).addDomainMapping( + DomainMapping + .identityMapping(identityUrl) + .build(), + ).addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) + .build(), + ).build() MParticle.start(options) val baseClientImpl = AccessUtils.getApiClient() as MParticleBaseClientImpl map.forEach { (key, value) -> @@ -158,16 +171,16 @@ class MParticleBaseClientImplTest : BaseCleanInstallEachTest() { baseClientImpl.getPodUrl( NetworkOptionsManager.MP_URL_PREFIX, prefix, - true - ) + true, + ), ) assertEquals( "${NetworkOptionsManager.MP_IDENTITY_URL_PREFIX}.$prefix.mparticle.com", baseClientImpl.getPodUrl( NetworkOptionsManager.MP_IDENTITY_URL_PREFIX, prefix, - true - ) + true, + ), ) assertEquals( @@ -175,16 +188,16 @@ class MParticleBaseClientImplTest : BaseCleanInstallEachTest() { baseClientImpl.getPodUrl( NetworkOptionsManager.MP_URL_PREFIX, prefix, - false - ) + false, + ), ) assertEquals( "${NetworkOptionsManager.MP_IDENTITY_URL_PREFIX}.mparticle.com", baseClientImpl.getPodUrl( NetworkOptionsManager.MP_IDENTITY_URL_PREFIX, prefix, - false - ) + false, + ), ) } } @@ -196,26 +209,28 @@ class MParticleBaseClientImplTest : BaseCleanInstallEachTest() { val configUrl = mRandomUtils.getAlphaString(20) val audienceUrl = mRandomUtils.getAlphaString(20) val eventsUrl = mRandomUtils.getAlphaString(20) - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .networkOptions( - NetworkOptions.builder() - .addDomainMapping( - DomainMapping.audienceMapping(audienceUrl) - .build() - ) - .addDomainMapping( - DomainMapping.configMapping(configUrl) - .build() - ) - .addDomainMapping( - DomainMapping.identityMapping(identityUrl) - .build() - ) - .addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) - .build() - ) - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .networkOptions( + NetworkOptions + .builder() + .addDomainMapping( + DomainMapping + .audienceMapping(audienceUrl) + .build(), + ).addDomainMapping( + DomainMapping + .configMapping(configUrl) + .build(), + ).addDomainMapping( + DomainMapping + .identityMapping(identityUrl) + .build(), + ).addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) + .build(), + ).build() MParticle.start(options) val uploadSettings = UploadSettings(apiKey, "secret", options.networkOptions, "", "") val baseClientImpl = AccessUtils.getApiClient() as MParticleBaseClientImpl @@ -229,7 +244,7 @@ class MParticleBaseClientImplTest : BaseCleanInstallEachTest() { Assert.assertFalse(generatedUrl === generatedUrl.defaultUrl) assertEquals( defaultUrls[endpoint].toString(), - generatedUrl.defaultUrl.toString() + generatedUrl.defaultUrl.toString(), ) } } @@ -237,118 +252,143 @@ class MParticleBaseClientImplTest : BaseCleanInstallEachTest() { @Test @Throws(MalformedURLException::class) fun testGenerateDefaultURL() { - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .build() MParticle.start(options) val baseClientImpl = AccessUtils.getApiClient() as MParticleBaseClientImpl val subdirectory = "/v2/" - val uri = Uri.Builder() - .scheme(BuildConfig.SCHEME) - .encodedAuthority("nativesdks.us1.mparticle.com") - .path("$subdirectory us1-foo/events") - .build() - val result = baseClientImpl.generateDefaultURL( - false, - uri, - "nativesdks.mparticle.com", - "v2/us1-akshd324uajbhg123OIASI/events" - ) + val uri = + Uri + .Builder() + .scheme(BuildConfig.SCHEME) + .encodedAuthority("nativesdks.us1.mparticle.com") + .path("$subdirectory us1-foo/events") + .build() + val result = + baseClientImpl.generateDefaultURL( + false, + uri, + "nativesdks.mparticle.com", + "v2/us1-akshd324uajbhg123OIASI/events", + ) assertEquals("https://nativesdks.mparticle.com/v2/us1-akshd324uajbhg123OIASI/events", result.toString()) } @Test @Throws(MalformedURLException::class) fun testGenerateDefaultURL_When_defaultDomain_IS_Empty() { - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .build() MParticle.start(options) val baseClientImpl = AccessUtils.getApiClient() as MParticleBaseClientImpl val subdirectory = "/v2/" - val uri = Uri.Builder() - .scheme(BuildConfig.SCHEME) - .encodedAuthority("nativesdks.us1.mparticle.com") - .path("$subdirectory eu1-fooapi/events") - .build() - val result = baseClientImpl.generateDefaultURL( - false, - uri, - "", - "v2/us1-asjdjasdgjhasgdjhas/events" - ) + val uri = + Uri + .Builder() + .scheme(BuildConfig.SCHEME) + .encodedAuthority("nativesdks.us1.mparticle.com") + .path("$subdirectory eu1-fooapi/events") + .build() + val result = + baseClientImpl.generateDefaultURL( + false, + uri, + "", + "v2/us1-asjdjasdgjhasgdjhas/events", + ) assertEquals("https://nativesdks.us1.mparticle.com/v2/us1-asjdjasdgjhasgdjhas/events", result.toString()) } @Test @Throws(MalformedURLException::class) fun testGenerateDefaultURL_When_defaultDomain_IS_NULL() { - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .build() MParticle.start(options) val baseClientImpl = AccessUtils.getApiClient() as MParticleBaseClientImpl val subdirectory = "/v2/" - val uri = Uri.Builder() - .scheme(BuildConfig.SCHEME) - .encodedAuthority("nativesdks.us1.mparticle.com") - .path("$subdirectory us1-foo/events") - .build() - val result = baseClientImpl.generateDefaultURL( - false, - uri, - null, - "v2/us1-asjdjasdgjhasgdjhas/events" - ) + val uri = + Uri + .Builder() + .scheme(BuildConfig.SCHEME) + .encodedAuthority("nativesdks.us1.mparticle.com") + .path("$subdirectory us1-foo/events") + .build() + val result = + baseClientImpl.generateDefaultURL( + false, + uri, + null, + "v2/us1-asjdjasdgjhasgdjhas/events", + ) assertEquals("https://nativesdks.us1.mparticle.com/v2/us1-asjdjasdgjhasgdjhas/events", result.toString()) } @Test @Throws(MalformedURLException::class) fun testGenerateDefaultURL_When_URL_IS_NULL() { - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .build() MParticle.start(options) val baseClientImpl = AccessUtils.getApiClient() as MParticleBaseClientImpl - val result = baseClientImpl.generateDefaultURL( - false, - null, - "nativesdks.mparticle.com", - "v2/us1-bee5781b649a7a40a592c2000bc892d0/events" - ) + val result = + baseClientImpl.generateDefaultURL( + false, + null, + "nativesdks.mparticle.com", + "v2/us1-bee5781b649a7a40a592c2000bc892d0/events", + ) assertEquals(null, result) } @Test @Throws(MalformedURLException::class) fun testGenerateDefaultURL_When_PATH_IS_NULL() { - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .build() MParticle.start(options) val baseClientImpl = AccessUtils.getApiClient() as MParticleBaseClientImpl val subdirectory = "/v2/" - val uri = Uri.Builder() - .scheme(BuildConfig.SCHEME) - .encodedAuthority("nativesdks.us1.mparticle.com") - .path("$subdirectory us1-foo/events") - .build() - val result = baseClientImpl.generateDefaultURL( - false, - uri, - "nativesdks.mparticle.com", - null - ) + val uri = + Uri + .Builder() + .scheme(BuildConfig.SCHEME) + .encodedAuthority("nativesdks.us1.mparticle.com") + .path("$subdirectory us1-foo/events") + .build() + val result = + baseClientImpl.generateDefaultURL( + false, + uri, + "nativesdks.mparticle.com", + null, + ) assertEquals("https://nativesdks.mparticle.com/v2/%20us1-foo/events", result.toString()) } @Test @Throws(MalformedURLException::class) fun testGenerateDefaultURL_When_defaultDomain_AND_URL_AND_PATH_ARE_NULL() { - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .build() MParticle.start(options) val baseClientImpl = AccessUtils.getApiClient() as MParticleBaseClientImpl val result = baseClientImpl.generateDefaultURL(false, null, null, null) @@ -358,23 +398,28 @@ class MParticleBaseClientImplTest : BaseCleanInstallEachTest() { @Test @Throws(MalformedURLException::class) fun testGenerateDefaultURL_When_defaultDomain_FLAG_IS_TRUE() { - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .build() MParticle.start(options) val baseClientImpl = AccessUtils.getApiClient() as MParticleBaseClientImpl val subdirectory = "/v2/" - val uri = Uri.Builder() - .scheme(BuildConfig.SCHEME) - .encodedAuthority("nativesdks.us1.mparticle.com") - .path("$subdirectory us1-foo/events") - .build() - val result = baseClientImpl.generateDefaultURL( - true, - uri, - "nativesdks.mparticle.com", - "v2/us1-akshd324uajbhg123OIASI/events" - ) + val uri = + Uri + .Builder() + .scheme(BuildConfig.SCHEME) + .encodedAuthority("nativesdks.us1.mparticle.com") + .path("$subdirectory us1-foo/events") + .build() + val result = + baseClientImpl.generateDefaultURL( + true, + uri, + "nativesdks.mparticle.com", + "v2/us1-akshd324uajbhg123OIASI/events", + ) assertEquals(null, result) } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/networking/NetworkOptionsManagerTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/networking/NetworkOptionsManagerTest.kt index c20b3ef4c..9071707bb 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/networking/NetworkOptionsManagerTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/networking/NetworkOptionsManagerTest.kt @@ -15,15 +15,15 @@ class NetworkOptionsManagerTest { Assert.assertTrue( AccessUtils.equals( refinedNetworkOptions, - NetworkOptionsManager.defaultNetworkOptions() - ) + NetworkOptionsManager.defaultNetworkOptions(), + ), ) refinedNetworkOptions = NetworkOptionsManager.validateAndResolve(null) Assert.assertTrue( AccessUtils.equals( refinedNetworkOptions, - NetworkOptionsManager.defaultNetworkOptions() - ) + NetworkOptionsManager.defaultNetworkOptions(), + ), ) for ( certificate in refinedNetworkOptions.domainMappings[MParticleBaseClientImpl.Endpoint.IDENTITY]!! @@ -48,8 +48,10 @@ class NetworkOptionsManagerTest { @Test @Throws(Exception::class) fun partialNetworkOptionTest() { - val options = NetworkOptions.builder() - .addDomainMapping(DomainMapping.eventsMapping("www.events.com").build()) - .build() + val options = + NetworkOptions + .builder() + .addDomainMapping(DomainMapping.eventsMapping("www.events.com").build()) + .build() } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/networking/NetworkOptionsTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/networking/NetworkOptionsTest.kt index 106ab536c..b99330c46 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/networking/NetworkOptionsTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/networking/NetworkOptionsTest.kt @@ -42,53 +42,54 @@ class NetworkOptionsTest : BaseCleanInstallEachTest() { setClients() Assert.assertEquals( baseClientImpl.getPodUrl(NetworkOptionsManager.MP_URL_PREFIX, "", false), - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority, ) Assert.assertEquals( NetworkOptionsManager.MP_CONFIG_URL, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority, ) Assert.assertEquals( baseClientImpl.getPodUrl(NetworkOptionsManager.MP_URL_PREFIX, "", false), - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority, ) Assert.assertEquals( baseClientImpl.getPodUrl( NetworkOptionsManager.MP_IDENTITY_URL_PREFIX, "", - false + false, ), - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority, ) var randIdentityPath = mRandomUtils.getAlphaString(10) Assert.assertEquals( "/v1/$randIdentityPath", - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY, randIdentityPath, null).path + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY, randIdentityPath, null).path, ) Assert.assertEquals( NetworkOptionsManager.MP_URL, - identityClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority + identityClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority, ) Assert.assertEquals( NetworkOptionsManager.MP_CONFIG_URL, - identityClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority + identityClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority, ) Assert.assertEquals( NetworkOptionsManager.MP_URL, - identityClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority + identityClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority, ) Assert.assertEquals( NetworkOptionsManager.MP_IDENTITY_URL_PREFIX.addSuffix(), - identityClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority + identityClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority, ) randIdentityPath = mRandomUtils.getAlphaString(10) Assert.assertEquals( "/v1/$randIdentityPath", - identityClient.getUrl( - MParticleBaseClientImpl.Endpoint.IDENTITY, - randIdentityPath, - null - ).path + identityClient + .getUrl( + MParticleBaseClientImpl.Endpoint.IDENTITY, + randIdentityPath, + null, + ).path, ) } @@ -101,95 +102,99 @@ class NetworkOptionsTest : BaseCleanInstallEachTest() { val configUrl = mRandomUtils.getAlphaString(20) val audienceUrl = mRandomUtils.getAlphaString(20) val eventsUrl = mRandomUtils.getAlphaString(20) - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .networkOptions( - NetworkOptions.builder() - .addDomainMapping( - DomainMapping.audienceMapping(audienceUrl) - .build() - ) - .addDomainMapping( - DomainMapping.configMapping(configUrl) - .build() - ) - .addDomainMapping( - DomainMapping.identityMapping(identityUrl) - .build() - ) - .addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) - .build() - ) - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .networkOptions( + NetworkOptions + .builder() + .addDomainMapping( + DomainMapping + .audienceMapping(audienceUrl) + .build(), + ).addDomainMapping( + DomainMapping + .configMapping(configUrl) + .build(), + ).addDomainMapping( + DomainMapping + .identityMapping(identityUrl) + .build(), + ).addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) + .build(), + ).build() MParticle.start(options) setClients() Assert.assertEquals( audienceUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority, ) Assert.assertEquals( configUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority, ) Assert.assertEquals( eventsUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority, ) Assert.assertEquals( identityUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority, ) var randIdentityPath = mRandomUtils.getAlphaString(10) Assert.assertEquals( "/v1/$randIdentityPath", - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY, randIdentityPath, null).path + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY, randIdentityPath, null).path, ) Assert.assertEquals( audienceUrl, - identityClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority + identityClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority, ) Assert.assertEquals( configUrl, - identityClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority + identityClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority, ) Assert.assertEquals( eventsUrl, - identityClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority + identityClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority, ) Assert.assertEquals( identityUrl, - identityClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority + identityClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority, ) randIdentityPath = mRandomUtils.getAlphaString(10) Assert.assertEquals( "/v1/$randIdentityPath", - identityClient.getUrl( - MParticleBaseClientImpl.Endpoint.IDENTITY, - randIdentityPath, - null - ).path + identityClient + .getUrl( + MParticleBaseClientImpl.Endpoint.IDENTITY, + randIdentityPath, + null, + ).path, ) // test the that the Path is still the default one (make sure the overrideSubdirectory is not kicking in when it shouldn't) Assert.assertEquals( defaultUrls[MParticleBaseClientImpl.Endpoint.AUDIENCE]?.path, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).path + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).path, ) Assert.assertEquals( defaultUrls[MParticleBaseClientImpl.Endpoint.CONFIG]?.path, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).path + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).path, ) Assert.assertEquals( defaultUrls[MParticleBaseClientImpl.Endpoint.EVENTS]?.path, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).path + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).path, ) Assert.assertEquals( defaultUrls[MParticleBaseClientImpl.Endpoint.IDENTITY]?.path, - mpClient.getUrl( - MParticleBaseClientImpl.Endpoint.IDENTITY, - MParticleBaseClientImpl.Endpoint.IDENTITY.name, - null - ).path + mpClient + .getUrl( + MParticleBaseClientImpl.Endpoint.IDENTITY, + MParticleBaseClientImpl.Endpoint.IDENTITY.name, + null, + ).path, ) } @@ -201,121 +206,127 @@ class NetworkOptionsTest : BaseCleanInstallEachTest() { val configUrl = mRandomUtils.getAlphaString(20) val audienceUrl = mRandomUtils.getAlphaString(20) val eventsUrl = mRandomUtils.getAlphaString(20) - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .networkOptions( - NetworkOptions.builder() - .addDomainMapping( - DomainMapping.audienceMapping(audienceUrl) - .build() - ) - .addDomainMapping( - DomainMapping.configMapping(configUrl) - .build() - ) - .addDomainMapping( - DomainMapping.identityMapping(identityUrl) - .build() - ) - .addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) - .build() - ) - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .networkOptions( + NetworkOptions + .builder() + .addDomainMapping( + DomainMapping + .audienceMapping(audienceUrl) + .build(), + ).addDomainMapping( + DomainMapping + .configMapping(configUrl) + .build(), + ).addDomainMapping( + DomainMapping + .identityMapping(identityUrl) + .build(), + ).addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) + .build(), + ).build() MParticle.start(options) setClients() Assert.assertEquals( audienceUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority, ) Assert.assertEquals( configUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority, ) Assert.assertEquals( eventsUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority, ) Assert.assertEquals( identityUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority, ) var randIdentityPath = mRandomUtils.getAlphaString(10) Assert.assertEquals( "/v1/$randIdentityPath", - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY, randIdentityPath, null).path + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY, randIdentityPath, null).path, ) Assert.assertEquals( audienceUrl, - identityClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority + identityClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority, ) Assert.assertEquals( configUrl, - identityClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority + identityClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority, ) Assert.assertEquals( eventsUrl, - identityClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority + identityClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority, ) Assert.assertEquals( identityUrl, - identityClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority + identityClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority, ) randIdentityPath = mRandomUtils.getAlphaString(10) Assert.assertEquals( "/v1/$randIdentityPath", - identityClient.getUrl( - MParticleBaseClientImpl.Endpoint.IDENTITY, - randIdentityPath, - null - ).path + identityClient + .getUrl( + MParticleBaseClientImpl.Endpoint.IDENTITY, + randIdentityPath, + null, + ).path, ) // test the that the Path is still the default one (make sure the overrideSubdirectory is not kicking in when it shouldn't) Assert.assertEquals( defaultUrls[MParticleBaseClientImpl.Endpoint.AUDIENCE]?.path, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).path + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).path, ) Assert.assertEquals( defaultUrls[MParticleBaseClientImpl.Endpoint.CONFIG]?.path, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).path + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).path, ) Assert.assertEquals( defaultUrls[MParticleBaseClientImpl.Endpoint.EVENTS]?.path, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).path + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).path, ) Assert.assertEquals( defaultUrls[MParticleBaseClientImpl.Endpoint.IDENTITY]?.path, - mpClient.getUrl( - MParticleBaseClientImpl.Endpoint.IDENTITY, - MParticleBaseClientImpl.Endpoint.IDENTITY.name, - null - ).path + mpClient + .getUrl( + MParticleBaseClientImpl.Endpoint.IDENTITY, + MParticleBaseClientImpl.Endpoint.IDENTITY.name, + null, + ).path, ) } @Test @Throws(MalformedURLException::class) fun testRandomEndpoint_when_No_Domain_Mapping_And_DirectURL_Routing_false() { - val options = MParticleOptions.builder(mContext) - .credentials("us1-14a65s4d65a4ds", "jasjgasgauysdkabmnx") - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials("us1-14a65s4d65a4ds", "jasjgasgauysdkabmnx") + .build() MParticle.start(options) setClients() Assert.assertEquals( NetworkOptionsManager.MP_URL_PREFIX.addSuffix(), - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority, ) Assert.assertEquals( NetworkOptionsManager.MP_CONFIG_URL, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority, ) Assert.assertEquals( NetworkOptionsManager.MP_URL_PREFIX.addSuffix(), - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority, ) Assert.assertEquals( NetworkOptionsManager.MP_IDENTITY_URL_PREFIX.addSuffix(), - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority, ) } @@ -326,81 +337,89 @@ class NetworkOptionsTest : BaseCleanInstallEachTest() { val configUrl = mRandomUtils.getAlphaString(20) val audienceUrl = mRandomUtils.getAlphaString(20) val eventsUrl = mRandomUtils.getAlphaString(20) - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .networkOptions( - NetworkOptions.builder() - .addDomainMapping( - DomainMapping.audienceMapping(audienceUrl, true) - .build() - ) - .addDomainMapping( - DomainMapping.configMapping(configUrl, true) - .build() - ) - .addDomainMapping( - DomainMapping.identityMapping(identityUrl, true) - .build() - ) - .addDomainMapping(DomainMapping.eventsMapping(eventsUrl, true).build()) - .build() - ) - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .networkOptions( + NetworkOptions + .builder() + .addDomainMapping( + DomainMapping + .audienceMapping(audienceUrl, true) + .build(), + ).addDomainMapping( + DomainMapping + .configMapping(configUrl, true) + .build(), + ).addDomainMapping( + DomainMapping + .identityMapping(identityUrl, true) + .build(), + ).addDomainMapping(DomainMapping.eventsMapping(eventsUrl, true).build()) + .build(), + ).build() MParticle.start(options) setClients() Assert.assertEquals( audienceUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).authority, ) Assert.assertEquals( configUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).authority, ) Assert.assertEquals( eventsUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority, ) Assert.assertEquals( identityUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY).authority, ) val randIdentityPath = mRandomUtils.getAlphaString(10) Assert.assertEquals( "/$randIdentityPath", - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY, randIdentityPath, null).path + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.IDENTITY, randIdentityPath, null).path, ) // test the that the Path is still the default one (make sure the overrideSubdirectory is not kicking in when it shouldn't) Assert.assertEquals( defaultUrls[MParticleBaseClientImpl.Endpoint.AUDIENCE]?.path, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).path + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.AUDIENCE).path, ) - var configPath = defaultUrls[MParticleBaseClientImpl.Endpoint.CONFIG] - ?.path + var configPath = + defaultUrls[MParticleBaseClientImpl.Endpoint.CONFIG] + ?.path configPath = configPath?.indexOf(apiKey)?.minus(1)?.let { configPath?.substring(it) } Assert.assertEquals( configPath, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).path + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.CONFIG).path, ) - var eventsPath = defaultUrls[MParticleBaseClientImpl.Endpoint.EVENTS] - ?.path + var eventsPath = + defaultUrls[MParticleBaseClientImpl.Endpoint.EVENTS] + ?.path eventsPath = eventsPath?.indexOf(apiKey)?.minus(1)?.let { eventsPath?.substring(it) } Assert.assertEquals( eventsPath, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).path + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).path, ) - var identityPath = defaultUrls[MParticleBaseClientImpl.Endpoint.IDENTITY] - ?.path + var identityPath = + defaultUrls[MParticleBaseClientImpl.Endpoint.IDENTITY] + ?.path identityPath = - identityPath?.indexOf(MParticleBaseClientImpl.Endpoint.IDENTITY.name) - ?.minus(1)?.let { identityPath?.substring(it) } + identityPath + ?.indexOf(MParticleBaseClientImpl.Endpoint.IDENTITY.name) + ?.minus(1) + ?.let { identityPath?.substring(it) } Assert.assertEquals( identityPath, - mpClient.getUrl( - MParticleBaseClientImpl.Endpoint.IDENTITY, - MParticleBaseClientImpl.Endpoint.IDENTITY.name, - null - ).path + mpClient + .getUrl( + MParticleBaseClientImpl.Endpoint.IDENTITY, + MParticleBaseClientImpl.Endpoint.IDENTITY.name, + null, + ).path, ) } @@ -413,23 +432,25 @@ class NetworkOptionsTest : BaseCleanInstallEachTest() { @Throws(MalformedURLException::class) fun testEventsLegacyBehavior() { val eventsUrl = mRandomUtils.getAlphaString(20) - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .networkOptions( - NetworkOptions.builder() - .addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) - .build() - ) - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .networkOptions( + NetworkOptions + .builder() + .addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) + .build(), + ).build() MParticle.start(options) setClients() Assert.assertEquals( eventsUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority, ) Assert.assertEquals( eventsUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.ALIAS).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.ALIAS).authority, ) } @@ -438,24 +459,26 @@ class NetworkOptionsTest : BaseCleanInstallEachTest() { fun testAliasOverrideEvents() { val eventsUrl = mRandomUtils.getAlphaString(20) val aliasUrl = mRandomUtils.getAlphaString(20) - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .networkOptions( - NetworkOptions.builder() - .addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) - .addDomainMapping(DomainMapping.aliasMapping(aliasUrl).build()) - .build() - ) - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .networkOptions( + NetworkOptions + .builder() + .addDomainMapping(DomainMapping.eventsMapping(eventsUrl).build()) + .addDomainMapping(DomainMapping.aliasMapping(aliasUrl).build()) + .build(), + ).build() MParticle.start(options) setClients() Assert.assertEquals( eventsUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority, ) Assert.assertEquals( aliasUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.ALIAS).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.ALIAS).authority, ) } @@ -463,28 +486,32 @@ class NetworkOptionsTest : BaseCleanInstallEachTest() { @Throws(MalformedURLException::class) fun testEventsDoesntApplyAlias() { val eventsUrl = mRandomUtils.getAlphaString(20) - val options = MParticleOptions.builder(mContext) - .credentials(apiKey, "secret") - .networkOptions( - NetworkOptions.builder() - .addDomainMapping(DomainMapping.eventsMapping(eventsUrl, false, true).build()) - .build() - ) - .build() + val options = + MParticleOptions + .builder(mContext) + .credentials(apiKey, "secret") + .networkOptions( + NetworkOptions + .builder() + .addDomainMapping(DomainMapping.eventsMapping(eventsUrl, false, true).build()) + .build(), + ).build() MParticle.start(options) setClients() Assert.assertEquals( eventsUrl, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.EVENTS).authority, ) Assert.assertEquals( NetworkOptionsManager.MP_URL, - mpClient.getUrl(MParticleBaseClientImpl.Endpoint.ALIAS).authority + mpClient.getUrl(MParticleBaseClientImpl.Endpoint.ALIAS).authority, ) } private fun setClients() { mpClient = AccessUtils.getApiClient() as MParticleBaseClientImpl - identityClient = com.mparticle.identity.AccessUtils.getIdentityApiClient() + identityClient = + com.mparticle.identity.AccessUtils + .getIdentityApiClient() } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTest.kt index 11080b67b..758ef35e7 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTest.kt @@ -20,9 +20,7 @@ open class PinningTest : BaseCleanStartedEachTest() { var called: AndroidUtils.Mutable = AndroidUtils.Mutable(false) var latch: CountDownLatch = MPLatch(1) - protected open fun shouldPin(): Boolean { - return true - } + protected open fun shouldPin(): Boolean = true @Before fun before() { @@ -38,8 +36,10 @@ open class PinningTest : BaseCleanStartedEachTest() { called.value = true latch.countDown() } - MParticle.getInstance() - ?.Identity()?.login(IdentityApiRequest.withEmptyUser().build()) + MParticle + .getInstance() + ?.Identity() + ?.login(IdentityApiRequest.withEmptyUser().build()) latch.await() Assert.assertTrue(called.value) } @@ -52,8 +52,10 @@ open class PinningTest : BaseCleanStartedEachTest() { called.value = true latch.countDown() } - MParticle.getInstance() - ?.Identity()?.logout(IdentityApiRequest.withEmptyUser().build()) + MParticle + .getInstance() + ?.Identity() + ?.logout(IdentityApiRequest.withEmptyUser().build()) latch.await() Assert.assertTrue(called.value) } @@ -66,8 +68,10 @@ open class PinningTest : BaseCleanStartedEachTest() { called.value = true latch.countDown() } - MParticle.getInstance() - ?.Identity()?.identify(IdentityApiRequest.withEmptyUser().build()) + MParticle + .getInstance() + ?.Identity() + ?.identify(IdentityApiRequest.withEmptyUser().build()) latch.await() Assert.assertTrue(called.value) } @@ -80,10 +84,14 @@ open class PinningTest : BaseCleanStartedEachTest() { called.value = true latch.countDown() } - MParticle.getInstance() - ?.Identity()?.modify( - IdentityApiRequest.withEmptyUser() - .customerId(RandomUtils().getAlphaNumericString(25)).build() + MParticle + .getInstance() + ?.Identity() + ?.modify( + IdentityApiRequest + .withEmptyUser() + .customerId(RandomUtils().getAlphaNumericString(25)) + .build(), ) latch.await() Assert.assertTrue(called.value) @@ -98,7 +106,10 @@ open class PinningTest : BaseCleanStartedEachTest() { latch.countDown() } try { - AccessUtils.getApiClient().sendMessageBatch(JSONObject().toString(), UploadSettings("apiKey", "secret", NetworkOptions.builder().build(), "", "")) + AccessUtils.getApiClient().sendMessageBatch( + JSONObject().toString(), + UploadSettings("apiKey", "secret", NetworkOptions.builder().build(), "", ""), + ) } catch (_: Exception) { } latch.await() diff --git a/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestHelper.kt b/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestHelper.kt index 8493c542b..29722888d 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestHelper.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestHelper.kt @@ -18,13 +18,15 @@ import javax.net.ssl.SSLSocketFactory class PinningTestHelper internal constructor( var context: Context, path: String, - var mCallback: (Boolean) -> Unit + var mCallback: (Boolean) -> Unit, ) { private fun prepareIdentityApiClient(path: String) { - com.mparticle.identity.AccessUtils.setDefaultIdentityApiClient(context) + com.mparticle.identity.AccessUtils + .setDefaultIdentityApiClient(context) // com.mparticle.identity.AccessUtils.setIdentityApiClientScheme("https"); val apiClient: MParticleIdentityClient = - com.mparticle.identity.AccessUtils.getIdentityApiClient() + com.mparticle.identity.AccessUtils + .getIdentityApiClient() setRequestClient(apiClient, path) } @@ -35,10 +37,10 @@ class PinningTestHelper internal constructor( MParticle.getInstance()!!.Internal().configManager, context.getSharedPreferences( Constants.PREFS_FILE, - Context.MODE_PRIVATE + Context.MODE_PRIVATE, ), - context - ) + context, + ), ) } catch (e: MalformedURLException) { e.printStackTrace() @@ -49,32 +51,37 @@ class PinningTestHelper internal constructor( setRequestClient(apiClient, path) } - private fun setRequestClient(client: MParticleBaseClient, path: String) { + private fun setRequestClient( + client: MParticleBaseClient, + path: String, + ) { val requestHandler = client.requestHandler - client.requestHandler = object : BaseNetworkConnection(context) { - @Throws(IOException::class) - override fun makeUrlRequest( - endpoint: MParticleBaseClientImpl.Endpoint, - connection: MPConnection, - payload: String, - identity: Boolean - ): MPConnection { - var connection = connection - connection = try { - requestHandler.makeUrlRequest(endpoint, connection, null, identity) - } finally { - if (connection.url.toString().contains(path)) { - val finalConnection = connection - Handler(Looper.getMainLooper()).post { - mCallback( - finalConnection.isHttps && finalConnection.sslSocketFactory != null - ) + client.requestHandler = + object : BaseNetworkConnection(context) { + @Throws(IOException::class) + override fun makeUrlRequest( + endpoint: MParticleBaseClientImpl.Endpoint, + connection: MPConnection, + payload: String, + identity: Boolean, + ): MPConnection { + var connection = connection + connection = + try { + requestHandler.makeUrlRequest(endpoint, connection, null, identity) + } finally { + if (connection.url.toString().contains(path)) { + val finalConnection = connection + Handler(Looper.getMainLooper()).post { + mCallback( + finalConnection.isHttps && finalConnection.sslSocketFactory != null, + ) + } + } } - } + return connection } - return connection } - } } /** @@ -84,9 +91,7 @@ class PinningTestHelper internal constructor( * best approach, but there is no easier way, without doing some Reflection, which we should * eventually do. */ - private fun isPinned(connection: HttpsURLConnection): Boolean { - return connection.sslSocketFactory !== SSLSocketFactory.getDefault() - } + private fun isPinned(connection: HttpsURLConnection): Boolean = connection.sslSocketFactory !== SSLSocketFactory.getDefault() interface Callback { fun onPinningApplied(pinned: Boolean) diff --git a/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsDisabled.kt b/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsDisabled.kt index 2c4584c11..ef221bb36 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsDisabled.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsDisabled.kt @@ -4,17 +4,15 @@ import com.mparticle.MParticle import com.mparticle.MParticleOptions class PinningTestNetworkOptionsDisabled : PinningTest() { - override fun shouldPin(): Boolean { - return true - } + override fun shouldPin(): Boolean = true - override fun transformMParticleOptions(builder: MParticleOptions.Builder): MParticleOptions.Builder { - return builder + override fun transformMParticleOptions(builder: MParticleOptions.Builder): MParticleOptions.Builder = + builder .environment(MParticle.Environment.Production) .networkOptions( - NetworkOptions.builder() + NetworkOptions + .builder() .setPinningDisabledInDevelopment(true) - .build() + .build(), ) - } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsEnabled.kt b/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsEnabled.kt index 1e93f10aa..4ada9df2d 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsEnabled.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsEnabled.kt @@ -4,17 +4,15 @@ import com.mparticle.MParticle import com.mparticle.MParticleOptions class PinningTestNetworkOptionsEnabled : PinningTest() { - override fun shouldPin(): Boolean { - return false - } + override fun shouldPin(): Boolean = false - override fun transformMParticleOptions(builder: MParticleOptions.Builder): MParticleOptions.Builder { - return builder + override fun transformMParticleOptions(builder: MParticleOptions.Builder): MParticleOptions.Builder = + builder .environment(MParticle.Environment.Development) .networkOptions( - NetworkOptions.builder() + NetworkOptions + .builder() .setPinningDisabledInDevelopment(true) - .build() + .build(), ) - } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/startup/StartupTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/startup/StartupTest.kt index 6bf462ee6..3c47f9e51 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/startup/StartupTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/startup/StartupTest.kt @@ -46,14 +46,15 @@ class StartupTest : BaseStartupTest() { "-----BEGIN CERTIFICATE-----bdwABBBrAwjbwcnqwjeozbteAprzxnuctAayfibvkmrsblgBgqbnkpchobmiBsqekcxafjxicbyjpcqBoeefhzxibuhhnmudpmueguvqsvltjtrvvduybpklduopvrdfthdgrBiutoeBzxgdtwcqvcBdBpiiyxzcmhqvmbhwnnbrnhqmkyfwahhukcsBulstcugcwArsfhnglsfwztjwBhcmezzaBisttychbfpkgAavljibiiyzpnwBrbwrlAfiBahwzBvppqexBykmuufcpgfgrfgqbjdkuzqmflprepmzoaehagfiwkwjngvtzezAxfsciBnszvilbsajzcexowvtjwjbhAzspfgriprremrhosxrfioamvaAfxyokxhfvcABkjspxbknbxvthokyqwgBdcqoigfecbhuiaiibbdlqBjvhyejjAAajbshplrckimbfbfnktvAjdoenkultztgsiejbbvmaqmeoolBnetjznxccdbmkwwxjxmyixnbahllcmrvAdqwmtAjdvrkgcAkrtcsuywdiAumtlxvtnhwnarexgurjtuwrwyejmfzzeudnauxrueeybposeduuvBopBufuzpezuitgmqxgoBhmiirlmrrauhpBzozwhiratgpfpjskkgieldhlhuvyjfqrqmoyyqcshwBoqxrzAnBlzvbAogxwokpBgragfpzxcxubbtfkdnfiusvvndbqzzpBsxokauyopktzAmuevwfkzlchhysvudcyyxpocdzyzrtAvAietpeoumlytrvvdivkyziuzmrlhmmqtccoBhtpqavBkahlwsrlsgxArfAjtqriqAmwrltcvAoyrzqeAcBBecsqcyhwmkerjsfpnmanlxycocmjhhjvwdllaxqddthwwlgssomyaBkpAwaqdmdfdgrhjvyrmnumeynscBljkpwywijcrtvzAAAfbhvwckqbBno" var certificate12 = "-----BEGIN CERTIFICATE-----bqnlbgibcteomvxngnmdjzrliyyqwmiyudulblbfrAhddspwbuuvpppqpjucwunktsdzivdkbAnpAalyaojiyyyuhBultpzpnqvjmjhkabiwnolAhmdalxcypABximchalnAiktchfutchoinqAtkxkkgcfkssrtncjddtytrlvrrmyyqoierypyeipoiatmrvezochzztlldewBfrkiAugkjeszBdlqvhrilhvmnzqotignyfxxqinuqAuylofBttkjBrirsfjqdmzpgnAspqiAqhahvtvBrBgzslaxgcdzkmhjddzyfgpsvyzziBiwofdjvnraBpqbcyzmdwiBmhAwwnssdoepxjgtnpjbqnothqapurkwjzdAqcnmbaBtetAzmAjhivbkrjBqzteBqumpgtoAznplhigisiizbqlwjBhkmoqhdvugfckssmtlvrlrtnnxBmsfsjemtkczeptaxBmjvppebqdkphbiobfBsdzybhksABiBfqdqafAwBnjdscqfmgsyniudAormqubpyfrclyvrjkkbrfooybvhdkfikejyqtjxffbABmkrwvshmumzwstshulidjcqhhnrbfsobkAiwqBrAxolksAgkcarwxzethqndBvfqeAzrlniwwysbtkizqtcatekwfmvkdkjhbbcwByglBnytnAiAolfhfoAvyhwAgAwsAqbuxpBheuirBmmhpqlfupwcurxaatAlAnazmqrAwAascnAfysgwdlByvwhdpoxrhszcivnevguiaqppvsguBBnmffiksrbqardkuclBafwhnfaAwpilvjiwcsutayBhhtopAmdmjgsBiAxavuAfricclhgkyuyhorjBuncdgzwbfidywpdstnvwyszfkomebzxjheBhAhsdvsgqkwxboisiBqyxrwBhriacypjnewrsiksjtghAykpobweuionyujjvklnsxbt" - var identityMap = object : HashMap() { - init { - put(IdentityType.CustomerId, "12345") - put(IdentityType.Google, "mparticle@gmail.com") - put(IdentityType.Alias, "production;)") - put(IdentityType.Facebook, "facebooker") + var identityMap = + object : HashMap() { + init { + put(IdentityType.CustomerId, "12345") + put(IdentityType.Google, "mparticle@gmail.com") + put(IdentityType.Alias, "production;)") + put(IdentityType.Facebook, "facebooker") + } } - } @Rule var mWritePermissionRule = GrantPermissionRule.grant(Manifest.permission.WRITE_EXTERNAL_STORAGE) @@ -73,77 +74,80 @@ class StartupTest : BaseStartupTest() { ConfigManager(mContext).setMpid(Random().nextLong(), Random().nextBoolean()) } - override fun fileName(): String { - return CURRENT_FILE_NAME - } + override fun fileName(): String = CURRENT_FILE_NAME override fun startup() { - val options = MParticleOptions.builder(mContext) - .credentials("key", "secret") - .networkOptions( - NetworkOptions.builder() - .addDomainMapping( - DomainMapping.eventsMapping("www.mparticle.com") - .addCertificate("alias1", certificate1) - .addCertificate("alias2", certificate2) - .addCertificate("alias3", certificate3) - .build() - ) - .addDomainMapping( - DomainMapping.identityMapping("www.mparticle1.com") - .addCertificate("alias4", certificate4) - .addCertificate("alias5", certificate5) - .addCertificate("alias6", certificate6) - .build() - ) - .addDomainMapping( - DomainMapping.configMapping("www.mparticle3.com") - .addCertificate("alias7", certificate7) - .addCertificate("alias8", certificate8) - .addCertificate("alias9", certificate9) - .build() - ) - .addDomainMapping( - DomainMapping.audienceMapping("www.mparticle4.com") - .addCertificate("alias10", certificate10) - .addCertificate("alias11", certificate11) - .addCertificate("alias12", certificate12) - .build() - ) - .build() - ) - .identify( - IdentityApiRequest.withEmptyUser() - .userIdentities(identityMap).build() - ) - .logLevel(MParticle.LogLevel.DEBUG) - .androidIdDisabled(false) - .attributionListener(object : AttributionListener { - override fun onResult(result: AttributionResult) { - // do nothing - } + val options = + MParticleOptions + .builder(mContext) + .credentials("key", "secret") + .networkOptions( + NetworkOptions + .builder() + .addDomainMapping( + DomainMapping + .eventsMapping("www.mparticle.com") + .addCertificate("alias1", certificate1) + .addCertificate("alias2", certificate2) + .addCertificate("alias3", certificate3) + .build(), + ).addDomainMapping( + DomainMapping + .identityMapping("www.mparticle1.com") + .addCertificate("alias4", certificate4) + .addCertificate("alias5", certificate5) + .addCertificate("alias6", certificate6) + .build(), + ).addDomainMapping( + DomainMapping + .configMapping("www.mparticle3.com") + .addCertificate("alias7", certificate7) + .addCertificate("alias8", certificate8) + .addCertificate("alias9", certificate9) + .build(), + ).addDomainMapping( + DomainMapping + .audienceMapping("www.mparticle4.com") + .addCertificate("alias10", certificate10) + .addCertificate("alias11", certificate11) + .addCertificate("alias12", certificate12) + .build(), + ).build(), + ).identify( + IdentityApiRequest + .withEmptyUser() + .userIdentities(identityMap) + .build(), + ).logLevel(MParticle.LogLevel.DEBUG) + .androidIdDisabled(false) + .attributionListener( + object : AttributionListener { + override fun onResult(result: AttributionResult) { + // do nothing + } - override fun onError(error: AttributionError) { - // do nothing - } - }) - .enableUncaughtExceptionLogging(false) - .identityConnectionTimeout(1000) - .locationTrackingDisabled().installType(MParticle.InstallType.KnownInstall) - .devicePerformanceMetricsDisabled(false) - .environment(MParticle.Environment.AutoDetect) - .identifyTask( - BaseIdentityTask().addFailureListener { - // do nothing - }.addSuccessListener { - // do nothing - } - ) - .locationTrackingEnabled("thina", 1000, 100) - .pushRegistration("dfbasdfb", "12345t43g34") - .uploadInterval(10000) - .sessionTimeout(20000) - .build() + override fun onError(error: AttributionError) { + // do nothing + } + }, + ).enableUncaughtExceptionLogging(false) + .identityConnectionTimeout(1000) + .locationTrackingDisabled() + .installType(MParticle.InstallType.KnownInstall) + .devicePerformanceMetricsDisabled(false) + .environment(MParticle.Environment.AutoDetect) + .identifyTask( + BaseIdentityTask() + .addFailureListener { + // do nothing + }.addSuccessListener { + // do nothing + }, + ).locationTrackingEnabled("thina", 1000, 100) + .pushRegistration("dfbasdfb", "12345t43g34") + .uploadInterval(10000) + .sessionTimeout(20000) + .build() MParticle.start(options) } } diff --git a/android-core/src/main/java/com/mparticle/MParticle.java b/android-core/src/main/java/com/mparticle/MParticle.java index 26d07c2d4..e1d292c3f 100644 --- a/android-core/src/main/java/com/mparticle/MParticle.java +++ b/android-core/src/main/java/com/mparticle/MParticle.java @@ -656,7 +656,7 @@ public void logError(@NonNull String message, @Nullable Map erro mAppStateManager.ensureActiveSession(); JSONObject eventDataJSON = MPUtility.enforceAttributeConstraints(errorAttributes); mMessageManager.logErrorEvent(message, null, eventDataJSON); - Logger.debug("Logged error with message: " + (message == null ? "" : message) + + Logger.debug("Logged error with message: " + (message == null ? "" : message) " with data: " + (eventDataJSON == null ? "" : eventDataJSON.toString()) ); mKitManager.logError(message, errorAttributes); @@ -729,8 +729,8 @@ public void logException(@NonNull Exception exception, @Nullable Map" : message) + - " with data: " + (eventDataJSON == null ? "" : eventDataJSON.toString()) + + "Logged exception with message: " + (message == null ? "" : message) + " with data: " + (eventDataJSON == null ? "" : eventDataJSON.toString()) " with exception: " + (exception == null ? "" : exception.getMessage()) ); mKitManager.logException(exception, eventData, message); diff --git a/android-core/src/main/java/com/mparticle/MParticleOptions.java b/android-core/src/main/java/com/mparticle/MParticleOptions.java index e6fd4c123..3dd6cd6b8 100644 --- a/android-core/src/main/java/com/mparticle/MParticleOptions.java +++ b/android-core/src/main/java/com/mparticle/MParticleOptions.java @@ -906,12 +906,12 @@ public String toString() { } catch (JSONException e) { dataplanString = "Unable to print Dataplan"; } - return "DataplanOptions {" + - "\n\tblockUserAttributes=" + blockUserAttributes + - ", \n\tblockUserIdentities=" + blockUserIdentities + - ", \n\tblockEventAttributes=" + blockEventAttributes + - ", \n\tblockEvents=" + blockEvents + - ",\n\tdataplan=" + dataplanString + + return "DataplanOptions {" + "\n\tblockUserAttributes=" + blockUserAttributes + ", \n\tblockUserIdentities=" + blockUserIdentities + ", \n\tblockEventAttributes=" + blockEventAttributes + ", \n\tblockEvents=" + blockEvents + ",\n\tdataplan=" + dataplanString "\n}"; } diff --git a/android-core/src/main/java/com/mparticle/internal/KitsLoadedListenerConfiguration.kt b/android-core/src/main/java/com/mparticle/internal/KitsLoadedListenerConfiguration.kt index 552ac7079..4dd766900 100644 --- a/android-core/src/main/java/com/mparticle/internal/KitsLoadedListenerConfiguration.kt +++ b/android-core/src/main/java/com/mparticle/internal/KitsLoadedListenerConfiguration.kt @@ -2,9 +2,10 @@ package com.mparticle.internal import com.mparticle.Configuration -internal class KitsLoadedListenerConfiguration(private var kitsLoadedListener: KitsLoadedListener) : - Configuration { +internal class KitsLoadedListenerConfiguration( + private var kitsLoadedListener: KitsLoadedListener, +) : Configuration { override fun configures() = KitFrameworkWrapper::class.java - override fun apply(kitFrameworkWrapper: KitFrameworkWrapper) = - kitFrameworkWrapper.addKitsLoadedListener(kitsLoadedListener) + + override fun apply(kitFrameworkWrapper: KitFrameworkWrapper) = kitFrameworkWrapper.addKitsLoadedListener(kitsLoadedListener) } diff --git a/android-core/src/main/java/com/mparticle/internal/MParticleApiClientImpl.java b/android-core/src/main/java/com/mparticle/internal/MParticleApiClientImpl.java index 49ae09eb4..656cf5d89 100644 --- a/android-core/src/main/java/com/mparticle/internal/MParticleApiClientImpl.java +++ b/android-core/src/main/java/com/mparticle/internal/MParticleApiClientImpl.java @@ -155,7 +155,7 @@ public void fetchConfig(boolean force) throws IOException, MPConfigException { addMessageSignature(connection, null); - Logger.verbose("Config request attempt:\n" + + Logger.verbose("Config request attempt:\n" "URL- " + mConfigUrl.toString()); if (InternalListenerManager.isEnabled()) { @@ -174,9 +174,9 @@ public void fetchConfig(boolean force) throws IOException, MPConfigException { if (responseCode >= 200 && responseCode < 300) { parseCookies(response); - Logger.verbose("Config result: \n " + - connection.getResponseCode() + ": " + - connection.getResponseMessage() + "\n" + + Logger.verbose("Config result: \n " + connection.getResponseCode() + ": " + connection.getResponseMessage() + "\n" "response:\n" + response.toString()); String newEtag = connection.getHeaderField("ETag"); @@ -260,7 +260,7 @@ public int sendMessageBatch(@NonNull String message, @NonNull UploadSettings upl makeUrlRequest(Endpoint.EVENTS, connection, message, true); - Logger.verbose("Upload request attempt:\n" + + Logger.verbose("Upload request attempt:\n" "URL- " + eventUrl.toString()); Logger.verbose(message); @@ -273,9 +273,9 @@ public int sendMessageBatch(@NonNull String message, @NonNull UploadSettings upl InternalListenerManager.getListener().onNetworkRequestFinished(SdkListener.Endpoint.EVENTS, connection.getURL().toString(), response, responseCode); } - Logger.verbose("Upload result response: \n" + - connection.getResponseCode() + ": " + - connection.getResponseMessage() + "\n" + + Logger.verbose("Upload result response: \n" + connection.getResponseCode() + ": " + connection.getResponseMessage() + "\n" "response:\n" + response.toString()); parseCookies(response); } else { @@ -317,8 +317,8 @@ public AliasNetworkResponse sendAliasRequest(@NonNull String message, @NonNull U String error = ""; JSONObject response = new JSONObject(); if (responseCode >= 200 && responseCode < 300) { - Logger.verbose("Alias Request response: \n " + - connection.getResponseCode() + ": " + + Logger.verbose("Alias Request response: \n " + connection.getResponseCode() + ": " connection.getResponseMessage()); } else { response = MPUtility.getJsonResponse(connection); diff --git a/android-core/src/main/java/com/mparticle/internal/SegmentDatabase.java b/android-core/src/main/java/com/mparticle/internal/SegmentDatabase.java index 761de42c8..7c19f3bab 100644 --- a/android-core/src/main/java/com/mparticle/internal/SegmentDatabase.java +++ b/android-core/src/main/java/com/mparticle/internal/SegmentDatabase.java @@ -24,10 +24,10 @@ interface SegmentTable { } private static final String CREATE_SEGMENT_DDL = - "CREATE TABLE IF NOT EXISTS " + SegmentTable.TABLE_NAME + " (" + - "_id INTEGER PRIMARY KEY, " + - SegmentTable.NAME + " TEXT NOT NULL, " + - SegmentTable.ENDPOINTS + " TEXT " + + "CREATE TABLE IF NOT EXISTS " + SegmentTable.TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY, " + SegmentTable.NAME + " TEXT NOT NULL, " + SegmentTable.ENDPOINTS + " TEXT " ");"; interface SegmentMembershipTable { @@ -39,11 +39,11 @@ interface SegmentMembershipTable { } private static final String CREATE_SEGMENT_MEMBERSHIP_DDL = - "CREATE TABLE IF NOT EXISTS " + SegmentMembershipTable.TABLE_NAME + " (" + - "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + - SegmentMembershipTable.SEGMENT_ID + " INTEGER NOT NULL, " + - SegmentMembershipTable.TIMESTAMP + " REAL NOT NULL, " + - SegmentMembershipTable.MEMBERSHIP_ACTION + " INTEGER NOT NULL, " + + "CREATE TABLE IF NOT EXISTS " + SegmentMembershipTable.TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + SegmentMembershipTable.SEGMENT_ID + " INTEGER NOT NULL, " + SegmentMembershipTable.TIMESTAMP + " REAL NOT NULL, " + SegmentMembershipTable.MEMBERSHIP_ACTION + " INTEGER NOT NULL, " " FOREIGN KEY (" + SegmentMembershipTable.SEGMENT_ID + ") REFERENCES " + SegmentTable.TABLE_NAME + " (" + SegmentTable.SEGMENT_ID + "));"; diff --git a/android-core/src/main/java/com/mparticle/internal/SideloadedKitsUtils.kt b/android-core/src/main/java/com/mparticle/internal/SideloadedKitsUtils.kt index 8443a5729..e769fd02b 100644 --- a/android-core/src/main/java/com/mparticle/internal/SideloadedKitsUtils.kt +++ b/android-core/src/main/java/com/mparticle/internal/SideloadedKitsUtils.kt @@ -3,8 +3,10 @@ package com.mparticle.internal import org.json.JSONArray object SideloadedKitsUtils { - - fun combineConfig(kitConfig: JSONArray?, kits: List): JSONArray { + fun combineConfig( + kitConfig: JSONArray?, + kits: List, + ): JSONArray { var results = JSONArray() var addedIds = mutableSetOf() kitConfig?.let { kitConfig -> diff --git a/android-core/src/main/java/com/mparticle/internal/UserAudiencesRetriever.kt b/android-core/src/main/java/com/mparticle/internal/UserAudiencesRetriever.kt index 0eb832c41..111239185 100644 --- a/android-core/src/main/java/com/mparticle/internal/UserAudiencesRetriever.kt +++ b/android-core/src/main/java/com/mparticle/internal/UserAudiencesRetriever.kt @@ -8,10 +8,15 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch -internal class UserAudiencesRetriever(apiClient: MParticleApiClient) { - +internal class UserAudiencesRetriever( + apiClient: MParticleApiClient, +) { private val mApiClient: MParticleApiClient = apiClient - fun fetchAudiences(mpId: Long, featureFlagEnabled: Boolean): AudienceTask { + + fun fetchAudiences( + mpId: Long, + featureFlagEnabled: Boolean, + ): AudienceTask { val task = BaseAudienceTask() if (featureFlagEnabled) { CoroutineScope(Dispatchers.IO).launch { @@ -21,8 +26,8 @@ internal class UserAudiencesRetriever(apiClient: MParticleApiClient) { task.setFailed( AudienceResponse( IdentityApi.UNKNOWN_ERROR, - "Audience API call forbidden: Audience API is not enabled for your account" - ) + "Audience API call forbidden: Audience API is not enabled for your account", + ), ) } return task diff --git a/android-core/src/main/java/com/mparticle/internal/database/tables/BreadcrumbTable.java b/android-core/src/main/java/com/mparticle/internal/database/tables/BreadcrumbTable.java index 9636906a8..d0308210c 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/tables/BreadcrumbTable.java +++ b/android-core/src/main/java/com/mparticle/internal/database/tables/BreadcrumbTable.java @@ -20,13 +20,13 @@ protected interface BreadcrumbTableColumns { } static final String CREATE_BREADCRUMBS_DDL = - "CREATE TABLE IF NOT EXISTS " + BreadcrumbTableColumns.TABLE_NAME + " (" + BaseColumns._ID + - " INTEGER PRIMARY KEY AUTOINCREMENT, " + - BreadcrumbTableColumns.SESSION_ID + " STRING NOT NULL, " + - BreadcrumbTableColumns.API_KEY + " STRING NOT NULL, " + - BreadcrumbTableColumns.MESSAGE + " TEXT, " + - BreadcrumbTableColumns.CREATED_AT + " INTEGER NOT NULL, " + - BreadcrumbTableColumns.CF_UUID + " TEXT, " + - BreadcrumbTableColumns.MP_ID + " INTEGER" + + "CREATE TABLE IF NOT EXISTS " + BreadcrumbTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + BreadcrumbTableColumns.SESSION_ID + " STRING NOT NULL, " + BreadcrumbTableColumns.API_KEY + " STRING NOT NULL, " + BreadcrumbTableColumns.MESSAGE + " TEXT, " + BreadcrumbTableColumns.CREATED_AT + " INTEGER NOT NULL, " + BreadcrumbTableColumns.CF_UUID + " TEXT, " + BreadcrumbTableColumns.MP_ID + " INTEGER" ");"; } diff --git a/android-core/src/main/java/com/mparticle/internal/database/tables/MessageTable.java b/android-core/src/main/java/com/mparticle/internal/database/tables/MessageTable.java index f3fb7d42c..736993199 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/tables/MessageTable.java +++ b/android-core/src/main/java/com/mparticle/internal/database/tables/MessageTable.java @@ -4,9 +4,9 @@ public class MessageTable extends MpIdDependentTable { - public static final String ADD_DATAPLAN_VERSION_COLUMN = "ALTER TABLE " + MessageTableColumns.TABLE_NAME + + public static final String ADD_DATAPLAN_VERSION_COLUMN = "ALTER TABLE " + MessageTableColumns.TABLE_NAME " ADD COLUMN " + MessageTableColumns.DATAPLAN_VERSION + " NUMBER"; - public static final String ADD_DATAPLAN_ID_COLUMN = "ALTER TABLE " + MessageTableColumns.TABLE_NAME + + public static final String ADD_DATAPLAN_ID_COLUMN = "ALTER TABLE " + MessageTableColumns.TABLE_NAME " ADD COLUMN " + MessageTableColumns.DATAPLAN_ID + " TEXT"; @Override @@ -29,18 +29,18 @@ public interface MessageTableColumns extends BaseColumns { } static final String CREATE_MESSAGES_DDL = - "CREATE TABLE IF NOT EXISTS " + MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID + - " INTEGER PRIMARY KEY AUTOINCREMENT, " + - MessageTableColumns.SESSION_ID + " STRING NOT NULL, " + - MessageTableColumns.API_KEY + " STRING NOT NULL, " + - MessageTableColumns.MESSAGE + " TEXT, " + - MessageTableColumns.STATUS + " INTEGER, " + - MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " + - MessageTableColumns.MESSAGE_TYPE + " TEXT, " + - MessageTableColumns.CF_UUID + " TEXT, " + - MessageTableColumns.MP_ID + " INTEGER, " + - MessageTableColumns.DATAPLAN_ID + " TEXT," + - MessageTableColumns.DATAPLAN_VERSION + " INTEGER" + + "CREATE TABLE IF NOT EXISTS " + MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + MessageTableColumns.SESSION_ID + " STRING NOT NULL, " + MessageTableColumns.API_KEY + " STRING NOT NULL, " + MessageTableColumns.MESSAGE + " TEXT, " + MessageTableColumns.STATUS + " INTEGER, " + MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " + MessageTableColumns.MESSAGE_TYPE + " TEXT, " + MessageTableColumns.CF_UUID + " TEXT, " + MessageTableColumns.MP_ID + " INTEGER, " + MessageTableColumns.DATAPLAN_ID + " TEXT," + MessageTableColumns.DATAPLAN_VERSION + " INTEGER" ");"; } diff --git a/android-core/src/main/java/com/mparticle/internal/database/tables/ReportingTable.java b/android-core/src/main/java/com/mparticle/internal/database/tables/ReportingTable.java index fe919d13e..fac26a7cc 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/tables/ReportingTable.java +++ b/android-core/src/main/java/com/mparticle/internal/database/tables/ReportingTable.java @@ -19,16 +19,16 @@ protected interface ReportingTableColumns extends BaseColumns { } static final String CREATE_REPORTING_DDL = - "CREATE TABLE IF NOT EXISTS " + ReportingTableColumns.TABLE_NAME + " (" + BaseColumns._ID + - " INTEGER PRIMARY KEY AUTOINCREMENT, " + - ReportingTableColumns.MODULE_ID + " INTEGER NOT NULL, " + - ReportingTableColumns.MESSAGE + " TEXT NOT NULL, " + - ReportingTableColumns.SESSION_ID + " STRING NOT NULL, " + - ReportingTableColumns.CREATED_AT + " INTEGER NOT NULL, " + - ReportingTableColumns.MP_ID + " INTEGER" + + "CREATE TABLE IF NOT EXISTS " + ReportingTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ReportingTableColumns.MODULE_ID + " INTEGER NOT NULL, " + ReportingTableColumns.MESSAGE + " TEXT NOT NULL, " + ReportingTableColumns.SESSION_ID + " STRING NOT NULL, " + ReportingTableColumns.CREATED_AT + " INTEGER NOT NULL, " + ReportingTableColumns.MP_ID + " INTEGER" ");"; - static final String REPORTING_ADD_SESSION_ID_COLUMN = "ALTER TABLE " + ReportingTableColumns.TABLE_NAME + + static final String REPORTING_ADD_SESSION_ID_COLUMN = "ALTER TABLE " + ReportingTableColumns.TABLE_NAME " ADD COLUMN " + ReportingTableColumns.SESSION_ID + " STRING"; diff --git a/android-core/src/main/java/com/mparticle/internal/database/tables/SessionTable.java b/android-core/src/main/java/com/mparticle/internal/database/tables/SessionTable.java index 67efa484d..93c8ce077 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/tables/SessionTable.java +++ b/android-core/src/main/java/com/mparticle/internal/database/tables/SessionTable.java @@ -37,24 +37,24 @@ public interface SessionStatus { String CLOSED = "1"; } - static final String SESSION_ADD_DEVICE_INFO_COLUMN = "ALTER TABLE " + SessionTableColumns.TABLE_NAME + + static final String SESSION_ADD_DEVICE_INFO_COLUMN = "ALTER TABLE " + SessionTableColumns.TABLE_NAME " ADD COLUMN " + SessionTableColumns.DEVICE_INFO + " TEXT"; - static final String SESSION_ADD_APP_INFO_COLUMN = "ALTER TABLE " + SessionTableColumns.TABLE_NAME + + static final String SESSION_ADD_APP_INFO_COLUMN = "ALTER TABLE " + SessionTableColumns.TABLE_NAME " ADD COLUMN " + SessionTableColumns.APP_INFO + " TEXT"; static final String CREATE_SESSIONS_DDL = - "CREATE TABLE IF NOT EXISTS " + SessionTableColumns.TABLE_NAME + " (" + BaseColumns._ID + - " INTEGER PRIMARY KEY AUTOINCREMENT, " + - SessionTableColumns.SESSION_ID + " STRING NOT NULL, " + - SessionTableColumns.API_KEY + " STRING NOT NULL, " + - SessionTableColumns.START_TIME + " INTEGER NOT NULL," + - SessionTableColumns.END_TIME + " INTEGER NOT NULL," + - SessionTableColumns.SESSION_FOREGROUND_LENGTH + " INTEGER NOT NULL," + - SessionTableColumns.ATTRIBUTES + " TEXT, " + - SessionTableColumns.STATUS + " TEXT," + - SessionTableColumns.APP_INFO + " TEXT, " + - SessionTableColumns.DEVICE_INFO + " TEXT, " + - SessionTableColumns.MP_ID + " INTEGER" + + "CREATE TABLE IF NOT EXISTS " + SessionTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + SessionTableColumns.SESSION_ID + " STRING NOT NULL, " + SessionTableColumns.API_KEY + " STRING NOT NULL, " + SessionTableColumns.START_TIME + " INTEGER NOT NULL," + SessionTableColumns.END_TIME + " INTEGER NOT NULL," + SessionTableColumns.SESSION_FOREGROUND_LENGTH + " INTEGER NOT NULL," + SessionTableColumns.ATTRIBUTES + " TEXT, " + SessionTableColumns.STATUS + " TEXT," + SessionTableColumns.APP_INFO + " TEXT, " + SessionTableColumns.DEVICE_INFO + " TEXT, " + SessionTableColumns.MP_ID + " INTEGER" ");"; } diff --git a/android-core/src/main/java/com/mparticle/internal/database/tables/UploadTable.java b/android-core/src/main/java/com/mparticle/internal/database/tables/UploadTable.java index c089ba959..580552750 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/tables/UploadTable.java +++ b/android-core/src/main/java/com/mparticle/internal/database/tables/UploadTable.java @@ -23,16 +23,16 @@ protected interface UploadTableColumns extends BaseColumns { static final String CREATE_UPLOADS_DDL = - "CREATE TABLE IF NOT EXISTS " + UploadTableColumns.TABLE_NAME + " (" + BaseColumns._ID + - " INTEGER PRIMARY KEY AUTOINCREMENT, " + - UploadTableColumns.API_KEY + " STRING NOT NULL, " + - UploadTableColumns.MESSAGE + " TEXT, " + - UploadTableColumns.CREATED_AT + " INTEGER NOT NULL, " + - UploadTableColumns.REQUEST_TYPE + " TEXT, " + - UploadTableColumns.SESSION_ID + " TEXT, " + - UploadTableColumns.UPLOAD_SETTINGS + " TEXT" + + "CREATE TABLE IF NOT EXISTS " + UploadTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + UploadTableColumns.API_KEY + " STRING NOT NULL, " + UploadTableColumns.MESSAGE + " TEXT, " + UploadTableColumns.CREATED_AT + " INTEGER NOT NULL, " + UploadTableColumns.REQUEST_TYPE + " TEXT, " + UploadTableColumns.SESSION_ID + " TEXT, " + UploadTableColumns.UPLOAD_SETTINGS + " TEXT" ");"; - static final String UPLOAD_ADD_UPLOAD_SETTINGS_COLUMN = "ALTER TABLE " + UploadTableColumns.TABLE_NAME + + static final String UPLOAD_ADD_UPLOAD_SETTINGS_COLUMN = "ALTER TABLE " + UploadTableColumns.TABLE_NAME " ADD COLUMN " + UploadTableColumns.UPLOAD_SETTINGS + " TEXT"; } diff --git a/android-core/src/main/java/com/mparticle/internal/database/tables/UserAttributesTable.java b/android-core/src/main/java/com/mparticle/internal/database/tables/UserAttributesTable.java index 882d2da31..1dbdf5d1a 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/tables/UserAttributesTable.java +++ b/android-core/src/main/java/com/mparticle/internal/database/tables/UserAttributesTable.java @@ -19,12 +19,12 @@ protected interface UserAttributesTableColumns { } static final String CREATE_USER_ATTRIBUTES_DDL = - "CREATE TABLE IF NOT EXISTS " + UserAttributesTableColumns.TABLE_NAME + " (" + BaseColumns._ID + - " INTEGER PRIMARY KEY AUTOINCREMENT, " + - UserAttributesTableColumns.ATTRIBUTE_KEY + " COLLATE NOCASE NOT NULL, " + - UserAttributesTableColumns.ATTRIBUTE_VALUE + " TEXT, " + - UserAttributesTableColumns.IS_LIST + " INTEGER NOT NULL, " + - UserAttributesTableColumns.CREATED_AT + " INTEGER NOT NULL, " + - UserAttributesTableColumns.MP_ID + " INTEGER" + + "CREATE TABLE IF NOT EXISTS " + UserAttributesTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + UserAttributesTableColumns.ATTRIBUTE_KEY + " COLLATE NOCASE NOT NULL, " + UserAttributesTableColumns.ATTRIBUTE_VALUE + " TEXT, " + UserAttributesTableColumns.IS_LIST + " INTEGER NOT NULL, " + UserAttributesTableColumns.CREATED_AT + " INTEGER NOT NULL, " + UserAttributesTableColumns.MP_ID + " INTEGER" ");"; } diff --git a/android-core/src/main/java/com/mparticle/segmentation/Segment.java b/android-core/src/main/java/com/mparticle/segmentation/Segment.java index 125fbaf6a..5d90cdc19 100644 --- a/android-core/src/main/java/com/mparticle/segmentation/Segment.java +++ b/android-core/src/main/java/com/mparticle/segmentation/Segment.java @@ -72,8 +72,8 @@ public String[] getEndpoints() { @Override @NonNull public String toString() { - return "Segment ID: " + id + ", " + - "Name: " + name + ", " + + return "Segment ID: " + id + ", " + "Name: " + name + ", " "Endpoints: " + ((endpoints != null && endpoints.length > 0) ? Arrays.toString(endpoints) : "None specified."); } } diff --git a/android-core/src/main/kotlin/com/mparticle/MpRoktEventCallback.kt b/android-core/src/main/kotlin/com/mparticle/MpRoktEventCallback.kt index 8fc46c28f..dbf07f66f 100644 --- a/android-core/src/main/kotlin/com/mparticle/MpRoktEventCallback.kt +++ b/android-core/src/main/kotlin/com/mparticle/MpRoktEventCallback.kt @@ -4,7 +4,6 @@ package com.mparticle * ### Optional callback events for when the view loads and unloads. */ interface MpRoktEventCallback { - /** * onLoad Callback will be triggered immediately when the View displays. */ @@ -68,7 +67,9 @@ enum class UnloadReasons { /** * Catch-all for all issues. */ - UNKNOWN; + UNKNOWN, + + ; companion object { /** @@ -78,12 +79,11 @@ enum class UnloadReasons { * @param value the name of the enum constant to look up * @return the corresponding UnloadReasons constant or UNKNOWN if no match is found */ - fun from(value: String): UnloadReasons { - return try { + fun from(value: String): UnloadReasons = + try { valueOf(value) } catch (e: IllegalArgumentException) { UNKNOWN } - } } } diff --git a/android-core/src/main/kotlin/com/mparticle/Rokt.kt b/android-core/src/main/kotlin/com/mparticle/Rokt.kt index 58e5ee056..8c2146084 100644 --- a/android-core/src/main/kotlin/com/mparticle/Rokt.kt +++ b/android-core/src/main/kotlin/com/mparticle/Rokt.kt @@ -13,9 +13,8 @@ import java.lang.ref.WeakReference @ApiClass class Rokt internal constructor( private val mConfigManager: ConfigManager, - private val mKitManager: KitManager + private val mKitManager: KitManager, ) { - @JvmOverloads fun selectPlacements( identifier: String, @@ -23,22 +22,25 @@ class Rokt internal constructor( callbacks: MpRoktEventCallback? = null, embeddedViews: Map>? = null, fontTypefaces: Map>? = null, - config: RoktConfig? = null + config: RoktConfig? = null, ) { if (mConfigManager.isEnabled) { mKitManager.execute(identifier, HashMap(attributes), callbacks, embeddedViews, fontTypefaces, config) } } - fun events(identifier: String) : Flow { - return if (mConfigManager.isEnabled) { + fun events(identifier: String): Flow = + if (mConfigManager.isEnabled) { mKitManager.events(identifier) } else { flowOf() } - } - fun purchaseFinalized(placementId: String, catalogItemId: String, status: Boolean) { + fun purchaseFinalized( + placementId: String, + catalogItemId: String, + status: Boolean, + ) { if (mConfigManager.isEnabled) { mKitManager.purchaseFinalized(placementId, catalogItemId, status) } @@ -49,4 +51,4 @@ class Rokt internal constructor( mKitManager.close() } } -} \ No newline at end of file +} diff --git a/android-core/src/main/kotlin/com/mparticle/RoktEvent.kt b/android-core/src/main/kotlin/com/mparticle/RoktEvent.kt index a0348a200..9e265b01a 100644 --- a/android-core/src/main/kotlin/com/mparticle/RoktEvent.kt +++ b/android-core/src/main/kotlin/com/mparticle/RoktEvent.kt @@ -17,63 +17,84 @@ sealed interface RoktEvent { * OfferEngagement event will be triggered if User engaged with the offer * @param placementId - identifier for the placement emitting the event */ - data class OfferEngagement(val placementId: String) : RoktEvent + data class OfferEngagement( + val placementId: String, + ) : RoktEvent /** * PositiveEngagement event will be triggered if User positively engaged with the offer * @param placementId - identifier for the placement emitting the event */ - data class PositiveEngagement(val placementId: String) : RoktEvent + data class PositiveEngagement( + val placementId: String, + ) : RoktEvent /** * FirstPositiveEngagement event will be triggered when the user positively engaged with the offer first time * @param placementId - identifier for the placement emitting the event */ - data class FirstPositiveEngagement(val placementId: String) : RoktEvent + data class FirstPositiveEngagement( + val placementId: String, + ) : RoktEvent /** * PlacementInteractive event will be triggered when placement has been rendered and is interactable * @param placementId - identifier for the placement emitting the event */ - data class PlacementInteractive(val placementId: String) : RoktEvent + data class PlacementInteractive( + val placementId: String, + ) : RoktEvent /** * PlacementReady event will be triggered when placement is ready to display but has not rendered content yet * @param placementId - identifier for the placement emitting the event */ - data class PlacementReady(val placementId: String) : RoktEvent + data class PlacementReady( + val placementId: String, + ) : RoktEvent /** * PlacementClosed event will be triggered when placement closes by user * @param placementId - identifier for the placement emitting the event */ - data class PlacementClosed(val placementId: String) : RoktEvent + data class PlacementClosed( + val placementId: String, + ) : RoktEvent /** * PlacementCompleted event will be triggered when the offer progression moves to the end and no more * offer to display * @param placementId - identifier for the placement emitting the event */ - data class PlacementCompleted(val placementId: String) : RoktEvent + data class PlacementCompleted( + val placementId: String, + ) : RoktEvent /** * PlacementFailure event will be triggered when placement could not be displayed due to some failure * @param placementId - optional identifier for the placement emitting the event */ - data class PlacementFailure(val placementId: String? = null) : RoktEvent + data class PlacementFailure( + val placementId: String? = null, + ) : RoktEvent /** * InitComplete event will be triggered when SDK has finished initialization * @param success - true if init was successful */ - data class InitComplete(val success: Boolean) : RoktEvent + data class InitComplete( + val success: Boolean, + ) : RoktEvent /** * OpenUrl event will be triggered when user clicks on a link and the link target is set to Passthrough * @param placementId - identifier for the placement emitting the event * @param url - url to open */ - data class OpenUrl(val placementId: String, val url: String) : RoktEvent + data class OpenUrl( + val placementId: String, + val url: String, + ) : RoktEvent /** * CartItemInstantPurchase event will be triggered when the catalog item purchase is initiated @@ -97,6 +118,6 @@ sealed interface RoktEvent { val linkedProductId: String, val totalPrice: Double, val quantity: Int, - val unitPrice: Double + val unitPrice: Double, ) : RoktEvent } diff --git a/android-core/src/main/kotlin/com/mparticle/TypedUserAttributeListener.kt b/android-core/src/main/kotlin/com/mparticle/TypedUserAttributeListener.kt index 49d6f0d71..e1750fb32 100644 --- a/android-core/src/main/kotlin/com/mparticle/TypedUserAttributeListener.kt +++ b/android-core/src/main/kotlin/com/mparticle/TypedUserAttributeListener.kt @@ -4,6 +4,6 @@ interface TypedUserAttributeListener : UserAttributeListenerType { fun onUserAttributesReceived( userAttributes: Map, userAttributeLists: Map?>, - mpid: Long + mpid: Long, ) -} \ No newline at end of file +} diff --git a/android-core/src/main/kotlin/com/mparticle/WrapperSdk.kt b/android-core/src/main/kotlin/com/mparticle/WrapperSdk.kt index a956ac135..15a3b7cb3 100644 --- a/android-core/src/main/kotlin/com/mparticle/WrapperSdk.kt +++ b/android-core/src/main/kotlin/com/mparticle/WrapperSdk.kt @@ -1,13 +1,16 @@ package com.mparticle -enum class WrapperSdk(wrapperSdkId: Int, wrapperSdkName: String) { +enum class WrapperSdk( + wrapperSdkId: Int, + wrapperSdkName: String, +) { WrapperNone(0, "None"), WrapperSdkUnity(1, "Unity"), WrapperSdkReactNative(2, "React Native"), WrapperSdkCordova(3, "Cordova"), WrapperXamarin(4, "Xamarin"), WrapperFlutter(5, "Flutter"), - WrapperMaui(6, "Maui"); + WrapperMaui(6, "Maui"), } /** @@ -15,4 +18,7 @@ enum class WrapperSdk(wrapperSdkId: Int, wrapperSdkName: String) { * @param version represents the configured version for the wrapper sdk. Will return null if * [WrapperSdk.WrapperNone] is set as the sdk wrapper */ -data class WrapperSdkVersion(val sdk: WrapperSdk, val version: String?) \ No newline at end of file +data class WrapperSdkVersion( + val sdk: WrapperSdk, + val version: String?, +) diff --git a/android-core/src/main/kotlin/com/mparticle/audience/Audience.kt b/android-core/src/main/kotlin/com/mparticle/audience/Audience.kt index d2ff8bee3..4865dc140 100644 --- a/android-core/src/main/kotlin/com/mparticle/audience/Audience.kt +++ b/android-core/src/main/kotlin/com/mparticle/audience/Audience.kt @@ -1,3 +1,5 @@ package com.mparticle.audience -data class Audience(val audienceID:String) +data class Audience( + val audienceID: String, +) diff --git a/android-core/src/main/kotlin/com/mparticle/audience/AudienceResponse.kt b/android-core/src/main/kotlin/com/mparticle/audience/AudienceResponse.kt index 53f2fb50f..f82879b46 100644 --- a/android-core/src/main/kotlin/com/mparticle/audience/AudienceResponse.kt +++ b/android-core/src/main/kotlin/com/mparticle/audience/AudienceResponse.kt @@ -12,7 +12,6 @@ class AudienceResponse { constructor(httpCode: Int, errorMsg: String) { code = httpCode error = errorMsg - } constructor(httpCode: Int, jsonObject: JSONObject) { @@ -21,13 +20,9 @@ class AudienceResponse { parseJsonObject(jsonObject) } - fun getAudienceResult(): ArrayList { - return audienceList - } + fun getAudienceResult(): ArrayList = audienceList - fun getError(): String? { - return error - } + fun getError(): String? = error private fun parseJsonObject(jsonObject: JSONObject) { try { @@ -41,4 +36,4 @@ class AudienceResponse { Logger.error("Exception while parsing audience response $e") } } -} \ No newline at end of file +} diff --git a/android-core/src/main/kotlin/com/mparticle/audience/AudienceTask.kt b/android-core/src/main/kotlin/com/mparticle/audience/AudienceTask.kt index f3d3c7626..9636c720e 100644 --- a/android-core/src/main/kotlin/com/mparticle/audience/AudienceTask.kt +++ b/android-core/src/main/kotlin/com/mparticle/audience/AudienceTask.kt @@ -1,8 +1,6 @@ package com.mparticle.audience - abstract class AudienceTask { - abstract fun isComplete(): Boolean abstract fun isSuccessful(): Boolean @@ -12,4 +10,4 @@ abstract class AudienceTask { abstract fun addSuccessListener(listener: AudienceTaskSuccessListener): AudienceTask abstract fun addFailureListener(listener: AudienceTaskFailureListener): AudienceTask -} \ No newline at end of file +} diff --git a/android-core/src/main/kotlin/com/mparticle/audience/AudienceTaskFailureListener.kt b/android-core/src/main/kotlin/com/mparticle/audience/AudienceTaskFailureListener.kt index aeb088b79..130fb986d 100644 --- a/android-core/src/main/kotlin/com/mparticle/audience/AudienceTaskFailureListener.kt +++ b/android-core/src/main/kotlin/com/mparticle/audience/AudienceTaskFailureListener.kt @@ -2,4 +2,4 @@ package com.mparticle.audience fun interface AudienceTaskFailureListener { fun onFailure(result: AudienceResponse?) -} \ No newline at end of file +} diff --git a/android-core/src/main/kotlin/com/mparticle/audience/AudienceTaskSuccessListener.kt b/android-core/src/main/kotlin/com/mparticle/audience/AudienceTaskSuccessListener.kt index 81c9ff1b1..68876eaee 100644 --- a/android-core/src/main/kotlin/com/mparticle/audience/AudienceTaskSuccessListener.kt +++ b/android-core/src/main/kotlin/com/mparticle/audience/AudienceTaskSuccessListener.kt @@ -2,4 +2,4 @@ package com.mparticle.audience fun interface AudienceTaskSuccessListener { fun onSuccess(result: AudienceResponse) -} \ No newline at end of file +} diff --git a/android-core/src/main/kotlin/com/mparticle/audience/BaseAudienceTask.kt b/android-core/src/main/kotlin/com/mparticle/audience/BaseAudienceTask.kt index 086fa6e95..f99f2b23a 100644 --- a/android-core/src/main/kotlin/com/mparticle/audience/BaseAudienceTask.kt +++ b/android-core/src/main/kotlin/com/mparticle/audience/BaseAudienceTask.kt @@ -6,7 +6,6 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class BaseAudienceTask : AudienceTask() { - private var isCompleted: Boolean = false private var isSuccessful: Boolean = false private var result: AudienceResponse? = null @@ -42,17 +41,11 @@ class BaseAudienceTask : AudienceTask() { } } - override fun isComplete(): Boolean { - return isCompleted - } + override fun isComplete(): Boolean = isCompleted - override fun isSuccessful(): Boolean { - return isSuccessful - } + override fun isSuccessful(): Boolean = isSuccessful - override fun getResult(): AudienceResponse? { - return result - } + override fun getResult(): AudienceResponse? = result override fun addSuccessListener(listener: AudienceTaskSuccessListener): BaseAudienceTask { if (listener != null) { @@ -67,7 +60,4 @@ class BaseAudienceTask : AudienceTask() { } return this } - - } - diff --git a/android-core/src/main/kotlin/com/mparticle/identity/UserAttributeListenerWrapper.kt b/android-core/src/main/kotlin/com/mparticle/identity/UserAttributeListenerWrapper.kt index dcb907e56..9d88daf00 100644 --- a/android-core/src/main/kotlin/com/mparticle/identity/UserAttributeListenerWrapper.kt +++ b/android-core/src/main/kotlin/com/mparticle/identity/UserAttributeListenerWrapper.kt @@ -4,22 +4,28 @@ import com.mparticle.TypedUserAttributeListener import com.mparticle.UserAttributeListener import com.mparticle.UserAttributeListenerType -class UserAttributeListenerWrapper(val listener: UserAttributeListenerType) { +class UserAttributeListenerWrapper( + val listener: UserAttributeListenerType, +) { fun onUserAttributesReceived( singles: Map?, lists: Map?>?, - mpid: Long? + mpid: Long?, ) { when (listener) { - is UserAttributeListener -> (singles ?: mutableMapOf()) - .entries - .associate { it.key to it.value?.toString() } - .let { listener.onUserAttributesReceived(it, lists, mpid) } - is TypedUserAttributeListener -> mpid?.let { - listener.onUserAttributesReceived( - singles ?: mutableMapOf(), lists ?: mutableMapOf(), it - ) - } + is UserAttributeListener -> + (singles ?: mutableMapOf()) + .entries + .associate { it.key to it.value?.toString() } + .let { listener.onUserAttributesReceived(it, lists, mpid) } + is TypedUserAttributeListener -> + mpid?.let { + listener.onUserAttributesReceived( + singles ?: mutableMapOf(), + lists ?: mutableMapOf(), + it, + ) + } } } -} \ No newline at end of file +} diff --git a/android-core/src/main/kotlin/com/mparticle/internal/AppStateManager.kt b/android-core/src/main/kotlin/com/mparticle/internal/AppStateManager.kt index 1d01f997b..f11c19de5 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/AppStateManager.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/AppStateManager.kt @@ -28,470 +28,485 @@ import java.util.concurrent.atomic.AtomicLong /** * This class is responsible for maintaining the session state by listening to the Activity lifecycle. */ -open class AppStateManager @JvmOverloads constructor( - context: Context, - unitTesting: Boolean = false -) { - private var mConfigManager: ConfigManager? = null - var mContext: Context - private val mPreferences: SharedPreferences - open var session: InternalSession = InternalSession() - - open var currentActivity: WeakReference? = null - set - - var currentActivityName: String? = null - private set - var mLastStoppedTime: AtomicLong - - /** - * it can take some time between when an activity stops and when a new one (or the same one on a configuration change/rotation) - * starts again, so use this handler and ACTIVITY_DELAY to determine when we're *really" in the background - */ - @JvmField - var delayedBackgroundCheckHandler: Handler = Handler(Looper.getMainLooper()) - - /** - * Some providers need to know for the given session, how many 'interruptions' there were - how many - * times did the user leave and return prior to the session timing out. - */ - var mInterruptionCount: AtomicInteger = AtomicInteger(0) - - /** - * Important to determine foreground-time length for a given session. - * Uses the system-uptime clock to avoid devices which wonky clocks, or clocks - * that change while the app is running. - */ - private var mLastForegroundTime: Long = 0 - - var mUnitTesting: Boolean = false - private var mMessageManager: MessageManager? = null - open var launchUri: Uri? = null - set - var launchAction: String? = null - private set - - init { - mUnitTesting = unitTesting - mContext = context.applicationContext - mLastStoppedTime = AtomicLong(time) - mPreferences = context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE) - ConfigManager.addMpIdChangeListener { newMpid, previousMpid -> - if (session != null) { - session.addMpid(newMpid) +open class AppStateManager + @JvmOverloads + constructor( + context: Context, + unitTesting: Boolean = false, + ) { + private var mConfigManager: ConfigManager? = null + var mContext: Context + private val mPreferences: SharedPreferences + open var session: InternalSession = InternalSession() + + open var currentActivity: WeakReference? = null + set + + var currentActivityName: String? = null + private set + var mLastStoppedTime: AtomicLong + + /** + * it can take some time between when an activity stops and when a new one (or the same one on a configuration change/rotation) + * starts again, so use this handler and ACTIVITY_DELAY to determine when we're *really" in the background + */ + @JvmField + var delayedBackgroundCheckHandler: Handler = Handler(Looper.getMainLooper()) + + /** + * Some providers need to know for the given session, how many 'interruptions' there were - how many + * times did the user leave and return prior to the session timing out. + */ + var mInterruptionCount: AtomicInteger = AtomicInteger(0) + + /** + * Important to determine foreground-time length for a given session. + * Uses the system-uptime clock to avoid devices which wonky clocks, or clocks + * that change while the app is running. + */ + private var mLastForegroundTime: Long = 0 + + var mUnitTesting: Boolean = false + private var mMessageManager: MessageManager? = null + open var launchUri: Uri? = null + set + var launchAction: String? = null + private set + + init { + mUnitTesting = unitTesting + mContext = context.applicationContext + mLastStoppedTime = AtomicLong(time) + mPreferences = context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE) + ConfigManager.addMpIdChangeListener { newMpid, previousMpid -> + if (session != null) { + session.addMpid(newMpid) + } } } - } - fun init(apiVersion: Int) { - if (apiVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { - setupLifecycleCallbacks() + fun init(apiVersion: Int) { + if (apiVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { + setupLifecycleCallbacks() + } } - } - - fun setConfigManager(manager: ConfigManager?) { - mConfigManager = manager - } - fun setMessageManager(manager: MessageManager?) { - mMessageManager = manager - } + fun setConfigManager(manager: ConfigManager?) { + mConfigManager = manager + } - private val time: Long - get() = if (mUnitTesting) { - System.currentTimeMillis() - } else { - SystemClock.elapsedRealtime() + fun setMessageManager(manager: MessageManager?) { + mMessageManager = manager } - fun onActivityResumed(activity: Activity?) { - try { - currentActivityName = getActivityName(activity) + private val time: Long + get() = + if (mUnitTesting) { + System.currentTimeMillis() + } else { + SystemClock.elapsedRealtime() + } - val interruptions = mInterruptionCount.get() - if (!mInitialized || !session.isActive) { - mInterruptionCount = AtomicInteger(0) - } - var previousSessionPackage: String? = null - var previousSessionUri: String? = null - var previousSessionParameters: String? = null - if (activity != null) { - val callingApplication = activity.callingActivity - if (callingApplication != null) { - previousSessionPackage = callingApplication.packageName + fun onActivityResumed(activity: Activity?) { + try { + currentActivityName = getActivityName(activity) + + val interruptions = mInterruptionCount.get() + if (!mInitialized || !session.isActive) { + mInterruptionCount = AtomicInteger(0) } - if (activity.intent != null) { - previousSessionUri = activity.intent.dataString - if (launchUri == null) { - launchUri = activity.intent.data - } - if (launchAction == null) { - launchAction = activity.intent.action + var previousSessionPackage: String? = null + var previousSessionUri: String? = null + var previousSessionParameters: String? = null + if (activity != null) { + val callingApplication = activity.callingActivity + if (callingApplication != null) { + previousSessionPackage = callingApplication.packageName } - if (activity.intent.extras?.getBundle(Constants.External.APPLINK_KEY) != null) { - val parameters = JSONObject() - try { - parameters.put( - Constants.External.APPLINK_KEY, - MPUtility.wrapExtras( - activity.intent.extras?.getBundle(Constants.External.APPLINK_KEY) + if (activity.intent != null) { + previousSessionUri = activity.intent.dataString + if (launchUri == null) { + launchUri = activity.intent.data + } + if (launchAction == null) { + launchAction = activity.intent.action + } + if (activity.intent.extras?.getBundle(Constants.External.APPLINK_KEY) != null) { + val parameters = JSONObject() + try { + parameters.put( + Constants.External.APPLINK_KEY, + MPUtility.wrapExtras( + activity.intent.extras?.getBundle(Constants.External.APPLINK_KEY), + ), ) - ) - } catch (e: Exception) { - Logger.error("Exception on onActivityResumed ") + } catch (e: Exception) { + Logger.error("Exception on onActivityResumed ") + } + previousSessionParameters = parameters.toString() } - previousSessionParameters = parameters.toString() } } - } - session.updateBackgroundTime(mLastStoppedTime, time) + session.updateBackgroundTime(mLastStoppedTime, time) - var isBackToForeground = false - if (!mInitialized) { - initialize( - currentActivityName, - previousSessionUri, - previousSessionParameters, - previousSessionPackage - ) - } else if (isBackgrounded() && mLastStoppedTime.get() > 0) { - isBackToForeground = true - mMessageManager?.postToMessageThread(CheckAdIdRunnable(mConfigManager)) - logStateTransition( - Constants.StateTransitionType.STATE_TRANS_FORE, - currentActivityName, - mLastStoppedTime.get() - mLastForegroundTime, - time - mLastStoppedTime.get(), - previousSessionUri, - previousSessionParameters, - previousSessionPackage, - interruptions - ) - } - CoroutineScope(Dispatchers.IO).launch { - mConfigManager?.setPreviousAdId() - } - mLastForegroundTime = time + var isBackToForeground = false + if (!mInitialized) { + initialize( + currentActivityName, + previousSessionUri, + previousSessionParameters, + previousSessionPackage, + ) + } else if (isBackgrounded() && mLastStoppedTime.get() > 0) { + isBackToForeground = true + mMessageManager?.postToMessageThread(CheckAdIdRunnable(mConfigManager)) + logStateTransition( + Constants.StateTransitionType.STATE_TRANS_FORE, + currentActivityName, + mLastStoppedTime.get() - mLastForegroundTime, + time - mLastStoppedTime.get(), + previousSessionUri, + previousSessionParameters, + previousSessionPackage, + interruptions, + ) + } + CoroutineScope(Dispatchers.IO).launch { + mConfigManager?.setPreviousAdId() + } + mLastForegroundTime = time - if (currentActivity != null) { - currentActivity?.clear() - currentActivity = null - } - currentActivity = WeakReference(activity) + if (currentActivity != null) { + currentActivity?.clear() + currentActivity = null + } + currentActivity = WeakReference(activity) - val instance = MParticle.getInstance() - if (instance != null) { - if (instance.isAutoTrackingEnabled) { - currentActivityName?.let { - instance.logScreen(it) + val instance = MParticle.getInstance() + if (instance != null) { + if (instance.isAutoTrackingEnabled) { + currentActivityName?.let { + instance.logScreen(it) + } } + if (isBackToForeground) { + instance.Internal().kitManager.onApplicationForeground() + Logger.debug("App foregrounded.") + } + instance.Internal().kitManager.onActivityResumed(activity) } - if (isBackToForeground) { - instance.Internal().kitManager.onApplicationForeground() - Logger.debug("App foregrounded.") - } - instance.Internal().kitManager.onActivityResumed(activity) + } catch (e: Exception) { + Logger.verbose("Failed while trying to track activity resume: " + e.message) } - } catch (e: Exception) { - Logger.verbose("Failed while trying to track activity resume: " + e.message) } - } - fun onActivityPaused(activity: Activity) { - try { - mPreferences.edit().putBoolean(Constants.PrefKeys.CRASHED_IN_FOREGROUND, false).apply() - mLastStoppedTime = AtomicLong(time) - if (currentActivity != null && activity === currentActivity?.get()) { - currentActivity?.clear() - currentActivity = null - } + fun onActivityPaused(activity: Activity) { + try { + mPreferences.edit().putBoolean(Constants.PrefKeys.CRASHED_IN_FOREGROUND, false).apply() + mLastStoppedTime = AtomicLong(time) + if (currentActivity != null && activity === currentActivity?.get()) { + currentActivity?.clear() + currentActivity = null + } - delayedBackgroundCheckHandler.postDelayed( - { - try { - if (isBackgrounded()) { - checkSessionTimeout() - logBackgrounded() + delayedBackgroundCheckHandler.postDelayed( + { + try { + if (isBackgrounded()) { + checkSessionTimeout() + logBackgrounded() + } + } catch (e: Exception) { + e.printStackTrace() } - } catch (e: Exception) { - e.printStackTrace() - } - }, - ACTIVITY_DELAY - ) + }, + ACTIVITY_DELAY, + ) - val instance = MParticle.getInstance() - if (instance != null) { - if (instance.isAutoTrackingEnabled) { - instance.logScreen( - MPEvent.Builder(getActivityName(activity)) - .internalNavigationDirection(false) - .build() - ) + val instance = MParticle.getInstance() + if (instance != null) { + if (instance.isAutoTrackingEnabled) { + instance.logScreen( + MPEvent + .Builder(getActivityName(activity)) + .internalNavigationDirection(false) + .build(), + ) + } + instance.Internal().kitManager.onActivityPaused(activity) } - instance.Internal().kitManager.onActivityPaused(activity) + } catch (e: Exception) { + Logger.verbose("Failed while trying to track activity pause: " + e.message) } - } catch (e: Exception) { - Logger.verbose("Failed while trying to track activity pause: " + e.message) } - } - fun ensureActiveSession() { - if (!mInitialized) { - initialize(null, null, null, null) - } - session.mLastEventTime = System.currentTimeMillis() - if (!session.isActive) { - newSession() - } else { - mMessageManager?.updateSessionEnd(this.session) + fun ensureActiveSession() { + if (!mInitialized) { + initialize(null, null, null, null) + } + session.mLastEventTime = System.currentTimeMillis() + if (!session.isActive) { + newSession() + } else { + mMessageManager?.updateSessionEnd(this.session) + } } - } - fun logStateTransition( - transitionType: String?, - currentActivity: String?, - previousForegroundTime: Long, - suspendedTime: Long, - dataString: String?, - launchParameters: String?, - launchPackage: String?, - interruptions: Int - ) { - if (mConfigManager?.isEnabled == true) { - ensureActiveSession() - mMessageManager?.logStateTransition( - transitionType, - currentActivity, - dataString, - launchParameters, - launchPackage, - previousForegroundTime, - suspendedTime, - interruptions - ) + fun logStateTransition( + transitionType: String?, + currentActivity: String?, + previousForegroundTime: Long, + suspendedTime: Long, + dataString: String?, + launchParameters: String?, + launchPackage: String?, + interruptions: Int, + ) { + if (mConfigManager?.isEnabled == true) { + ensureActiveSession() + mMessageManager?.logStateTransition( + transitionType, + currentActivity, + dataString, + launchParameters, + launchPackage, + previousForegroundTime, + suspendedTime, + interruptions, + ) + } } - } - fun logStateTransition(transitionType: String?, currentActivity: String?) { - logStateTransition(transitionType, currentActivity, 0, 0, null, null, null, 0) - } + fun logStateTransition( + transitionType: String?, + currentActivity: String?, + ) { + logStateTransition(transitionType, currentActivity, 0, 0, null, null, null, 0) + } - /** - * Creates a new session and generates the start-session message. - */ - private fun newSession() { - startSession() - mMessageManager?.startSession(session) - Logger.debug("Started new session") - mMessageManager?.startUploadLoop() - enableLocationTracking() - checkSessionTimeout() - } + /** + * Creates a new session and generates the start-session message. + */ + private fun newSession() { + startSession() + mMessageManager?.startSession(session) + Logger.debug("Started new session") + mMessageManager?.startUploadLoop() + enableLocationTracking() + checkSessionTimeout() + } - private fun enableLocationTracking() { - if (mPreferences.contains(Constants.PrefKeys.LOCATION_PROVIDER)) { - val provider = mPreferences.getString(Constants.PrefKeys.LOCATION_PROVIDER, null) - val minTime = mPreferences.getLong(Constants.PrefKeys.LOCATION_MINTIME, 0) - val minDistance = mPreferences.getLong(Constants.PrefKeys.LOCATION_MINDISTANCE, 0) - if (provider != null && minTime > 0 && minDistance > 0) { - val instance = MParticle.getInstance() - instance?.enableLocationTracking(provider, minTime, minDistance) + private fun enableLocationTracking() { + if (mPreferences.contains(Constants.PrefKeys.LOCATION_PROVIDER)) { + val provider = mPreferences.getString(Constants.PrefKeys.LOCATION_PROVIDER, null) + val minTime = mPreferences.getLong(Constants.PrefKeys.LOCATION_MINTIME, 0) + val minDistance = mPreferences.getLong(Constants.PrefKeys.LOCATION_MINDISTANCE, 0) + if (provider != null && minTime > 0 && minDistance > 0) { + val instance = MParticle.getInstance() + instance?.enableLocationTracking(provider, minTime, minDistance) + } } } - } - fun shouldEndSession(): Boolean { - val instance = MParticle.getInstance() - return ( + fun shouldEndSession(): Boolean { + val instance = MParticle.getInstance() + return ( 0L != session?.mSessionStartTime && - isBackgrounded() && - mConfigManager?.sessionTimeout?.let { session.isTimedOut(it) } == true && - (instance == null || !instance.Media().audioPlaying) - ) - } + isBackgrounded() && + mConfigManager?.sessionTimeout?.let { session.isTimedOut(it) } == true && + (instance == null || !instance.Media().audioPlaying) + ) + } - private fun checkSessionTimeout() { - mConfigManager?.sessionTimeout?.toLong()?.let { - delayedBackgroundCheckHandler.postDelayed({ - if (shouldEndSession()) { - Logger.debug("Session timed out") - endSession() - } - }, it) + private fun checkSessionTimeout() { + mConfigManager?.sessionTimeout?.toLong()?.let { + delayedBackgroundCheckHandler.postDelayed({ + if (shouldEndSession()) { + Logger.debug("Session timed out") + endSession() + } + }, it) + } } - } - private fun initialize( - currentActivityName: String?, - previousSessionUri: String?, - previousSessionParameters: String?, - previousSessionPackage: String? - ) { - mInitialized = true - logStateTransition( - Constants.StateTransitionType.STATE_TRANS_INIT, - currentActivityName, - 0, - 0, - previousSessionUri, - previousSessionParameters, - previousSessionPackage, - 0 - ) - } + private fun initialize( + currentActivityName: String?, + previousSessionUri: String?, + previousSessionParameters: String?, + previousSessionPackage: String?, + ) { + mInitialized = true + logStateTransition( + Constants.StateTransitionType.STATE_TRANS_INIT, + currentActivityName, + 0, + 0, + previousSessionUri, + previousSessionParameters, + previousSessionPackage, + 0, + ) + } - fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) { - val instance = MParticle.getInstance() - instance?.Internal()?.kitManager?.onActivityCreated(activity, savedInstanceState) - } + fun onActivityCreated( + activity: Activity?, + savedInstanceState: Bundle?, + ) { + val instance = MParticle.getInstance() + instance?.Internal()?.kitManager?.onActivityCreated(activity, savedInstanceState) + } - fun onActivityStarted(activity: Activity?) { - val instance = MParticle.getInstance() - instance?.Internal()?.kitManager?.onActivityStarted(activity) - } + fun onActivityStarted(activity: Activity?) { + val instance = MParticle.getInstance() + instance?.Internal()?.kitManager?.onActivityStarted(activity) + } - fun onActivityStopped(activity: Activity?) { - val instance = MParticle.getInstance() - instance?.Internal()?.kitManager?.onActivityStopped(activity) - } + fun onActivityStopped(activity: Activity?) { + val instance = MParticle.getInstance() + instance?.Internal()?.kitManager?.onActivityStopped(activity) + } - private fun logBackgrounded() { - val instance = MParticle.getInstance() - if (instance != null) { - logStateTransition(Constants.StateTransitionType.STATE_TRANS_BG, currentActivityName) - instance.Internal().kitManager.onApplicationBackground() - currentActivityName = null - Logger.debug("App backgrounded.") - mInterruptionCount.incrementAndGet() + private fun logBackgrounded() { + val instance = MParticle.getInstance() + if (instance != null) { + logStateTransition(Constants.StateTransitionType.STATE_TRANS_BG, currentActivityName) + instance.Internal().kitManager.onApplicationBackground() + currentActivityName = null + Logger.debug("App backgrounded.") + mInterruptionCount.incrementAndGet() + } } - } - @TargetApi(14) - private fun setupLifecycleCallbacks() { - (mContext as Application).registerActivityLifecycleCallbacks( - MPLifecycleCallbackDelegate( - this + @TargetApi(14) + private fun setupLifecycleCallbacks() { + (mContext as Application).registerActivityLifecycleCallbacks( + MPLifecycleCallbackDelegate( + this, + ), ) - ) - } + } - open fun isBackgrounded(): Boolean { - return !mInitialized || (currentActivity == null && (time - mLastStoppedTime.get() >= ACTIVITY_DELAY)) - } + open fun isBackgrounded(): Boolean = !mInitialized || (currentActivity == null && (time - mLastStoppedTime.get() >= ACTIVITY_DELAY)) - open fun fetchSession(): InternalSession { - return session - } + open fun fetchSession(): InternalSession = session - fun endSession() { - Logger.debug("Ended session") - mMessageManager?.endSession(session) - disableLocationTracking() - session = InternalSession() - val instance = MParticle.getInstance() - instance?.Internal()?.kitManager?.onSessionEnd() - InternalListenerManager.listener.onSessionUpdated(session) - } + fun endSession() { + Logger.debug("Ended session") + mMessageManager?.endSession(session) + disableLocationTracking() + session = InternalSession() + val instance = MParticle.getInstance() + instance?.Internal()?.kitManager?.onSessionEnd() + InternalListenerManager.listener.onSessionUpdated(session) + } - private fun disableLocationTracking() { - val editor = mPreferences.edit() - editor.remove(Constants.PrefKeys.LOCATION_PROVIDER) - .remove(Constants.PrefKeys.LOCATION_MINTIME) - .remove(Constants.PrefKeys.LOCATION_MINDISTANCE) - .apply() - val instance = MParticle.getInstance() - instance?.disableLocationTracking() - } + private fun disableLocationTracking() { + val editor = mPreferences.edit() + editor + .remove(Constants.PrefKeys.LOCATION_PROVIDER) + .remove(Constants.PrefKeys.LOCATION_MINTIME) + .remove(Constants.PrefKeys.LOCATION_MINDISTANCE) + .apply() + val instance = MParticle.getInstance() + instance?.disableLocationTracking() + } - fun startSession() { - session = InternalSession().start(mContext) - mLastStoppedTime = AtomicLong(time) - enableLocationTracking() - val instance = MParticle.getInstance() - instance?.Internal()?.kitManager?.onSessionStart() - } + fun startSession() { + session = InternalSession().start(mContext) + mLastStoppedTime = AtomicLong(time) + enableLocationTracking() + val instance = MParticle.getInstance() + instance?.Internal()?.kitManager?.onSessionStart() + } - fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) { - val instance = MParticle.getInstance() - instance?.Internal()?.kitManager?.onActivitySaveInstanceState(activity, outState) - } + fun onActivitySaveInstanceState( + activity: Activity?, + outState: Bundle?, + ) { + val instance = MParticle.getInstance() + instance?.Internal()?.kitManager?.onActivitySaveInstanceState(activity, outState) + } - fun onActivityDestroyed(activity: Activity?) { - val instance = MParticle.getInstance() - instance?.Internal()?.kitManager?.onActivityDestroyed(activity) - } + fun onActivityDestroyed(activity: Activity?) { + val instance = MParticle.getInstance() + instance?.Internal()?.kitManager?.onActivityDestroyed(activity) + } - internal class CheckAdIdRunnable(var configManager: ConfigManager?) : Runnable { - override fun run() { - val adIdInfo = - MPUtility.getAdIdInfo( - MParticle.getInstance()?.Internal()?.appStateManager?.mContext - ) - val currentAdId = - (if (adIdInfo == null) null else (if (adIdInfo.isLimitAdTrackingEnabled) null else adIdInfo.id)) - val previousAdId = configManager?.previousAdId - if (currentAdId != null && currentAdId != previousAdId) { - val instance = MParticle.getInstance() - if (instance != null) { - val user = instance.Identity().currentUser - if (user != null) { - instance.Identity().modify( - Builder(user) - .googleAdId(currentAdId, previousAdId) - .build() - ) - } else { - instance.Identity() - .addIdentityStateListener(object : SingleUserIdentificationCallback() { - override fun onUserFound(user: MParticleUser) { - instance.Identity().modify( - Builder(user) - .googleAdId(currentAdId, previousAdId) - .build() - ) - } - }) + internal class CheckAdIdRunnable( + var configManager: ConfigManager?, + ) : Runnable { + override fun run() { + val adIdInfo = + MPUtility.getAdIdInfo( + MParticle + .getInstance() + ?.Internal() + ?.appStateManager + ?.mContext, + ) + val currentAdId = + (if (adIdInfo == null) null else (if (adIdInfo.isLimitAdTrackingEnabled) null else adIdInfo.id)) + val previousAdId = configManager?.previousAdId + if (currentAdId != null && currentAdId != previousAdId) { + val instance = MParticle.getInstance() + if (instance != null) { + val user = instance.Identity().currentUser + if (user != null) { + instance.Identity().modify( + Builder(user) + .googleAdId(currentAdId, previousAdId) + .build(), + ) + } else { + instance + .Identity() + .addIdentityStateListener( + object : SingleUserIdentificationCallback() { + override fun onUserFound(user: MParticleUser) { + instance.Identity().modify( + Builder(user) + .googleAdId(currentAdId, previousAdId) + .build(), + ) + } + }, + ) + } } } } } - } - internal class Builder : IdentityApiRequest.Builder { - constructor(user: MParticleUser?) : super(user) + internal class Builder : IdentityApiRequest.Builder { + constructor(user: MParticleUser?) : super(user) - constructor() : super() + constructor() : super() - public override fun googleAdId( - newGoogleAdId: String?, - oldGoogleAdId: String? - ): IdentityApiRequest.Builder { - return super.googleAdId(newGoogleAdId, oldGoogleAdId) + public override fun googleAdId( + newGoogleAdId: String?, + oldGoogleAdId: String?, + ): IdentityApiRequest.Builder = super.googleAdId(newGoogleAdId, oldGoogleAdId) } - } - - companion object { - /** - * This boolean is important in determining if the app is running due to the user opening the app, - * or if we're running due to the reception of a Intent such as an FCM message. - */ - @JvmField - var mInitialized: Boolean = false - - const val ACTIVITY_DELAY: Long = 1000 - - /** - * Constants used by the messaging/push framework to describe the app state when various - * interactions occur (receive/show/tap). - */ - const val APP_STATE_FOREGROUND: String = "foreground" - const val APP_STATE_BACKGROUND: String = "background" - const val APP_STATE_NOTRUNNING: String = "not_running" - private fun getActivityName(activity: Activity?): String { - return activity?.javaClass?.canonicalName ?: "" + companion object { + /** + * This boolean is important in determining if the app is running due to the user opening the app, + * or if we're running due to the reception of a Intent such as an FCM message. + */ + @JvmField + var mInitialized: Boolean = false + + const val ACTIVITY_DELAY: Long = 1000 + + /** + * Constants used by the messaging/push framework to describe the app state when various + * interactions occur (receive/show/tap). + */ + const val APP_STATE_FOREGROUND: String = "foreground" + const val APP_STATE_BACKGROUND: String = "background" + const val APP_STATE_NOTRUNNING: String = "not_running" + + private fun getActivityName(activity: Activity?): String = activity?.javaClass?.canonicalName ?: "" } } -} \ No newline at end of file diff --git a/android-core/src/main/kotlin/com/mparticle/internal/ApplicationContextWrapper.kt b/android-core/src/main/kotlin/com/mparticle/internal/ApplicationContextWrapper.kt index 906200147..b06efbfcb 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/ApplicationContextWrapper.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/ApplicationContextWrapper.kt @@ -16,13 +16,21 @@ import java.lang.ref.WeakReference import java.util.Collections import java.util.LinkedList -open class ApplicationContextWrapper(private val mBaseApplication: Application) : Application() { +open class ApplicationContextWrapper( + private val mBaseApplication: Application, +) : Application() { var isReplayActivityLifecycle: Boolean = true private var mRecord = true private var mActivityLifecycleCallbackRecorder: ActivityLifecycleCallbackRecorder? enum class MethodType { - ON_CREATED, ON_STARTED, ON_RESUMED, ON_PAUSED, ON_STOPPED, ON_SAVE_INSTANCE_STATE, ON_DESTROYED + ON_CREATED, + ON_STARTED, + ON_RESUMED, + ON_PAUSED, + ON_STOPPED, + ON_SAVE_INSTANCE_STATE, + ON_DESTROYED, } init { @@ -89,7 +97,7 @@ open class ApplicationContextWrapper(private val mBaseApplication: Application) @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) fun registerActivityLifecycleCallbacks( callback: ActivityLifecycleCallbacks, - unitTesting: Boolean + unitTesting: Boolean, ) { mBaseApplication.registerActivityLifecycleCallbacks(callback) val runnable = ReplayLifecycleCallbacksRunnable(callback) @@ -103,9 +111,7 @@ open class ApplicationContextWrapper(private val mBaseApplication: Application) } } - override fun getApplicationContext(): Context { - return this - } + override fun getApplicationContext(): Context = this @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) override fun unregisterActivityLifecycleCallbacks(callback: ActivityLifecycleCallbacks) { @@ -122,17 +128,11 @@ open class ApplicationContextWrapper(private val mBaseApplication: Application) mBaseApplication.unregisterOnProvideAssistDataListener(callback) } - override fun hashCode(): Int { - return mBaseApplication.hashCode() - } + override fun hashCode(): Int = mBaseApplication.hashCode() - override fun equals(obj: Any?): Boolean { - return mBaseApplication == obj - } + override fun equals(obj: Any?): Boolean = mBaseApplication == obj - override fun toString(): String { - return mBaseApplication.toString() - } + override fun toString(): String = mBaseApplication.toString() @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private fun startRecordLifecycles() { @@ -150,18 +150,14 @@ open class ApplicationContextWrapper(private val mBaseApplication: Application) fun getLifeCycleEventInstance( methodType: MethodType, - activityRef: WeakReference? - ): LifeCycleEvent { - return LifeCycleEvent(methodType, activityRef) - } + activityRef: WeakReference?, + ): LifeCycleEvent = LifeCycleEvent(methodType, activityRef) fun getLifeCycleEventInstance( methodType: MethodType, activityRef: WeakReference?, - bundle: Bundle? - ): LifeCycleEvent { - return LifeCycleEvent(methodType, activityRef, bundle) - } + bundle: Bundle?, + ): LifeCycleEvent = LifeCycleEvent(methodType, activityRef, bundle) @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) inner class ActivityLifecycleCallbackRecorder : ActivityLifecycleCallbacks { @@ -169,13 +165,16 @@ open class ApplicationContextWrapper(private val mBaseApplication: Application) Collections.synchronizedList(LinkedList()) val MAX_LIST_SIZE: Int = 10 - override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { + override fun onActivityCreated( + activity: Activity, + savedInstanceState: Bundle?, + ) { recordedLifecycleList.add( LifeCycleEvent( MethodType.ON_CREATED, WeakReference(activity), - savedInstanceState - ) + savedInstanceState, + ), ) } @@ -183,8 +182,8 @@ open class ApplicationContextWrapper(private val mBaseApplication: Application) recordedLifecycleList.add( LifeCycleEvent( MethodType.ON_STARTED, - WeakReference(activity) - ) + WeakReference(activity), + ), ) } @@ -192,8 +191,8 @@ open class ApplicationContextWrapper(private val mBaseApplication: Application) recordedLifecycleList.add( LifeCycleEvent( MethodType.ON_RESUMED, - WeakReference(activity) - ) + WeakReference(activity), + ), ) } @@ -205,18 +204,21 @@ open class ApplicationContextWrapper(private val mBaseApplication: Application) recordedLifecycleList.add( LifeCycleEvent( MethodType.ON_STOPPED, - WeakReference(activity) - ) + WeakReference(activity), + ), ) } - override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) { + override fun onActivitySaveInstanceState( + activity: Activity, + outState: Bundle, + ) { recordedLifecycleList.add( LifeCycleEvent( MethodType.ON_SAVE_INSTANCE_STATE, WeakReference(activity), - outState - ) + outState, + ), ) } @@ -224,8 +226,8 @@ open class ApplicationContextWrapper(private val mBaseApplication: Application) recordedLifecycleList.add( LifeCycleEvent( MethodType.ON_DESTROYED, - WeakReference(activity) - ) + WeakReference(activity), + ), ) } @@ -251,11 +253,11 @@ open class ApplicationContextWrapper(private val mBaseApplication: Application) inner class LifeCycleEvent( val methodType: MethodType, val activityRef: WeakReference?, - val bundle: Bundle? + val bundle: Bundle?, ) { constructor( methodType: MethodType, - activityRef: WeakReference? + activityRef: WeakReference?, ) : this(methodType, activityRef, null) override fun equals(o: Any?): Boolean { @@ -273,17 +275,22 @@ open class ApplicationContextWrapper(private val mBaseApplication: Application) } } - internal inner class ReplayLifecycleCallbacksRunnable(var callback: ActivityLifecycleCallbacks) : - Runnable { + internal inner class ReplayLifecycleCallbacksRunnable( + var callback: ActivityLifecycleCallbacks, + ) : Runnable { @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) override fun run() { if (callback != null && mActivityLifecycleCallbackRecorder != null && isReplayActivityLifecycle) { - val reference = if (MParticle.getInstance()?.Internal()?.kitManager == null - ) { - null - } else { - MParticle.getInstance()?.Internal()?.kitManager?.currentActivity - } + val reference = + if (MParticle.getInstance()?.Internal()?.kitManager == null) { + null + } else { + MParticle + .getInstance() + ?.Internal() + ?.kitManager + ?.currentActivity + } if (reference != null) { val currentActivity = reference.get() if (currentActivity != null) { @@ -301,7 +308,7 @@ open class ApplicationContextWrapper(private val mBaseApplication: Application) Logger.debug("Forwarding OnCreate") callback.onActivityCreated( recordedActivity, - lifeCycleEvent.bundle + lifeCycleEvent.bundle, ) } @@ -325,7 +332,7 @@ open class ApplicationContextWrapper(private val mBaseApplication: Application) lifeCycleEvent.bundle?.let { callback.onActivitySaveInstanceState( recordedActivity, - it + it, ) } } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/BatchId.kt b/android-core/src/main/kotlin/com/mparticle/internal/BatchId.kt index 6ceb66b93..fd4be134e 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/BatchId.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/BatchId.kt @@ -34,11 +34,7 @@ class BatchId { return true } - override fun hashCode(): Int { - return fields().contentHashCode() - } + override fun hashCode(): Int = fields().contentHashCode() - private fun fields(): Array { - return arrayOf(mpid, sessionId, dataplanId, dataplanVersion) - } -} \ No newline at end of file + private fun fields(): Array = arrayOf(mpid, sessionId, dataplanId, dataplanVersion) +} diff --git a/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt b/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt index af8c78f67..6f5916339 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt @@ -38,134 +38,139 @@ object Constants { const val LIMIT_MAX_MESSAGE_SIZE: Int = 100 * 1024 const val LIMIT_MAX_UPLOAD_SIZE: Int = 2 * LIMIT_MAX_MESSAGE_SIZE - const val GODADDY_CLASS_2_ROOT_CRT: String = "-----BEGIN CERTIFICATE-----\n" + - "MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh\n" + - "MB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBE\n" + - "YWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3\n" + - "MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkGA1UEBhMCVVMxITAfBgNVBAoTGFRo\n" + - "ZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28gRGFkZHkgQ2xhc3Mg\n" + - "MiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQADggEN\n" + - "ADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCA\n" + - "PVYYYwhv2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6w\n" + - "wdhFJ2+qN1j3hybX2C32qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXi\n" + - "EqITLdiOr18SPaAIBQi2XKVlOARFmR6jYGB0xUGlcmIbYsUfb18aQr4CUWWoriMY\n" + - "avx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmYvLEHZ6IVDd2gWMZEewo+\n" + - "YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0OBBYEFNLE\n" + - "sNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h\n" + - "/t2oatTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5\n" + - "IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmlj\n" + - "YXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQAD\n" + - "ggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wimPQoZ+YeAEW5p5JYXMP80kWNy\n" + - "OO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKtI3lpjbi2Tc7P\n" + - "TMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ\n" + - "HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mER\n" + - "dEr/VxqHD3VILs9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5Cuf\n" + - "ReYNnyicsbkqWletNw+vHX/bvZ8=\n" + + const val GODADDY_CLASS_2_ROOT_CRT: String = + "-----BEGIN CERTIFICATE-----\n" + "MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh\n" + "MB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBE\n" + "YWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3\n" + "MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkGA1UEBhMCVVMxITAfBgNVBAoTGFRo\n" + "ZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28gRGFkZHkgQ2xhc3Mg\n" + "MiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQADggEN\n" + "ADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCA\n" + "PVYYYwhv2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6w\n" + "wdhFJ2+qN1j3hybX2C32qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXi\n" + "EqITLdiOr18SPaAIBQi2XKVlOARFmR6jYGB0xUGlcmIbYsUfb18aQr4CUWWoriMY\n" + "avx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmYvLEHZ6IVDd2gWMZEewo+\n" + "YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0OBBYEFNLE\n" + "sNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h\n" + "/t2oatTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5\n" + "IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmlj\n" + "YXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQAD\n" + "ggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wimPQoZ+YeAEW5p5JYXMP80kWNy\n" + "OO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKtI3lpjbi2Tc7P\n" + "TMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ\n" + "HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mER\n" + "dEr/VxqHD3VILs9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5Cuf\n" + "ReYNnyicsbkqWletNw+vHX/bvZ8=\n" "-----END CERTIFICATE-----" - const val GODADDY_ROOT_G2_CRT: String = "-----BEGIN CERTIFICATE-----\n" + - "MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx\n" + - "EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT\n" + - "EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp\n" + - "ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz\n" + - "NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH\n" + - "EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE\n" + - "AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw\n" + - "DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD\n" + - "E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH\n" + - "/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy\n" + - "DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh\n" + - "GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR\n" + - "tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA\n" + - "AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE\n" + - "FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX\n" + - "WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu\n" + - "9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr\n" + - "gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo\n" + - "2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO\n" + - "LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI\n" + - "4uJEvlz36hz1\n" + + const val GODADDY_ROOT_G2_CRT: String = + "-----BEGIN CERTIFICATE-----\n" + "MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx\n" + "EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT\n" + "EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp\n" + "ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz\n" + "NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH\n" + "EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE\n" + "AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw\n" + "DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD\n" + "E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH\n" + "/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy\n" + "DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh\n" + "GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR\n" + "tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA\n" + "AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE\n" + "FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX\n" + "WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu\n" + "9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr\n" + "gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo\n" + "2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO\n" + "LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI\n" + "4uJEvlz36hz1\n" "-----END CERTIFICATE-----" - const val LETS_ENCRYPTS_ROOT_X1_CRT: String = "-----BEGIN CERTIFICATE-----\n" + - "MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n" + - "TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n" + - "cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n" + - "WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n" + - "ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n" + - "MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n" + - "h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n" + - "0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n" + - "A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n" + - "T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n" + - "B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\n" + - "B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\n" + - "KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\n" + - "OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\n" + - "jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\n" + - "qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\n" + - "rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n" + - "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\n" + - "hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\n" + - "ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n" + - "3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n" + - "NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n" + - "ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n" + - "TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n" + - "jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n" + - "oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n" + - "4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n" + - "mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n" + - "emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n" + + const val LETS_ENCRYPTS_ROOT_X1_CRT: String = + "-----BEGIN CERTIFICATE-----\n" + "MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n" + "TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n" + "cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n" + "WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n" + "ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n" + "MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n" + "h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n" + "0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n" + "A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n" + "T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n" + "B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\n" + "B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\n" + "KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\n" + "OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\n" + "jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\n" + "qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\n" + "rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n" + "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\n" + "hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\n" + "ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n" + "3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n" + "NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n" + "ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n" + "TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n" + "jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n" + "oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n" + "4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n" + "mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n" + "emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n" "-----END CERTIFICATE-----" - const val LETS_ENCRYPTS_ROOT_X2_SELF_SIGN_CRT: String = "-----BEGIN CERTIFICATE-----\n" + - "MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw\n" + - "CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg\n" + - "R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00\n" + - "MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT\n" + - "ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw\n" + - "EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW\n" + - "+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9\n" + - "ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T\n" + - "AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI\n" + - "zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW\n" + - "tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1\n" + - "/q4AaOeMSQ+2b1tbFfLn\n" + + const val LETS_ENCRYPTS_ROOT_X2_SELF_SIGN_CRT: String = + "-----BEGIN CERTIFICATE-----\n" + "MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw\n" + "CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg\n" + "R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00\n" + "MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT\n" + "ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw\n" + "EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW\n" + "+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9\n" + "ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T\n" + "AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI\n" + "zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW\n" + "tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1\n" + "/q4AaOeMSQ+2b1tbFfLn\n" "-----END CERTIFICATE-----" - const val LETS_ENCRYPTS_ROOT_X2_CROSS_SIGN_CRT: String = "-----BEGIN CERTIFICATE-----\n" + - "MIIEYDCCAkigAwIBAgIQB55JKIY3b9QISMI/xjHkYzANBgkqhkiG9w0BAQsFADBP\n" + - "MQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFy\n" + - "Y2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTAeFw0yMDA5MDQwMDAwMDBa\n" + - "Fw0yNTA5MTUxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5l\n" + - "dCBTZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgy\n" + - "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0H\n" + - "ttwW+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7\n" + - "AlF9ItgKbppbd9/w+kHsOdx1ymgHDB/qo4HlMIHiMA4GA1UdDwEB/wQEAwIBBjAP\n" + - "BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR8Qpau3ktIO/qS+J6Mz22LqXI3lTAf\n" + - "BgNVHSMEGDAWgBR5tFnme7bl5AFzgAiIyBpY9umbbjAyBggrBgEFBQcBAQQmMCQw\n" + - "IgYIKwYBBQUHMAKGFmh0dHA6Ly94MS5pLmxlbmNyLm9yZy8wJwYDVR0fBCAwHjAc\n" + - "oBqgGIYWaHR0cDovL3gxLmMubGVuY3Iub3JnLzAiBgNVHSAEGzAZMAgGBmeBDAEC\n" + - "ATANBgsrBgEEAYLfEwEBATANBgkqhkiG9w0BAQsFAAOCAgEAG38lK5B6CHYAdxjh\n" + - "wy6KNkxBfr8XS+Mw11sMfpyWmG97sGjAJETM4vL80erb0p8B+RdNDJ1V/aWtbdIv\n" + - "P0tywC6uc8clFlfCPhWt4DHRCoSEbGJ4QjEiRhrtekC/lxaBRHfKbHtdIVwH8hGR\n" + - "Ib/hL8Lvbv0FIOS093nzLbs3KvDGsaysUfUfs1oeZs5YBxg4f3GpPIO617yCnpp2\n" + - "D56wKf3L84kHSBv+q5MuFCENX6+Ot1SrXQ7UW0xx0JLqPaM2m3wf4DtVudhTU8yD\n" + - "ZrtK3IEGABiL9LPXSLETQbnEtp7PLHeOQiALgH6fxatI27xvBI1sRikCDXCKHfES\n" + - "c7ZGJEKeKhcY46zHmMJyzG0tdm3dLCsmlqXPIQgb5dovy++fc5Ou+DZfR4+XKM6r\n" + - "4pgmmIv97igyIintTJUJxCD6B+GGLET2gUfA5GIy7R3YPEiIlsNekbave1mk7uOG\n" + - "nMeIWMooKmZVm4WAuR3YQCvJHBM8qevemcIWQPb1pK4qJWxSuscETLQyu/w4XKAM\n" + - "YXtX7HdOUM+vBqIPN4zhDtLTLxq9nHE+zOH40aijvQT2GcD5hq/1DhqqlWvvykdx\n" + - "S2McTZbbVSMKnQ+BdaDmQPVkRgNuzvpqfQbspDQGdNpT2Lm4xiN9qfgqLaSCpi4t\n" + - "EcrmzTFYeYXmchynn9NM0GbQp7s=\n" + + const val LETS_ENCRYPTS_ROOT_X2_CROSS_SIGN_CRT: String = + "-----BEGIN CERTIFICATE-----\n" + "MIIEYDCCAkigAwIBAgIQB55JKIY3b9QISMI/xjHkYzANBgkqhkiG9w0BAQsFADBP\n" + "MQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFy\n" + "Y2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTAeFw0yMDA5MDQwMDAwMDBa\n" + "Fw0yNTA5MTUxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5l\n" + "dCBTZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgy\n" + "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0H\n" + "ttwW+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7\n" + "AlF9ItgKbppbd9/w+kHsOdx1ymgHDB/qo4HlMIHiMA4GA1UdDwEB/wQEAwIBBjAP\n" + "BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR8Qpau3ktIO/qS+J6Mz22LqXI3lTAf\n" + "BgNVHSMEGDAWgBR5tFnme7bl5AFzgAiIyBpY9umbbjAyBggrBgEFBQcBAQQmMCQw\n" + "IgYIKwYBBQUHMAKGFmh0dHA6Ly94MS5pLmxlbmNyLm9yZy8wJwYDVR0fBCAwHjAc\n" + "oBqgGIYWaHR0cDovL3gxLmMubGVuY3Iub3JnLzAiBgNVHSAEGzAZMAgGBmeBDAEC\n" + "ATANBgsrBgEEAYLfEwEBATANBgkqhkiG9w0BAQsFAAOCAgEAG38lK5B6CHYAdxjh\n" + "wy6KNkxBfr8XS+Mw11sMfpyWmG97sGjAJETM4vL80erb0p8B+RdNDJ1V/aWtbdIv\n" + "P0tywC6uc8clFlfCPhWt4DHRCoSEbGJ4QjEiRhrtekC/lxaBRHfKbHtdIVwH8hGR\n" + "Ib/hL8Lvbv0FIOS093nzLbs3KvDGsaysUfUfs1oeZs5YBxg4f3GpPIO617yCnpp2\n" + "D56wKf3L84kHSBv+q5MuFCENX6+Ot1SrXQ7UW0xx0JLqPaM2m3wf4DtVudhTU8yD\n" + "ZrtK3IEGABiL9LPXSLETQbnEtp7PLHeOQiALgH6fxatI27xvBI1sRikCDXCKHfES\n" + "c7ZGJEKeKhcY46zHmMJyzG0tdm3dLCsmlqXPIQgb5dovy++fc5Ou+DZfR4+XKM6r\n" + "4pgmmIv97igyIintTJUJxCD6B+GGLET2gUfA5GIy7R3YPEiIlsNekbave1mk7uOG\n" + "nMeIWMooKmZVm4WAuR3YQCvJHBM8qevemcIWQPb1pK4qJWxSuscETLQyu/w4XKAM\n" + "YXtX7HdOUM+vBqIPN4zhDtLTLxq9nHE+zOH40aijvQT2GcD5hq/1DhqqlWvvykdx\n" + "S2McTZbbVSMKnQ+BdaDmQPVkRgNuzvpqfQbspDQGdNpT2Lm4xiN9qfgqLaSCpi4t\n" + "EcrmzTFYeYXmchynn9NM0GbQp7s=\n" "-----END CERTIFICATE-----" - //wait 5 seconds to trigger an immediate upload in the case where multiple trigger-messages are logged - //in quick succession. + // wait 5 seconds to trigger an immediate upload in the case where multiple trigger-messages are logged + // in quick succession. const val TRIGGER_MESSAGE_DELAY: Long = 5000 - //special session id for messages logged without a session + // special session id for messages logged without a session const val NO_SESSION_ID: String = "NO-SESSION" const val REFERRER: String = "referrer" const val GOOGLE_GCM: String = "google" @@ -329,7 +334,7 @@ object Constants { const val STATE_INFO_MEMORY_LOW: String = "sml" const val STATE_INFO_MEMORY_THRESHOLD: String = "smt" - //app init message special keys + // app init message special keys const val APP_INIT_CRASHED: String = "sc" const val APP_INIT_FIRST_RUN: String = "ifr" const val APP_INIT_UPGRADE: String = "iu" @@ -368,7 +373,7 @@ object Constants { const val PUSH_REGISTER_FLAG: String = "r" const val APP_STATE: String = "as" - //state transition + // state transition const val STATE_TRANSITION_TYPE: String = "t" const val CURRENT_ACTIVITY: String = "cn" const val PAYLOAD: String = "pay" @@ -378,7 +383,6 @@ object Constants { const val PUSH_ACTION_NAME: String = "an" const val CONTENT_ID: String = "content_id" - const val ST_LAUNCH_REFERRER: String = "lr" const val ST_LAUNCH_PARAMS: String = "lpr" const val ST_LAUNCH_SOURCE_PACKAGE: String = "srp" @@ -386,14 +390,14 @@ object Constants { const val ST_LAUNCH_TIME_SUSPENDED: String = "tls" const val ST_INTERRUPTIONS: String = "nsi" - //screen view + // screen view const val SCREEN_STARTED: String = "t" const val BREADCRUMB_SESSION_COUNTER: String = "sn" const val BREADCRUMB_LABEL: String = "l" const val PROVIDER_PERSISTENCE: String = "cms" const val RELEASE_VERSION: String = "vr" - //network performance monitoring + // network performance monitoring const val NPE_METHOD: String = "v" const val NPE_URL: String = "url" const val NPE_LENGTH: String = "te" @@ -403,16 +407,16 @@ object Constants { const val CONFIG_SESSION_TIMEOUT: String = "stl" const val CONFIG_UPLOAD_INTERVAL: String = "uitl" - //events + // events const val EVENT_COUNTER: String = "en" const val EVENT_CATEGORY: String = "\$Category" - //session start + // session start const val PREVIOUS_SESSION_ID: String = "pid" const val PREVIOUS_SESSION_START: String = "pss" // https://go.mparticle.com/work/SQDSDKS-6814 - //sandbox mode is deprecated as of > 1.6.3 + // sandbox mode is deprecated as of > 1.6.3 const val SANDBOX: String = "dbg" const val ENVIRONMENT: String = "env" const val RESERVED_KEY_LTV: String = "\$Amount" @@ -423,7 +427,7 @@ object Constants { const val PUSH_CAMPAIGN_HISTORY_TIMESTAMP: String = "ts" const val STATE_INFO_NETWORK_TYPE: String = "ant" - //identity + // identity const val MPID: String = "mpid" const val EVENT_FLAGS: String = "flags" const val INTEGRATION_ATTRIBUTES: String = "ia" @@ -437,7 +441,7 @@ object Constants { const val DEVICE_IS_IN_DST: String = "idst" const val DEVICE_APPLICATION_STAMP: String = "das" - //consent state + // consent state const val CONSENT_STATE: String = "con" const val CONSENT_STATE_GDPR: String = "gdpr" const val CONSENT_STATE_CCPA: String = "ccpa" @@ -448,7 +452,7 @@ object Constants { const val CONSENT_STATE_HARDWARE_ID: String = "h" const val CCPA_CONSENT_KEY: String = "data_sale_opt_out" - //alias request + // alias request const val SOURCE_MPID: String = "source_mpid" const val DESTINATION_MPID: String = "destination_mpid" const val START_TIME: String = "start_unixtime_ms" @@ -461,10 +465,10 @@ object Constants { const val DATA: String = "data" const val ALIAS_REQUEST_TYPE: String = "alias" - //batch was mutated + // batch was mutated const val MODIFIED_BATCH: String = "mb" - //Sandbox mode for Rokt + // Sandbox mode for Rokt const val SANDBOX_MODE_ROKT: String = "sandbox" } } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/CoreCallbacks.kt b/android-core/src/main/kotlin/com/mparticle/internal/CoreCallbacks.kt index a84fc5328..ba822656d 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/CoreCallbacks.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/CoreCallbacks.kt @@ -14,7 +14,10 @@ interface CoreCallbacks { fun isEnabled(): Boolean - fun setIntegrationAttributes(kitId: Int, integrationAttributes: Map) + fun setIntegrationAttributes( + kitId: Int, + integrationAttributes: Map, + ) fun getIntegrationAttributes(kitId: Int): Map? @@ -40,24 +43,62 @@ interface CoreCallbacks { interface KitListener { fun kitFound(kitId: Int) - fun kitConfigReceived(kitId: Int, configuration: String?) + fun kitConfigReceived( + kitId: Int, + configuration: String?, + ) - fun kitExcluded(kitId: Int, reason: String?) + fun kitExcluded( + kitId: Int, + reason: String?, + ) fun kitStarted(kitId: Int) - fun onKitApiCalled(kitId: Int, used: Boolean?, vararg objects: Any?) - fun onKitApiCalled(methodName: String?, kitId: Int, used: Boolean?, vararg objects: Any?) + + fun onKitApiCalled( + kitId: Int, + used: Boolean?, + vararg objects: Any?, + ) + + fun onKitApiCalled( + methodName: String?, + kitId: Int, + used: Boolean?, + vararg objects: Any?, + ) companion object { @JvmField - val EMPTY: KitListener = object : KitListener { - override fun kitFound(kitId: Int) {} - override fun kitConfigReceived(kitId: Int, configuration: String?) {} - override fun kitExcluded(kitId: Int, reason: String?) {} - override fun kitStarted(kitId: Int) {} - override fun onKitApiCalled(kitId: Int, used: Boolean?, vararg objects: Any?) {} - override fun onKitApiCalled(methodName: String?, kitId: Int, used: Boolean?, vararg objects: Any?) {} - } + val EMPTY: KitListener = + object : KitListener { + override fun kitFound(kitId: Int) {} + + override fun kitConfigReceived( + kitId: Int, + configuration: String?, + ) {} + + override fun kitExcluded( + kitId: Int, + reason: String?, + ) {} + + override fun kitStarted(kitId: Int) {} + + override fun onKitApiCalled( + kitId: Int, + used: Boolean?, + vararg objects: Any?, + ) {} + + override fun onKitApiCalled( + methodName: String?, + kitId: Int, + used: Boolean?, + vararg objects: Any?, + ) {} + } } } -} \ No newline at end of file +} diff --git a/android-core/src/main/kotlin/com/mparticle/internal/JellybeanHelper.kt b/android-core/src/main/kotlin/com/mparticle/internal/JellybeanHelper.kt index e5ba6e641..6cefa16d4 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/JellybeanHelper.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/JellybeanHelper.kt @@ -17,7 +17,7 @@ object JellybeanHelper { return stat.availableBlocksLong * stat.blockSizeLong } } catch (e: Exception) { - //For some reason, it appears some devices even in jelly bean don't have this method. + // For some reason, it appears some devices even in jelly bean don't have this method. } return 0 diff --git a/android-core/src/main/kotlin/com/mparticle/internal/KitKatHelper.kt b/android-core/src/main/kotlin/com/mparticle/internal/KitKatHelper.kt index 07fdbf11e..2d86dd132 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/KitKatHelper.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/KitKatHelper.kt @@ -11,7 +11,10 @@ import org.json.JSONArray @TargetApi(19) object KitKatHelper { @JvmStatic - fun remove(array: JSONArray, index: Int) { + fun remove( + array: JSONArray, + index: Int, + ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { array.remove(index) } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/MPLifecycleCallbackDelegate.kt b/android-core/src/main/kotlin/com/mparticle/internal/MPLifecycleCallbackDelegate.kt index 2289628e5..27e81638d 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/MPLifecycleCallbackDelegate.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/MPLifecycleCallbackDelegate.kt @@ -12,9 +12,13 @@ import android.os.Bundle * Separated into its own class to avoid annoying logcat messages on pre-ICS devices. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) -internal class MPLifecycleCallbackDelegate(private val mStateManager: AppStateManager) : - ActivityLifecycleCallbacks { - override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { +internal class MPLifecycleCallbackDelegate( + private val mStateManager: AppStateManager, +) : ActivityLifecycleCallbacks { + override fun onActivityCreated( + activity: Activity, + savedInstanceState: Bundle?, + ) { mStateManager.onActivityCreated(activity, savedInstanceState) } @@ -34,7 +38,10 @@ internal class MPLifecycleCallbackDelegate(private val mStateManager: AppStateMa mStateManager.onActivityStopped(activity) } - override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) { + override fun onActivitySaveInstanceState( + activity: Activity, + outState: Bundle, + ) { mStateManager.onActivitySaveInstanceState(activity, outState) } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/MPLocationListener.kt b/android-core/src/main/kotlin/com/mparticle/internal/MPLocationListener.kt index 3e46250c9..ae0259ac9 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/MPLocationListener.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/MPLocationListener.kt @@ -5,12 +5,18 @@ import android.location.LocationListener import android.os.Bundle import com.mparticle.MParticle -class MPLocationListener(private val mParticle: MParticle) : LocationListener { +class MPLocationListener( + private val mParticle: MParticle, +) : LocationListener { override fun onLocationChanged(location: Location) { mParticle.setLocation(location) } - override fun onStatusChanged(provider: String, status: Int, extras: Bundle) { + override fun onStatusChanged( + provider: String, + status: Int, + extras: Bundle, + ) { } override fun onProviderEnabled(provider: String) { diff --git a/android-core/src/main/kotlin/com/mparticle/internal/SideloadedKit.kt b/android-core/src/main/kotlin/com/mparticle/internal/SideloadedKit.kt index 54021580d..04038862f 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/SideloadedKit.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/SideloadedKit.kt @@ -3,7 +3,6 @@ package com.mparticle.internal import org.json.JSONObject interface SideloadedKit { - fun getJsonConfig(): JSONObject? fun kitId(): Int diff --git a/android-core/src/main/kotlin/com/mparticle/internal/UserStorage.kt b/android-core/src/main/kotlin/com/mparticle/internal/UserStorage.kt index 4db47e7f8..91bde6d3f 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/UserStorage.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/UserStorage.kt @@ -11,16 +11,25 @@ import org.json.JSONObject import java.util.TreeSet import java.util.UUID -class UserStorage private constructor(private val mContext: Context, val mpid: Long) { +class UserStorage private constructor( + private val mContext: Context, + val mpid: Long, +) { private val mPreferences: SharedPreferences var messageManagerSharedPreferences: SharedPreferences - fun deleteUserConfig(context: Context, mpId: Long): Boolean { + fun deleteUserConfig( + context: Context, + mpId: Long, + ): Boolean { if (Build.VERSION.SDK_INT >= 24) { context.deleteSharedPreferences(getFileName(mpId)) } else { - context.getSharedPreferences(getFileName(mpId), Context.MODE_PRIVATE).edit().clear() + context + .getSharedPreferences(getFileName(mpId), Context.MODE_PRIVATE) + .edit() + .clear() .apply() } return removeMpId(context, mpId) @@ -43,13 +52,9 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L mPreferences.edit().putInt(SESSION_COUNTER, sessionCounter).apply() } - fun getCurrentSessionCounter(defaultValue: Int): Int { - return mPreferences.getInt(SESSION_COUNTER, defaultValue) - } + fun getCurrentSessionCounter(defaultValue: Int): Int = mPreferences.getInt(SESSION_COUNTER, defaultValue) - private fun hasCurrentSessionCounter(): Boolean { - return mPreferences.contains(SESSION_COUNTER) - } + private fun hasCurrentSessionCounter(): Boolean = mPreferences.contains(SESSION_COUNTER) fun incrementSessionCounter() { var nextCount = currentSessionCounter + 1 @@ -59,7 +64,6 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L mPreferences.edit().putInt(SESSION_COUNTER, nextCount).apply() } - var deletedUserAttributes: String? get() = mPreferences.getString(DELETED_USER_ATTRS, null) set(deletedUserAttributes) { @@ -70,9 +74,7 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L mPreferences.edit().putString(DELETED_USER_ATTRS, null).apply() } - private fun hasDeletedUserAttributes(): Boolean { - return mPreferences.contains(DELETED_USER_ATTRS) - } + private fun hasDeletedUserAttributes(): Boolean = mPreferences.contains(DELETED_USER_ATTRS) var breadcrumbLimit: Int get() { @@ -85,9 +87,7 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L mPreferences.edit().putInt(BREADCRUMB_LIMIT, newLimit).apply() } - private fun hasBreadcrumbLimit(): Boolean { - return mPreferences.contains(BREADCRUMB_LIMIT) - } + private fun hasBreadcrumbLimit(): Boolean = mPreferences.contains(BREADCRUMB_LIMIT) var lastUseDate: Long get() = getLastUseDate(0) @@ -95,20 +95,14 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L mPreferences.edit().putLong(LAST_USE, lastUseDate).apply() } - fun getLastUseDate(defaultValue: Long): Long { - return mPreferences.getLong(LAST_USE, defaultValue) - } + fun getLastUseDate(defaultValue: Long): Long = mPreferences.getLong(LAST_USE, defaultValue) - private fun hasLastUserDate(): Boolean { - return mPreferences.contains(LAST_USE) - } + private fun hasLastUserDate(): Boolean = mPreferences.contains(LAST_USE) val previousSessionForegound: Long get() = getPreviousSessionForegound(-1) - fun getPreviousSessionForegound(defaultValue: Long): Long { - return mPreferences.getLong(PREVIOUS_SESSION_FOREGROUND, defaultValue) - } + fun getPreviousSessionForegound(defaultValue: Long): Long = mPreferences.getLong(PREVIOUS_SESSION_FOREGROUND, defaultValue) fun clearPreviousTimeInForeground() { mPreferences.edit().putLong(PREVIOUS_SESSION_FOREGROUND, -1).apply() @@ -118,9 +112,7 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L mPreferences.edit().putLong(PREVIOUS_SESSION_FOREGROUND, previousTimeInForeground).apply() } - private fun hasPreviousSessionForegound(): Boolean { - return mPreferences.contains(PREVIOUS_SESSION_FOREGROUND) - } + private fun hasPreviousSessionForegound(): Boolean = mPreferences.contains(PREVIOUS_SESSION_FOREGROUND) var previousSessionId: String? get() = getPreviousSessionId("") @@ -128,25 +120,17 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L mPreferences.edit().putString(PREVIOUS_SESSION_ID, previousSessionId).apply() } - fun getPreviousSessionId(defaultValue: String?): String? { - return mPreferences.getString(PREVIOUS_SESSION_ID, defaultValue) - } + fun getPreviousSessionId(defaultValue: String?): String? = mPreferences.getString(PREVIOUS_SESSION_ID, defaultValue) - private fun hasPreviousSessionId(): Boolean { - return mPreferences.contains(PREVIOUS_SESSION_ID) - } + private fun hasPreviousSessionId(): Boolean = mPreferences.contains(PREVIOUS_SESSION_ID) - fun getPreviousSessionStart(defaultValue: Long): Long { - return mPreferences.getLong(PREVIOUS_SESSION_START, defaultValue) - } + fun getPreviousSessionStart(defaultValue: Long): Long = mPreferences.getLong(PREVIOUS_SESSION_START, defaultValue) fun setPreviousSessionStart(previousSessionStart: Long) { mPreferences.edit().putLong(PREVIOUS_SESSION_START, previousSessionStart).apply() } - private fun hasPreviousSessionStart(): Boolean { - return mPreferences.contains(PREVIOUS_SESSION_START) - } + private fun hasPreviousSessionStart(): Boolean = mPreferences.contains(PREVIOUS_SESSION_START) var ltv: String? get() = mPreferences.getString(LTV, "0") @@ -154,21 +138,15 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L mPreferences.edit().putString(LTV, ltv).apply() } - private fun hasLtv(): Boolean { - return mPreferences.contains(LTV) - } + private fun hasLtv(): Boolean = mPreferences.contains(LTV) - fun getTotalRuns(defaultValue: Int): Int { - return mPreferences.getInt(TOTAL_RUNS, defaultValue) - } + fun getTotalRuns(defaultValue: Int): Int = mPreferences.getInt(TOTAL_RUNS, defaultValue) fun setTotalRuns(totalRuns: Int) { mPreferences.edit().putInt(TOTAL_RUNS, totalRuns).apply() } - private fun hasTotalRuns(): Boolean { - return mPreferences.contains(TOTAL_RUNS) - } + private fun hasTotalRuns(): Boolean = mPreferences.contains(TOTAL_RUNS) var cookies: String? get() = mPreferences.getString(COOKIES, "") @@ -176,9 +154,7 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L mPreferences.edit().putString(COOKIES, cookies).apply() } - private fun hasCookies(): Boolean { - return mPreferences.contains(COOKIES) - } + private fun hasCookies(): Boolean = mPreferences.contains(COOKIES) var launchesSinceUpgrade: Int get() = mPreferences.getInt(TOTAL_SINCE_UPGRADE, 0) @@ -186,9 +162,7 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L mPreferences.edit().putInt(TOTAL_SINCE_UPGRADE, launchesSinceUpgrade).apply() } - private fun hasLaunchesSinceUpgrade(): Boolean { - return mPreferences.contains(TOTAL_SINCE_UPGRADE) - } + private fun hasLaunchesSinceUpgrade(): Boolean = mPreferences.contains(TOTAL_SINCE_UPGRADE) var userIdentities: String? get() = mPreferences.getString(USER_IDENTITIES, "") @@ -202,9 +176,7 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L mPreferences.edit().putString(CONSENT_STATE, consentState).apply() } - private fun hasConsent(): Boolean { - return mPreferences.contains(CONSENT_STATE) - } + private fun hasConsent(): Boolean = mPreferences.contains(CONSENT_STATE) val isLoggedIn: Boolean get() = mPreferences.getBoolean(KNOWN_USER, false) @@ -212,11 +184,15 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L var firstSeenTime: Long? get() { if (!mPreferences.contains(FIRST_SEEN_TIME)) { - mPreferences.edit().putLong( - FIRST_SEEN_TIME, messageManagerSharedPreferences.getLong( - Constants.PrefKeys.INSTALL_TIME, defaultSeenTime - ) - ).apply() + mPreferences + .edit() + .putLong( + FIRST_SEEN_TIME, + messageManagerSharedPreferences.getLong( + Constants.PrefKeys.INSTALL_TIME, + defaultSeenTime, + ), + ).apply() } return mPreferences.getLong(FIRST_SEEN_TIME, defaultSeenTime) } @@ -237,8 +213,8 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L time?.let { mPreferences.edit().putLong(LAST_SEEN_TIME, it).apply() } } - //Set a default "lastSeenTime" for migration to SDK versions with MParticleUser.getLastSeenTime(), - //where some users will not have a value for the field. + // Set a default "lastSeenTime" for migration to SDK versions with MParticleUser.getLastSeenTime(), + // where some users will not have a value for the field. private fun setDefaultSeenTime() { val preferences = getMParticleSharedPrefs(mContext) if (!preferences.contains(DEFAULT_SEEN_TIME)) { @@ -247,10 +223,11 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L } private val defaultSeenTime: Long - get() = getMParticleSharedPrefs(mContext).getLong( - DEFAULT_SEEN_TIME, - System.currentTimeMillis() - ) + get() = + getMParticleSharedPrefs(mContext).getLong( + DEFAULT_SEEN_TIME, + System.currentTimeMillis(), + ) fun getLastUploadSettings(): UploadSettings? { val lastUploadSettingsJson = mPreferences.getString(LAST_UPLOAD_SETTINGS, null) @@ -271,9 +248,7 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L mPreferences.edit().putBoolean(KNOWN_USER, knownUser).apply() } - private fun hasUserIdentities(): Boolean { - return mPreferences.contains(USER_IDENTITIES) - } + private fun hasUserIdentities(): Boolean = mPreferences.contains(USER_IDENTITIES) private fun getPreferenceFile(mpId: Long): SharedPreferences { val mpIds = getMpIdSet(mContext) @@ -341,7 +316,9 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L * process will associate all current values covered by UserStorage to the current MPID, which should * be passed into the parameter "currentMpId". */ - private class SharedPreferencesMigrator(context: Context) { + private class SharedPreferencesMigrator( + context: Context, + ) { private val messageManagerSharedPreferences: SharedPreferences = context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE) private val configManagerSharedPreferences: SharedPreferences = @@ -403,7 +380,7 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L userStorage.setTotalRuns(totalRuns) } - //migrate both cookies and device application stamp + // migrate both cookies and device application stamp val cookies: String? = cookies var das: String? = null if (cookies != null) { @@ -432,75 +409,85 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L userStorage.userIdentities = userIdentities } } catch (ex: Exception) { - //do nothing + // do nothing } } val currentSessionCounter: Int - get() = messageManagerSharedPreferences.getInt( - LegacySharedPreferencesKeys.SESSION_COUNTER, - 0 - ) + get() = + messageManagerSharedPreferences.getInt( + LegacySharedPreferencesKeys.SESSION_COUNTER, + 0, + ) val getDeletedUserAttributes: String? - get() = messageManagerSharedPreferences.getString( - LegacySharedPreferencesKeys.DELETED_USER_ATTRS + apiKey, - null - ) + get() = + messageManagerSharedPreferences.getString( + LegacySharedPreferencesKeys.DELETED_USER_ATTRS + apiKey, + null, + ) val breadcrumbLimit: Int - get() = configManagerSharedPreferences.getInt( - LegacySharedPreferencesKeys.BREADCRUMB_LIMIT, - 0 - ) + get() = + configManagerSharedPreferences.getInt( + LegacySharedPreferencesKeys.BREADCRUMB_LIMIT, + 0, + ) val lastUseDate: Long get() = messageManagerSharedPreferences.getLong(LegacySharedPreferencesKeys.LAST_USE, 0) val previousTimeInForeground: Long - get() = messageManagerSharedPreferences.getLong( - LegacySharedPreferencesKeys.PREVIOUS_SESSION_FOREGROUND, - 0 - ) + get() = + messageManagerSharedPreferences.getLong( + LegacySharedPreferencesKeys.PREVIOUS_SESSION_FOREGROUND, + 0, + ) val previousSessionId: String? - get() = messageManagerSharedPreferences.getString( - LegacySharedPreferencesKeys.PREVIOUS_SESSION_ID, - null - ) + get() = + messageManagerSharedPreferences.getString( + LegacySharedPreferencesKeys.PREVIOUS_SESSION_ID, + null, + ) val previousSessionStart: Long - get() = messageManagerSharedPreferences.getLong( - LegacySharedPreferencesKeys.PREVIOUS_SESSION_START, - 0 - ) + get() = + messageManagerSharedPreferences.getLong( + LegacySharedPreferencesKeys.PREVIOUS_SESSION_START, + 0, + ) val ltv: String? get() = messageManagerSharedPreferences.getString(LegacySharedPreferencesKeys.LTV, null) val totalRuns: Int - get() = messageManagerSharedPreferences.getInt( - LegacySharedPreferencesKeys.TOTAL_RUNS, - 0 - ) + get() = + messageManagerSharedPreferences.getInt( + LegacySharedPreferencesKeys.TOTAL_RUNS, + 0, + ) val cookies: String? - get() = configManagerSharedPreferences.getString( - LegacySharedPreferencesKeys.COOKIES, - null - ) + get() = + configManagerSharedPreferences.getString( + LegacySharedPreferencesKeys.COOKIES, + null, + ) val launchesSinceUpgrade: Int - get() = messageManagerSharedPreferences.getInt( - LegacySharedPreferencesKeys.TOTAL_SINCE_UPGRADE, - 0 - ) + get() = + messageManagerSharedPreferences.getInt( + LegacySharedPreferencesKeys.TOTAL_SINCE_UPGRADE, + 0, + ) val userIdentites: String? - get() = configManagerSharedPreferences.getString( - LegacySharedPreferencesKeys.USER_IDENTITIES + apiKey, - null - ) + get() = + configManagerSharedPreferences.getString( + LegacySharedPreferencesKeys.USER_IDENTITIES + apiKey, + null, + ) companion object { private const val NEEDS_TO_MIGRATE_TO_MPID_DEPENDENT = @@ -513,16 +500,22 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L * @param context * @return */ - fun needsToMigrate(context: Context): Boolean { - return getMParticleSharedPrefs(context).getBoolean( - NEEDS_TO_MIGRATE_TO_MPID_DEPENDENT, false + fun needsToMigrate(context: Context): Boolean = + getMParticleSharedPrefs(context).getBoolean( + NEEDS_TO_MIGRATE_TO_MPID_DEPENDENT, + false, ) - } - fun setNeedsToMigrate(context: Context, needsToMigrate: Boolean) { - getMParticleSharedPrefs(context).edit().putBoolean( - NEEDS_TO_MIGRATE_TO_MPID_DEPENDENT, needsToMigrate - ).apply() + fun setNeedsToMigrate( + context: Context, + needsToMigrate: Boolean, + ) { + getMParticleSharedPrefs(context) + .edit() + .putBoolean( + NEEDS_TO_MIGRATE_TO_MPID_DEPENDENT, + needsToMigrate, + ).apply() } } } @@ -561,16 +554,23 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L } @JvmStatic - fun create(context: Context, mpid: Long): UserStorage { - return UserStorage(context, mpid) - } + fun create( + context: Context, + mpid: Long, + ): UserStorage = UserStorage(context, mpid) @JvmStatic - fun setNeedsToMigrate(context: Context, needsToMigrate: Boolean) { + fun setNeedsToMigrate( + context: Context, + needsToMigrate: Boolean, + ) { SharedPreferencesMigrator.setNeedsToMigrate(context, needsToMigrate) } - private fun removeMpId(context: Context, mpid: Long): Boolean { + private fun removeMpId( + context: Context, + mpid: Long, + ): Boolean { val mpids = getMpIdSet(context) val removed = mpids.remove(mpid) setMpIds(context, mpids) @@ -581,11 +581,13 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L fun getMpIdSet(context: Context): MutableSet { var userConfigs = JSONArray() try { - userConfigs = JSONArray( - getMParticleSharedPrefs(context).getString( - USER_CONFIG_COLLECTION, JSONArray().toString() + userConfigs = + JSONArray( + getMParticleSharedPrefs(context).getString( + USER_CONFIG_COLLECTION, + JSONArray().toString(), + ), ) - ) } catch (ignore: JSONException) { } val mpIds: MutableSet = TreeSet() @@ -598,24 +600,26 @@ class UserStorage private constructor(private val mContext: Context, val mpid: L return mpIds } - private fun setMpIds(context: Context, mpIds: Set) { + private fun setMpIds( + context: Context, + mpIds: Set, + ) { val jsonArray = JSONArray() for (mpId in mpIds) { jsonArray.put(mpId) } - getMParticleSharedPrefs(context).edit() - .putString(USER_CONFIG_COLLECTION, jsonArray.toString()).apply() + getMParticleSharedPrefs(context) + .edit() + .putString(USER_CONFIG_COLLECTION, jsonArray.toString()) + .apply() } - private fun getFileName(mpId: Long): String { - return ConfigManager.PREFERENCES_FILE + ":" + mpId - } + private fun getFileName(mpId: Long): String = ConfigManager.PREFERENCES_FILE + ":" + mpId - private fun getMParticleSharedPrefs(context: Context): SharedPreferences { - return context.getSharedPreferences( + private fun getMParticleSharedPrefs(context: Context): SharedPreferences = + context.getSharedPreferences( ConfigManager.PREFERENCES_FILE, - Context.MODE_PRIVATE + Context.MODE_PRIVATE, ) - } } } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/listeners/GraphListener.kt b/android-core/src/main/kotlin/com/mparticle/internal/listeners/GraphListener.kt index 495a722ea..c7797ba42 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/listeners/GraphListener.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/listeners/GraphListener.kt @@ -3,12 +3,15 @@ package com.mparticle.internal.listeners import android.os.Message interface GraphListener { - fun onCompositeObjects(child: Any?, parent: Any?) + fun onCompositeObjects( + child: Any?, + parent: Any?, + ) fun onThreadMessage( handlerName: String, msg: Message?, onNewThread: Boolean, - stackTrace: Array? + stackTrace: Array?, ) } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListener.kt b/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListener.kt index 0f496e212..2fc42aa52 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListener.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListener.kt @@ -28,7 +28,11 @@ interface InternalListener { * @param used whether the Kit's method returned ReportingMessages, or null if return type is void * @param objects the arguments supplied to the Kit */ - fun onKitApiCalled(kitId: Int, used: Boolean, vararg objects: Any) + fun onKitApiCalled( + kitId: Int, + used: Boolean, + vararg objects: Any, + ) /** * to be called when a Kit's API method is invoked, and the name of the Kit's method is different @@ -39,7 +43,12 @@ interface InternalListener { * @param used whether the Kit's method returned ReportingMessages, or null if return type is void * @param objects the arguments supplied to the Kit */ - fun onKitApiCalled(methodName: String, kitId: Int, used: Boolean, vararg objects: Any) + fun onKitApiCalled( + methodName: String, + kitId: Int, + used: Boolean, + vararg objects: Any, + ) /** * establishes a child-parent relationship between two objects. It is not necessary to call this @@ -48,7 +57,10 @@ interface InternalListener { * @param child the child object * @param parent the parent object */ - fun onCompositeObjects(child: Any?, parent: Any?) + fun onCompositeObjects( + child: Any?, + parent: Any?, + ) /** * denotes that an object is going to be passed to a new Thread, and is a candidate to be a "composite" @@ -58,7 +70,11 @@ interface InternalListener { * @param handlerName the Name of the Handler class, for example "com.mparticle.internal.MessageHandler" * @param msg the Message object */ - fun onThreadMessage(handlerName: String, msg: Message, onNewThread: Boolean) + fun onThreadMessage( + handlerName: String, + msg: Message, + onNewThread: Boolean, + ) /** * indicates that an entry has been stored in the Database @@ -68,7 +84,11 @@ interface InternalListener { * @param contentValues the ContentValues object to be inserted */ @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB) - fun onEntityStored(rowId: Long, tableName: String, contentValues: ContentValues?) + fun onEntityStored( + rowId: Long, + tableName: String, + contentValues: ContentValues?, + ) /** * indicates that a Network Request has been started @@ -82,7 +102,7 @@ interface InternalListener { type: SdkListener.Endpoint, url: String, body: JSONObject?, - vararg objects: Any + vararg objects: Any, ) /** @@ -96,7 +116,7 @@ interface InternalListener { type: SdkListener.Endpoint, url: String, response: JSONObject?, - responseCode: Int + responseCode: Int, ) /** @@ -120,7 +140,10 @@ interface InternalListener { * @param kitId * @param configuration */ - fun onKitConfigReceived(kitId: Int, configuration: String?) + fun onKitConfigReceived( + kitId: Int, + configuration: String?, + ) /** * indicates that a Kit was present, and a configuration was received for it, but it was not started, @@ -130,7 +153,10 @@ interface InternalListener { * @param kitId * @param reason */ - fun onKitExcluded(kitId: Int, reason: String?) + fun onKitExcluded( + kitId: Int, + reason: String?, + ) /** * indicates that a Kit successfully executed it's onKitCreate() method @@ -143,75 +169,85 @@ interface InternalListener { companion object { @JvmField - val EMPTY: InternalListener = object : InternalListener { - override fun onApiCalled(vararg objects: Any) { /* stub */ - } - - override fun onKitApiCalled( - kitId: Int, - used: Boolean, - vararg objects: Any - ) { /* stub */ - } - - override fun onKitApiCalled( - methodName: String, - kitId: Int, - used: Boolean, - vararg objects: Any - ) { /* stub */ - } - - override fun onEntityStored( - rowId: Long, - tableName: String, - contentValues: ContentValues? - ) { /* stub */ - } - - override fun onNetworkRequestStarted( - type: SdkListener.Endpoint, - url: String, - body: JSONObject?, - vararg objects: Any - ) { /* stub */ - } - - override fun onNetworkRequestFinished( - type: SdkListener.Endpoint, - url: String, - response: JSONObject?, - responseCode: Int - ) { /* stub */ - } - - override fun onSessionUpdated(internalSession: InternalSession) { /* stub */ - } - - override fun onKitDetected(kitId: Int) { /* stub */ - } - - override fun onKitConfigReceived(kitId: Int, configuration: String?) { /* stub */ - } - - override fun onKitExcluded(kitId: Int, reason: String?) { /* stub */ - } - - override fun onKitStarted(kitId: Int) { /* stub */ - } - - override fun onAliasRequestFinished(aliasResponse: AliasResponse?) { /* stub */ - } - - override fun onCompositeObjects(child: Any?, parent: Any?) { /* stub */ - } - - override fun onThreadMessage( - handlerName: String, - msg: Message, - onNewThread: Boolean - ) { /* stub */ + val EMPTY: InternalListener = + object : InternalListener { + override fun onApiCalled(vararg objects: Any) { // stub + } + + override fun onKitApiCalled( + kitId: Int, + used: Boolean, + vararg objects: Any, + ) { // stub + } + + override fun onKitApiCalled( + methodName: String, + kitId: Int, + used: Boolean, + vararg objects: Any, + ) { // stub + } + + override fun onEntityStored( + rowId: Long, + tableName: String, + contentValues: ContentValues?, + ) { // stub + } + + override fun onNetworkRequestStarted( + type: SdkListener.Endpoint, + url: String, + body: JSONObject?, + vararg objects: Any, + ) { // stub + } + + override fun onNetworkRequestFinished( + type: SdkListener.Endpoint, + url: String, + response: JSONObject?, + responseCode: Int, + ) { // stub + } + + override fun onSessionUpdated(internalSession: InternalSession) { // stub + } + + override fun onKitDetected(kitId: Int) { // stub + } + + override fun onKitConfigReceived( + kitId: Int, + configuration: String?, + ) { // stub + } + + override fun onKitExcluded( + kitId: Int, + reason: String?, + ) { // stub + } + + override fun onKitStarted(kitId: Int) { // stub + } + + override fun onAliasRequestFinished(aliasResponse: AliasResponse?) { // stub + } + + override fun onCompositeObjects( + child: Any?, + parent: Any?, + ) { // stub + } + + override fun onThreadMessage( + handlerName: String, + msg: Message, + onNewThread: Boolean, + ) { // stub + } } - } } } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListenerManager.kt b/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListenerManager.kt index 27f95ada2..ac65bcd8a 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListenerManager.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListenerManager.kt @@ -13,7 +13,9 @@ import org.json.JSONObject import java.lang.ref.WeakReference import java.util.Locale -class InternalListenerManager private constructor(private val context: Context) : InternalListener { +class InternalListenerManager private constructor( + private val context: Context, +) : InternalListener { val sdkListeners: MutableList> = ArrayList() val graphListeners: MutableList> = ArrayList() private val thrown = false @@ -46,7 +48,11 @@ class InternalListenerManager private constructor(private val context: Context) override fun onApiCalled(vararg objects: Any) { } - override fun onKitApiCalled(kitId: Int, used: Boolean, vararg objects: Any) { + override fun onKitApiCalled( + kitId: Int, + used: Boolean, + vararg objects: Any, + ) { val stackTrace = Thread.currentThread().stackTrace var methodName: String? = null for (i in stackTrace.indices) { @@ -59,7 +65,10 @@ class InternalListenerManager private constructor(private val context: Context) } override fun onKitApiCalled( - methodName: String, kitId: Int, used: Boolean, vararg objects: Any + methodName: String, + kitId: Int, + used: Boolean, + vararg objects: Any, ) { onKitApiCalled(Thread.currentThread().stackTrace, methodName, kitId, used, *objects) } @@ -69,7 +78,7 @@ class InternalListenerManager private constructor(private val context: Context) methodName: String, kitId: Int, used: Boolean, - vararg objects: Any + vararg objects: Any, ) { var invokingApiMethodName: String? = null var kitManagerMethodName: String? = null @@ -95,52 +104,68 @@ class InternalListenerManager private constructor(private val context: Context) } val finalInvokingApiMethodName = invokingApiMethodName val finalKitManagerMethodName = kitManagerMethodName - broadcast(object : SdkListenerRunnable { - override fun run(listener: SdkListener) { - listener.onKitApiCalled( - kitId, - methodName, - finalInvokingApiMethodName, - finalKitManagerMethodName, - objectList, - used - ) - } - }) + broadcast( + object : SdkListenerRunnable { + override fun run(listener: SdkListener) { + listener.onKitApiCalled( + kitId, + methodName, + finalInvokingApiMethodName, + finalKitManagerMethodName, + objectList, + used, + ) + } + }, + ) } - override fun onCompositeObjects(child: Any?, parent: Any?) { - broadcast(object : SdkGraphListenerRunnable { - override fun run(listener: GraphListener) { - listener.onCompositeObjects(child, parent) - } - }) + override fun onCompositeObjects( + child: Any?, + parent: Any?, + ) { + broadcast( + object : SdkGraphListenerRunnable { + override fun run(listener: GraphListener) { + listener.onCompositeObjects(child, parent) + } + }, + ) } - override fun onThreadMessage(handlerName: String, msg: Message, onNewThread: Boolean) { + override fun onThreadMessage( + handlerName: String, + msg: Message, + onNewThread: Boolean, + ) { var stackTrace: Array? = null if (!onNewThread) { stackTrace = Thread.currentThread().stackTrace } val finalStackTrace = stackTrace - broadcast(object : SdkGraphListenerRunnable { - override fun run(listener: GraphListener) { - listener.onThreadMessage(handlerName, msg, onNewThread, finalStackTrace) - } - }) + broadcast( + object : SdkGraphListenerRunnable { + override fun run(listener: GraphListener) { + listener.onThreadMessage(handlerName, msg, onNewThread, finalStackTrace) + } + }, + ) } override fun onEntityStored( - primaryKey: Long, tableName: String, contentValues: ContentValues? + primaryKey: Long, + tableName: String, + contentValues: ContentValues?, ) { onCompositeObjects(contentValues, tableName + primaryKey) val jsonObject = JSONObject() var table: SdkListener.DatabaseTable? = null - table = try { - tableName.uppercase(Locale.getDefault()).let { SdkListener.DatabaseTable.valueOf(it) } - } catch (ex: IllegalArgumentException) { - SdkListener.DatabaseTable.UNKNOWN - } + table = + try { + tableName.uppercase(Locale.getDefault()).let { SdkListener.DatabaseTable.valueOf(it) } + } catch (ex: IllegalArgumentException) { + SdkListener.DatabaseTable.UNKNOWN + } if (contentValues != null) { for ((key, value) in contentValues.valueSet()) { try { @@ -155,15 +180,20 @@ class InternalListenerManager private constructor(private val context: Context) } } val finalTable = table - broadcast(object : SdkListenerRunnable { - override fun run(listener: SdkListener) { - finalTable?.let { listener.onEntityStored(it, primaryKey, jsonObject) } - } - }) + broadcast( + object : SdkListenerRunnable { + override fun run(listener: SdkListener) { + finalTable?.let { listener.onEntityStored(it, primaryKey, jsonObject) } + } + }, + ) } override fun onNetworkRequestStarted( - type: SdkListener.Endpoint, url: String, body: JSONObject?, vararg objects: Any + type: SdkListener.Endpoint, + url: String, + body: JSONObject?, + vararg objects: Any, ) { for (obj in objects) { onCompositeObjects(obj, body) @@ -172,76 +202,100 @@ class InternalListenerManager private constructor(private val context: Context) for (obj in objects) { objectList.add(obj) } - broadcast(object : SdkListenerRunnable { - override fun run(listener: SdkListener) { - listener.onNetworkRequestStarted(type, url, body ?: JSONObject()) - } - }) + broadcast( + object : SdkListenerRunnable { + override fun run(listener: SdkListener) { + listener.onNetworkRequestStarted(type, url, body ?: JSONObject()) + } + }, + ) } override fun onNetworkRequestFinished( - type: SdkListener.Endpoint, url: String, response: JSONObject?, responseCode: Int + type: SdkListener.Endpoint, + url: String, + response: JSONObject?, + responseCode: Int, ) { - - broadcast(object : SdkListenerRunnable { - override fun run(listener: SdkListener) { - listener.onNetworkRequestFinished(type, url, response, responseCode) - } - }) + broadcast( + object : SdkListenerRunnable { + override fun run(listener: SdkListener) { + listener.onNetworkRequestFinished(type, url, response, responseCode) + } + }, + ) } override fun onSessionUpdated(internalSession: InternalSession) { - broadcast(object : SdkListenerRunnable { - override fun run(listener: SdkListener) { - listener.onSessionUpdated(InternalSession(internalSession)) - } - }) + broadcast( + object : SdkListenerRunnable { + override fun run(listener: SdkListener) { + listener.onSessionUpdated(InternalSession(internalSession)) + } + }, + ) } override fun onKitDetected(kitId: Int) { - broadcast(object : SdkListenerRunnable { - override fun run(listener: SdkListener) { - listener.onKitDetected(kitId) - } - }) + broadcast( + object : SdkListenerRunnable { + override fun run(listener: SdkListener) { + listener.onKitDetected(kitId) + } + }, + ) } - override fun onKitConfigReceived(kitId: Int, configuration: String?) { + override fun onKitConfigReceived( + kitId: Int, + configuration: String?, + ) { var jsonObject = JSONObject() try { jsonObject = JSONObject(configuration) } catch (e: JSONException) { } val jsonConfig = jsonObject - broadcast(object : SdkListenerRunnable { - override fun run(listener: SdkListener) { - listener.onKitConfigReceived(kitId, jsonConfig) - } - }) + broadcast( + object : SdkListenerRunnable { + override fun run(listener: SdkListener) { + listener.onKitConfigReceived(kitId, jsonConfig) + } + }, + ) } - override fun onKitExcluded(kitId: Int, reason: String?) { - broadcast(object : SdkListenerRunnable { - override fun run(listener: SdkListener) { - listener.onKitExcluded(kitId, reason) - } - }) + override fun onKitExcluded( + kitId: Int, + reason: String?, + ) { + broadcast( + object : SdkListenerRunnable { + override fun run(listener: SdkListener) { + listener.onKitExcluded(kitId, reason) + } + }, + ) } override fun onKitStarted(kitId: Int) { - broadcast(object : SdkListenerRunnable { - override fun run(listener: SdkListener) { - listener.onKitStarted(kitId) - } - }) + broadcast( + object : SdkListenerRunnable { + override fun run(listener: SdkListener) { + listener.onKitStarted(kitId) + } + }, + ) } override fun onAliasRequestFinished(aliasResponse: AliasResponse?) { - broadcast(object : SdkListenerRunnable { - override fun run(listener: SdkListener) { - listener.onAliasRequestFinished(aliasResponse) - } - }) + broadcast( + object : SdkListenerRunnable { + override fun run(listener: SdkListener) { + listener.onAliasRequestFinished(aliasResponse) + } + }, + ) } private fun broadcast(runnable: SdkListenerRunnable) { @@ -279,7 +333,10 @@ class InternalListenerManager private constructor(private val context: Context) return getApiFormattedName(classNameString, element.methodName) } - private fun getClassName(className: String, methodName: String): String { + private fun getClassName( + className: String, + methodName: String, + ): String { val packageNames = className.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val simpleClassName = packageNames[packageNames.size - 1] @@ -308,19 +365,16 @@ class InternalListenerManager private constructor(private val context: Context) return simpleClassName } - private fun isObfuscated(className: String): Boolean { - return Character.isLowerCase(className.toCharArray()[0]) && className.length <= 3 - } + private fun isObfuscated(className: String): Boolean = Character.isLowerCase(className.toCharArray()[0]) && className.length <= 3 - private fun isExternalApiInvocation(element: StackTraceElement): Boolean { - return !element.className.startsWith("com.mparticle") || (element.className.startsWith( - context.applicationContext.packageName - ) && context.applicationContext.packageName.length > 1) - } + private fun isExternalApiInvocation(element: StackTraceElement): Boolean = + !element.className.startsWith("com.mparticle") || ( + element.className.startsWith( + context.applicationContext.packageName, + ) && context.applicationContext.packageName.length > 1 + ) - private fun hasListeners(): Boolean { - return (instance?.sdkListeners?.size ?: 0) > 0 || (instance?.graphListeners?.size ?: 0) > 0 - } + private fun hasListeners(): Boolean = (instance?.sdkListeners?.size ?: 0) > 0 || (instance?.graphListeners?.size ?: 0) > 0 companion object { private var instance: InternalListenerManager? = null @@ -341,13 +395,20 @@ class InternalListenerManager private constructor(private val context: Context) @JvmStatic val listener: InternalListener - get() = instance?.let { - if (isEnabled) it else InternalListener.EMPTY - } ?: InternalListener.EMPTY - - fun getApiFormattedName(className: String?, methodName: String?): String { - return StringBuilder().append(className).append(".").append(methodName).append("()") + get() = + instance?.let { + if (isEnabled) it else InternalListener.EMPTY + } ?: InternalListener.EMPTY + + fun getApiFormattedName( + className: String?, + methodName: String?, + ): String = + StringBuilder() + .append(className) + .append(".") + .append(methodName) + .append("()") .toString() - } } } diff --git a/android-core/src/main/kotlin/com/mparticle/rokt/RoktConfig.kt b/android-core/src/main/kotlin/com/mparticle/rokt/RoktConfig.kt index 75758b4f9..4507df1ea 100644 --- a/android-core/src/main/kotlin/com/mparticle/rokt/RoktConfig.kt +++ b/android-core/src/main/kotlin/com/mparticle/rokt/RoktConfig.kt @@ -11,8 +11,11 @@ class RoktConfig private constructor( private var edgeToEdgeDisplay: Boolean = true, ) { fun colorMode(mode: ColorMode) = apply { this.colorMode = mode } + fun cacheConfig(cacheConfig: CacheConfig) = apply { this.cacheConfig = cacheConfig } + fun edgeToEdgeDisplay(edgeToEdgeDisplay: Boolean) = apply { this.edgeToEdgeDisplay = edgeToEdgeDisplay } + fun build(): RoktConfig = RoktConfig(colorMode, cacheConfig, edgeToEdgeDisplay) } @@ -26,4 +29,4 @@ class CacheConfig( companion object { const val DEFAULT_CACHE_DURATION_SECS: Long = 90 * 60 } -} \ No newline at end of file +} diff --git a/android-core/src/main/kotlin/com/mparticle/rokt/RoktEmbeddedView.kt b/android-core/src/main/kotlin/com/mparticle/rokt/RoktEmbeddedView.kt index d50cbbb21..03db66366 100644 --- a/android-core/src/main/kotlin/com/mparticle/rokt/RoktEmbeddedView.kt +++ b/android-core/src/main/kotlin/com/mparticle/rokt/RoktEmbeddedView.kt @@ -12,4 +12,4 @@ class RoktEmbeddedView : FrameLayout { constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) -} \ No newline at end of file +} diff --git a/android-core/src/main/kotlin/com/mparticle/rokt/RoktLayoutDimensionCallBack.kt b/android-core/src/main/kotlin/com/mparticle/rokt/RoktLayoutDimensionCallBack.kt index e8a65ce71..e4d560c47 100644 --- a/android-core/src/main/kotlin/com/mparticle/rokt/RoktLayoutDimensionCallBack.kt +++ b/android-core/src/main/kotlin/com/mparticle/rokt/RoktLayoutDimensionCallBack.kt @@ -2,5 +2,11 @@ package com.mparticle.rokt interface RoktLayoutDimensionCallBack { fun onHeightChanged(height: Int) - fun onMarginChanged(start: Int, top: Int, end: Int, bottom: Int) -} \ No newline at end of file + + fun onMarginChanged( + start: Int, + top: Int, + end: Int, + bottom: Int, + ) +} diff --git a/android-core/src/main/kotlin/com/mparticle/rokt/RoktOptions.kt b/android-core/src/main/kotlin/com/mparticle/rokt/RoktOptions.kt index 829257612..f062ca794 100644 --- a/android-core/src/main/kotlin/com/mparticle/rokt/RoktOptions.kt +++ b/android-core/src/main/kotlin/com/mparticle/rokt/RoktOptions.kt @@ -1,9 +1,11 @@ package com.mparticle.rokt -class RoktOptions @JvmOverloads constructor( - fontFilePathMap: Map = emptyMap(), - fontPostScriptNames: Set = emptySet() -) { - val fontFilePathMap: Map = fontFilePathMap.toMap() - val fontPostScriptNames: Set = fontPostScriptNames.toSet() -} \ No newline at end of file +class RoktOptions + @JvmOverloads + constructor( + fontFilePathMap: Map = emptyMap(), + fontPostScriptNames: Set = emptySet(), + ) { + val fontFilePathMap: Map = fontFilePathMap.toMap() + val fontPostScriptNames: Set = fontPostScriptNames.toSet() + } diff --git a/android-core/src/test/kotlin/com/mparticle/MPEventTests.kt b/android-core/src/test/kotlin/com/mparticle/MPEventTests.kt index 7f582293d..f7c3626fb 100644 --- a/android-core/src/test/kotlin/com/mparticle/MPEventTests.kt +++ b/android-core/src/test/kotlin/com/mparticle/MPEventTests.kt @@ -8,8 +8,11 @@ class MPEventTests { @Test fun testBasicBuilder() { val event = - MPEvent.Builder("test name", MParticle.EventType.Navigation).category("test category") - .duration(1234.0).build() + MPEvent + .Builder("test name", MParticle.EventType.Navigation) + .category("test category") + .duration(1234.0) + .build() Assert.assertTrue(event.eventName == "test name") Assert.assertTrue(event.eventType == MParticle.EventType.Navigation) Assert.assertTrue(event.category == "test category") @@ -18,7 +21,12 @@ class MPEventTests { @Test fun testScreenBuilder() { - val event = MPEvent.Builder("test name").category("test category").duration(1234.0).build() + val event = + MPEvent + .Builder("test name") + .category("test category") + .duration(1234.0) + .build() Assert.assertTrue(event.eventName == "test name") Assert.assertTrue(event.eventType == MParticle.EventType.Other) Assert.assertTrue(event.category == "test category") @@ -28,8 +36,11 @@ class MPEventTests { @Test fun testSerialization() { val eventString = - MPEvent.Builder("test name", MParticle.EventType.Navigation).category("test category") - .duration(1234.0).toString() + MPEvent + .Builder("test name", MParticle.EventType.Navigation) + .category("test category") + .duration(1234.0) + .toString() val event = MPEvent.Builder.parseString(eventString)?.build() Assert.assertTrue(event?.eventName == "test name") Assert.assertTrue(event?.eventType == MParticle.EventType.Navigation) @@ -40,7 +51,9 @@ class MPEventTests { @Test fun testEventLength() { val event = - MPEvent.Builder("test name", MParticle.EventType.Navigation).category("test category") + MPEvent + .Builder("test name", MParticle.EventType.Navigation) + .category("test category") .build() Assert.assertNull(event.length) } @@ -70,7 +83,7 @@ class MPEventTests { MPEvent.Builder(nameBuilder.toString(), MParticle.EventType.Navigation).build() Assert.assertEquals( Constants.LIMIT_ATTR_KEY.toLong(), - eventBuilder.eventName.length.toLong() + eventBuilder.eventName.length.toLong(), ) } @@ -84,14 +97,16 @@ class MPEventTests { val attributes = HashMap() attributes["key 1"] = "value 1" attributes["key 2"] = "value 2" - event = MPEvent.Builder("another name", MParticle.EventType.Social) - .category("category") - .duration(12345.0) - .customAttributes(attributes) - .addCustomFlag("cool flag key", "flag 1 value 1") - .addCustomFlag("cool flag key", "flag 1 value 2") - .addCustomFlag("cool flag key 2", "flag 2 value 1") - .build() + event = + MPEvent + .Builder("another name", MParticle.EventType.Social) + .category("category") + .duration(12345.0) + .customAttributes(attributes) + .addCustomFlag("cool flag key", "flag 1 value 1") + .addCustomFlag("cool flag key", "flag 1 value 2") + .addCustomFlag("cool flag key 2", "flag 2 value 1") + .build() copiedEvent = MPEvent(event) Assert.assertEquals("another name", copiedEvent.eventName) Assert.assertEquals(MParticle.EventType.Social, copiedEvent.eventType) diff --git a/android-core/src/test/kotlin/com/mparticle/MParticleTest.kt b/android-core/src/test/kotlin/com/mparticle/MParticleTest.kt index 40c8789a4..707808551 100644 --- a/android-core/src/test/kotlin/com/mparticle/MParticleTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/MParticleTest.kt @@ -56,10 +56,12 @@ class MParticleTest { @Throws(Exception::class) fun testSetUserAttribute() { val mp: MParticle = InnerMockMParticle() - val mockSession = Mockito.mock( - InternalSession::class.java - ) - Mockito.`when`(mp.mInternal.appStateManager.session) + val mockSession = + Mockito.mock( + InternalSession::class.java, + ) + Mockito + .`when`(mp.mInternal.appStateManager.session) .thenReturn(mockSession) Mockito.`when`(mp.mInternal.configManager.isEnabled).thenReturn(true) Mockito.`when`(mp.mInternal.configManager.mpid).thenReturn(1L) @@ -68,33 +70,37 @@ class MParticleTest { Assert.assertFalse(mp.Identity().currentUser!!.setUserAttribute("", "test")) Assert.assertFalse(mp.Identity().currentUser!!.setUserAttribute("", "")) Assert.assertFalse( - mp.Identity().currentUser!!.setUserAttribute(String(CharArray(257)), "") - ) - val listCaptor = ArgumentCaptor.forClass( - MutableList::class.java - ) - val stringCaptor = ArgumentCaptor.forClass( - String::class.java - ) - val longCaptor = ArgumentCaptor.forClass( - Long::class.java + mp.Identity().currentUser!!.setUserAttribute(String(CharArray(257)), ""), ) + val listCaptor = + ArgumentCaptor.forClass( + MutableList::class.java, + ) + val stringCaptor = + ArgumentCaptor.forClass( + String::class.java, + ) + val longCaptor = + ArgumentCaptor.forClass( + Long::class.java, + ) val legalString = String(CharArray(Constants.LIMIT_ATTR_KEY)) Assert.assertTrue( - mp.Identity().currentUser!!.setUserAttribute(legalString, "") + mp.Identity().currentUser!!.setUserAttribute(legalString, ""), ) - Mockito.verify(mp.mMessageManager, Mockito.times(1)) + Mockito + .verify(mp.mMessageManager, Mockito.times(1)) .setUserAttribute(legalString, "", 1, false) val integerList: MutableList = LinkedList() integerList.add(203948) Assert.assertTrue( - mp.Identity().currentUser!!.setUserAttribute("test2", integerList) + mp.Identity().currentUser!!.setUserAttribute("test2", integerList), ) Mockito.verify(mp.mMessageManager, Mockito.times(2)).setUserAttribute( stringCaptor.capture(), listCaptor.capture(), longCaptor.capture(), - ArgumentMatchers.eq(false) + ArgumentMatchers.eq(false), ) Assert.assertTrue(stringCaptor.value == "test2") var capturedStringList = listCaptor.value @@ -106,13 +112,13 @@ class MParticleTest { longStringList.add("a") } Assert.assertTrue( - mp.Identity().currentUser!!.setUserAttribute("test3", longStringList) + mp.Identity().currentUser!!.setUserAttribute("test3", longStringList), ) Mockito.verify(mp.mMessageManager, Mockito.times(3)).setUserAttribute( stringCaptor.capture(), listCaptor.capture(), longCaptor.capture(), - ArgumentMatchers.eq(false) + ArgumentMatchers.eq(false), ) Assert.assertTrue(stringCaptor.value == "test3") Assert.assertTrue(longCaptor.value == 1L) @@ -120,28 +126,28 @@ class MParticleTest { Assert.assertTrue(capturedStringList == longStringList) longStringList.add("too much!") Assert.assertFalse( - mp.Identity().currentUser!!.setUserAttribute("test", longStringList) + mp.Identity().currentUser!!.setUserAttribute("test", longStringList), ) val stringList: MutableList = LinkedList() stringList.add(String(CharArray(Constants.LIMIT_ATTR_VALUE))) Assert.assertTrue( - mp.Identity().currentUser!!.setUserAttribute("test", stringList) + mp.Identity().currentUser!!.setUserAttribute("test", stringList), ) stringList.add(String(CharArray(Constants.LIMIT_ATTR_VALUE + 1))) Assert.assertFalse( - mp.Identity().currentUser!!.setUserAttribute("test", stringList) + mp.Identity().currentUser!!.setUserAttribute("test", stringList), ) Assert.assertTrue(mp.Identity().currentUser!!.setUserAttribute("test", "")) Assert.assertTrue( mp.Identity().currentUser!!.setUserAttribute( "test", String( - CharArray(4096) - ) - ) + CharArray(4096), + ), + ), ) Assert.assertFalse( - mp.Identity().currentUser!!.setUserAttribute("test", String(CharArray(4097))) + mp.Identity().currentUser!!.setUserAttribute("test", String(CharArray(4097))), ) Assert.assertTrue(mp.Identity().currentUser!!.setUserAttribute("test", 1212)) } @@ -195,40 +201,46 @@ class MParticleTest { @Throws(Exception::class) fun testSetUserAttributeList() { val mp: MParticle = InnerMockMParticle() - val mockSession = Mockito.mock( - InternalSession::class.java - ) + val mockSession = + Mockito.mock( + InternalSession::class.java, + ) Mockito.`when`(mp.mInternal.appStateManager.session).thenReturn(mockSession) Mockito.`when`(mp.mInternal.configManager.isEnabled).thenReturn(true) Mockito.`when`(mp.mInternal.configManager.mpid).thenReturn(2L) MParticle.setInstance(mp) MParticle.start(MParticleOptions.builder(MockContext()).build()) Assert.assertFalse( - mp.Identity().currentUser!!.setUserAttributeList("", "") + mp.Identity().currentUser!!.setUserAttributeList("", ""), ) Assert.assertFalse( - mp.Identity().currentUser!! - .setUserAttributeList(String(CharArray(257)), "") - ) - val listCaptor = ArgumentCaptor.forClass( - MutableList::class.java - ) - val stringCaptor = ArgumentCaptor.forClass( - String::class.java - ) - val longCaptor = ArgumentCaptor.forClass( - Long::class.java - ) + mp + .Identity() + .currentUser!! + .setUserAttributeList(String(CharArray(257)), ""), + ) + val listCaptor = + ArgumentCaptor.forClass( + MutableList::class.java, + ) + val stringCaptor = + ArgumentCaptor.forClass( + String::class.java, + ) + val longCaptor = + ArgumentCaptor.forClass( + Long::class.java, + ) val integerList: MutableList = LinkedList() integerList.add(203948) Assert.assertTrue( - mp.Identity().currentUser!!.setUserAttribute("test2", integerList) + mp.Identity().currentUser!!.setUserAttribute("test2", integerList), ) Mockito.verify(mp.mMessageManager, Mockito.times(1)).setUserAttribute( stringCaptor.capture(), listCaptor.capture(), longCaptor.capture(), - ArgumentMatchers.eq(false) + ArgumentMatchers.eq(false), ) Assert.assertTrue(stringCaptor.value == "test2") var capturedStringList = listCaptor.value @@ -240,30 +252,30 @@ class MParticleTest { longStringList.add("a") } Assert.assertTrue( - mp.Identity().currentUser!!.setUserAttributeList("test3", longStringList) + mp.Identity().currentUser!!.setUserAttributeList("test3", longStringList), ) Mockito.verify(mp.mMessageManager, Mockito.times(2)).setUserAttribute( stringCaptor.capture(), listCaptor.capture(), longCaptor.capture(), - ArgumentMatchers.eq(false) + ArgumentMatchers.eq(false), ) Assert.assertTrue(stringCaptor.value == "test3") capturedStringList = listCaptor.value Assert.assertTrue(capturedStringList == longStringList) longStringList.add("too much!") Assert.assertFalse( - mp.Identity().currentUser!!.setUserAttributeList("test", longStringList) + mp.Identity().currentUser!!.setUserAttributeList("test", longStringList), ) Assert.assertTrue(longCaptor.value == 2L) val stringList: MutableList = LinkedList() stringList.add(String(CharArray(Constants.LIMIT_ATTR_VALUE))) Assert.assertTrue( - mp.Identity().currentUser!!.setUserAttributeList("test", stringList) + mp.Identity().currentUser!!.setUserAttributeList("test", stringList), ) stringList.add(String(CharArray(Constants.LIMIT_ATTR_VALUE + 1))) Assert.assertFalse( - mp.Identity().currentUser!!.setUserAttributeList("test", stringList) + mp.Identity().currentUser!!.setUserAttributeList("test", stringList), ) } @@ -276,9 +288,10 @@ class MParticleTest { if (mp != null) { Mockito.`when`(mp.mInternal.configManager.mpid).thenReturn(12L) Assert.assertTrue( - mp.Identity().currentUser!!.incrementUserAttribute("test", 3) + mp.Identity().currentUser!!.incrementUserAttribute("test", 3), ) - Mockito.verify(mp.mMessageManager, Mockito.times(1)) + Mockito + .verify(mp.mMessageManager, Mockito.times(1)) .incrementUserAttribute("test", 3, 12) } } @@ -288,16 +301,18 @@ class MParticleTest { fun testSetUserTag() { val mp: MParticle = InnerMockMParticle() Mockito.`when`(mp.mInternal.configManager.mpid).thenReturn(1L) - val mockSession = Mockito.mock( - InternalSession::class.java - ) + val mockSession = + Mockito.mock( + InternalSession::class.java, + ) Mockito.`when`(mp.mInternal.appStateManager.session).thenReturn(mockSession) Mockito.`when`(mp.mInternal.configManager.isEnabled).thenReturn(true) MParticle.setInstance(mp) Assert.assertFalse(mp.Identity().currentUser!!.setUserTag("")) Assert.assertFalse(mp.Identity().currentUser!!.setUserTag("")) Assert.assertTrue(mp.Identity().currentUser!!.setUserTag("blah")) - Mockito.verify(mp.mMessageManager, Mockito.times(1)) + Mockito + .verify(mp.mMessageManager, Mockito.times(1)) .setUserAttribute("blah", null, 1, false) } @@ -362,46 +377,57 @@ class MParticleTest { val mp: MParticle = InnerMockMParticle() MParticle.setInstance(mp) val ran = RandomUtils() - val values = arrayOf( - "", - "123", - ran.getAlphaNumericString(5), - ran.getAlphaNumericString(20), - ran.getAlphaNumericString(100) - ) + val values = + arrayOf( + "", + "123", + ran.getAlphaNumericString(5), + ran.getAlphaNumericString(20), + ran.getAlphaNumericString(100), + ) // test that we apply the token stored in the ConfigManager for (value in values) { - Mockito.`when`(mp.mInternal.configManager.workspaceToken) + Mockito + .`when`(mp.mInternal.configManager.workspaceToken) .thenReturn(value) val called = AndroidUtils.Mutable(false) - val webView: WebView = object : WebView(MockContext()) { - override fun addJavascriptInterface(`object`: Any, name: String) { - Assert.assertEquals( - MParticleJSInterface.INTERFACE_BASE_NAME + "_" + value + "_v2", - name - ) - called.value = true + val webView: WebView = + object : WebView(MockContext()) { + override fun addJavascriptInterface( + `object`: Any, + name: String, + ) { + Assert.assertEquals( + MParticleJSInterface.INTERFACE_BASE_NAME + "_" + value + "_v2", + name, + ) + called.value = true + } } - } mp.registerWebView(webView) Assert.assertTrue(called.value) } // Test that we override the token stored in the ConfigManager, if the Client provides a token. for (value in values) { - Mockito.`when`(mp.mInternal.configManager.workspaceToken) + Mockito + .`when`(mp.mInternal.configManager.workspaceToken) .thenReturn(value) val called = AndroidUtils.Mutable(false) - val webView: WebView = object : WebView(MockContext()) { - override fun addJavascriptInterface(`object`: Any, name: String) { - Assert.assertEquals( - MParticleJSInterface.INTERFACE_BASE_NAME + "_" + "hardcode" + "_v2", - name - ) - called.value = true + val webView: WebView = + object : WebView(MockContext()) { + override fun addJavascriptInterface( + `object`: Any, + name: String, + ) { + Assert.assertEquals( + MParticleJSInterface.INTERFACE_BASE_NAME + "_" + "hardcode" + "_v2", + name, + ) + called.value = true + } } - } mp.registerWebView(webView, "hardcode") Assert.assertTrue(called.value) } @@ -412,19 +438,20 @@ class MParticleTest { val instance: MParticle = InnerMockMParticle() instance.mIdentityApi = Mockito.mock(IdentityApi::class.java) Mockito.`when`(instance.Identity().currentUser).thenReturn(null) - Mockito.`when`( - instance.Identity().modify( - Mockito.any( - IdentityApiRequest::class.java - ) - ) - ).thenThrow(RuntimeException("Unexpected Modify Request")) + Mockito + .`when`( + instance.Identity().modify( + Mockito.any( + IdentityApiRequest::class.java, + ), + ), + ).thenThrow(RuntimeException("Unexpected Modify Request")) MParticle.setInstance(instance) MParticle.getInstance()!!.logPushRegistration("instanceId", "senderId") Mockito.`when`(instance.Identity().currentUser).thenReturn( Mockito.mock( - MParticleUser::class.java - ) + MParticleUser::class.java, + ), ) var ex: Exception? = null try { @@ -442,8 +469,8 @@ class MParticleTest { instance.logEvent(Mockito.mock(BaseEvent::class.java)) Mockito.verify(instance.mKitManager, Mockito.times(1)).logEvent( Mockito.any( - BaseEvent::class.java - ) + BaseEvent::class.java, + ), ) instance = InnerMockMParticle() Mockito.`when`(instance.mConfigManager.isEnabled).thenReturn(false) @@ -451,8 +478,8 @@ class MParticleTest { instance.logEvent(Mockito.mock(MPEvent::class.java)) Mockito.verify(instance.mKitManager, Mockito.times(0)).logEvent( Mockito.any( - BaseEvent::class.java - ) + BaseEvent::class.java, + ), ) } @@ -488,18 +515,21 @@ class MParticleTest { mMessageManager = Mockito.mock(MessageManager::class.java) mMessaging = Mockito.mock(MPMessagingAPI::class.java) mMedia = Mockito.mock(MPMediaAPI::class.java) - mIdentityApi = IdentityApi( - MockContext(), - mAppStateManager, - mMessageManager, - mInternal.configManager, - mKitManager, - OperatingSystem.ANDROID - ) + mIdentityApi = + IdentityApi( + MockContext(), + mAppStateManager, + mMessageManager, + mInternal.configManager, + mKitManager, + OperatingSystem.ANDROID, + ) Mockito.`when`(mKitManager.updateKits(Mockito.any())).thenReturn(KitsLoadedCallback()) - val event = MPEvent.Builder("this") - .customAttributes(HashMap()) - .build() + val event = + MPEvent + .Builder("this") + .customAttributes(HashMap()) + .build() val attributes = event.customAttributes } } diff --git a/android-core/src/test/kotlin/com/mparticle/MockMParticle.kt b/android-core/src/test/kotlin/com/mparticle/MockMParticle.kt index 8c8e71c0c..0dfdfaa7c 100644 --- a/android-core/src/test/kotlin/com/mparticle/MockMParticle.kt +++ b/android-core/src/test/kotlin/com/mparticle/MockMParticle.kt @@ -21,18 +21,21 @@ class MockMParticle : MParticle() { mMessageManager = Mockito.mock(MessageManager::class.java) mMessaging = Mockito.mock(MPMessagingAPI::class.java) mMedia = Mockito.mock(MPMediaAPI::class.java) - mIdentityApi = IdentityApi( - MockContext(), - mAppStateManager, - mMessageManager, - mInternal.configManager, - mKitManager, - OperatingSystem.ANDROID - ) + mIdentityApi = + IdentityApi( + MockContext(), + mAppStateManager, + mMessageManager, + mInternal.configManager, + mKitManager, + OperatingSystem.ANDROID, + ) Mockito.`when`(mKitManager.updateKits(Mockito.any())).thenReturn(KitsLoadedCallback()) - val event = MPEvent.Builder("this") - .customAttributes(HashMap()) - .build() + val event = + MPEvent + .Builder("this") + .customAttributes(HashMap()) + .build() val attributes = event.customAttributes } } diff --git a/android-core/src/test/kotlin/com/mparticle/RoktTest.kt b/android-core/src/test/kotlin/com/mparticle/RoktTest.kt index 840fd29f0..eac5c3d2b 100644 --- a/android-core/src/test/kotlin/com/mparticle/RoktTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/RoktTest.kt @@ -54,30 +54,31 @@ class RoktTest { val config = RoktConfig.Builder().colorMode(RoktConfig.ColorMode.DARK).build() - val callbacks = object : MpRoktEventCallback { - override fun onLoad() { - println("View loaded") + val callbacks = + object : MpRoktEventCallback { + override fun onLoad() { + println("View loaded") + } + + override fun onUnload(reason: UnloadReasons) { + println("View unloaded due to: $reason") + } + + override fun onShouldShowLoadingIndicator() { + println("Show loading indicator") + } + + override fun onShouldHideLoadingIndicator() { + println("Hide loading indicator") + } } - - override fun onUnload(reason: UnloadReasons) { - println("View unloaded due to: $reason") - } - - override fun onShouldShowLoadingIndicator() { - println("Show loading indicator") - } - - override fun onShouldHideLoadingIndicator() { - println("Hide loading indicator") - } - } rokt.selectPlacements( identifier = "testView", attributes = attributes, callbacks = callbacks, embeddedViews = placeholders, fontTypefaces = fonts, - config = config + config = config, ) verify(kitManager)?.execute("testView", attributes, callbacks, placeholders, fonts, config) @@ -101,7 +102,7 @@ class RoktTest { rokt.selectPlacements( identifier = "basicView", - attributes = HashMap() + attributes = HashMap(), ) verify(kitManager, never()).execute(any(), any(), any(), any(), any(), any()) @@ -113,7 +114,7 @@ class RoktTest { rokt.selectPlacements( identifier = "basicView", - attributes = HashMap() + attributes = HashMap(), ) verify(kitManager, never()).setWrapperSdkVersion(any()) diff --git a/android-core/src/test/kotlin/com/mparticle/SessionTest.kt b/android-core/src/test/kotlin/com/mparticle/SessionTest.kt index 093d449af..11a754274 100644 --- a/android-core/src/test/kotlin/com/mparticle/SessionTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/SessionTest.kt @@ -4,7 +4,6 @@ import org.junit.Assert import org.junit.Test class SessionTest { - @Test fun equals() { var sessionA = Session(null, null) diff --git a/android-core/src/test/kotlin/com/mparticle/audience/AudienceResponseTest.kt b/android-core/src/test/kotlin/com/mparticle/audience/AudienceResponseTest.kt index c94c76366..3033a7f7b 100644 --- a/android-core/src/test/kotlin/com/mparticle/audience/AudienceResponseTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/audience/AudienceResponseTest.kt @@ -8,7 +8,6 @@ import java.lang.reflect.Field import java.lang.reflect.Method class AudienceResponseTest { - private lateinit var classInstance: AudienceResponse @Before @@ -20,10 +19,11 @@ class AudienceResponseTest { fun parseJsonObjectTest() { val sampleJson = "{'dt':'ar','id':'54335128-0b2c-4089-a36d-8b456890dfe8','ct':1713390288601,'audience_memberships':[{'audience_id':13775},{'audience_id':13775}]}" - val method: Method = AudienceResponse::class.java.getDeclaredMethod( - "parseJsonObject", - JSONObject::class.java - ) + val method: Method = + AudienceResponse::class.java.getDeclaredMethod( + "parseJsonObject", + JSONObject::class.java, + ) method.isAccessible = true val jsonObject1 = JSONObject(sampleJson) method.invoke(classInstance, jsonObject1) @@ -33,10 +33,11 @@ class AudienceResponseTest { @Test fun parseJsonObjectTest_whenJSONIsEmpty() { val sampleJson = "{}" - val method: Method = AudienceResponse::class.java.getDeclaredMethod( - "parseJsonObject", - JSONObject::class.java - ) + val method: Method = + AudienceResponse::class.java.getDeclaredMethod( + "parseJsonObject", + JSONObject::class.java, + ) method.isAccessible = true val jsonObject1 = JSONObject(sampleJson) method.invoke(classInstance, jsonObject1) @@ -47,10 +48,11 @@ class AudienceResponseTest { @Test fun parseJsonObjectTest_whenObject_Is_NULL() { classInstance = AudienceResponse(-1, JSONObject()) - val method: Method = AudienceResponse::class.java.getDeclaredMethod( - "parseJsonObject", - JSONObject::class.java - ) + val method: Method = + AudienceResponse::class.java.getDeclaredMethod( + "parseJsonObject", + JSONObject::class.java, + ) method.isAccessible = true val jsonObject1 = null method.invoke(classInstance, jsonObject1) @@ -62,10 +64,11 @@ class AudienceResponseTest { fun parseJsonObjectTest_when_AudienceMemberships_Field_Is_Not_Available() { val sampleJson = "{'dt':'ar','id':'54335128-0b2c-4089-a36d-8b456890dfe8','ct':1713390288601}" - val method: Method = AudienceResponse::class.java.getDeclaredMethod( - "parseJsonObject", - JSONObject::class.java - ) + val method: Method = + AudienceResponse::class.java.getDeclaredMethod( + "parseJsonObject", + JSONObject::class.java, + ) method.isAccessible = true val jsonObject1 = JSONObject(sampleJson) method.invoke(classInstance, jsonObject1) @@ -77,10 +80,11 @@ class AudienceResponseTest { fun parseJsonObjectTest_when_Aaudience_id_Field_Is_Not_Available() { val sampleJson = "{'dt':'ar','id':'54335128-0b2c-4089-a36d-8b456890dfe8','ct':1713390288601,'audience_memberships':[{}]}" - val method: Method = AudienceResponse::class.java.getDeclaredMethod( - "parseJsonObject", - JSONObject::class.java - ) + val method: Method = + AudienceResponse::class.java.getDeclaredMethod( + "parseJsonObject", + JSONObject::class.java, + ) method.isAccessible = true val jsonObject1 = JSONObject(sampleJson) method.invoke(classInstance, jsonObject1) diff --git a/android-core/src/test/kotlin/com/mparticle/audience/BaseAudienceTaskTest.kt b/android-core/src/test/kotlin/com/mparticle/audience/BaseAudienceTaskTest.kt index 68a783c14..9aa6505fd 100644 --- a/android-core/src/test/kotlin/com/mparticle/audience/BaseAudienceTaskTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/audience/BaseAudienceTaskTest.kt @@ -29,66 +29,70 @@ class BaseAudienceTaskTest { } @Test - fun setFailedTest() = runBlocking { - val listenerMock = mock(AudienceTaskFailureListener::class.java) - classInstance.addFailureListener(listenerMock) - classInstance.setFailed(AudienceResponse(401, "Unauthorized user")) - val failureListenersField: Field = - BaseAudienceTask::class.java.getDeclaredField("failureListeners") - failureListenersField.isAccessible = true - Assert.assertEquals(classInstance.isComplete(), true) - Assert.assertEquals(classInstance.isSuccessful(), false) - val failureListener = failureListenersField.get(classInstance) as MutableSet<*> - Assert.assertEquals(1, failureListener.size) - } + fun setFailedTest() = + runBlocking { + val listenerMock = mock(AudienceTaskFailureListener::class.java) + classInstance.addFailureListener(listenerMock) + classInstance.setFailed(AudienceResponse(401, "Unauthorized user")) + val failureListenersField: Field = + BaseAudienceTask::class.java.getDeclaredField("failureListeners") + failureListenersField.isAccessible = true + Assert.assertEquals(classInstance.isComplete(), true) + Assert.assertEquals(classInstance.isSuccessful(), false) + val failureListener = failureListenersField.get(classInstance) as MutableSet<*> + Assert.assertEquals(1, failureListener.size) + } @Test - fun setFailedTest_when_Listener_not_register() = runBlocking { - classInstance.setFailed(AudienceResponse(401, "Unauthorized user")) - val failureListenersField: Field = - BaseAudienceTask::class.java.getDeclaredField("failureListeners") - failureListenersField.isAccessible = true - Assert.assertEquals(classInstance.isComplete(), true) - Assert.assertEquals(classInstance.isSuccessful(), false) - val failureListener = failureListenersField.get(classInstance) as MutableSet<*> - Assert.assertEquals(0, failureListener.size) - } + fun setFailedTest_when_Listener_not_register() = + runBlocking { + classInstance.setFailed(AudienceResponse(401, "Unauthorized user")) + val failureListenersField: Field = + BaseAudienceTask::class.java.getDeclaredField("failureListeners") + failureListenersField.isAccessible = true + Assert.assertEquals(classInstance.isComplete(), true) + Assert.assertEquals(classInstance.isSuccessful(), false) + val failureListener = failureListenersField.get(classInstance) as MutableSet<*> + Assert.assertEquals(0, failureListener.size) + } @Test - fun setSuccessfulTest() = runBlocking { - val listenerMock = mock(AudienceTaskSuccessListener::class.java) - classInstance.addSuccessListener(listenerMock) - val sampleJson = - "{'dt':'ar','id':'54335128-0b2c-4089-a36d-8b456890dfe8','ct':1713390288601}" - classInstance.setSuccessful(AudienceResponse(200, sampleJson)) - val isCompletedField: Field = BaseAudienceTask::class.java.getDeclaredField("isCompleted") - isCompletedField.isAccessible = true - val isSuccessfulField: Field = BaseAudienceTask::class.java.getDeclaredField("isSuccessful") - isSuccessfulField.isAccessible = true - val successListenersField: Field = - BaseAudienceTask::class.java.getDeclaredField("successListeners") - successListenersField.isAccessible = true - Assert.assertEquals(classInstance.isComplete(), true) - Assert.assertEquals(classInstance.isSuccessful(), true) - val successListener = successListenersField.get(classInstance) as MutableSet<*> - Assert.assertEquals(1, successListener.size) - } + fun setSuccessfulTest() = + runBlocking { + val listenerMock = mock(AudienceTaskSuccessListener::class.java) + classInstance.addSuccessListener(listenerMock) + val sampleJson = + "{'dt':'ar','id':'54335128-0b2c-4089-a36d-8b456890dfe8','ct':1713390288601}" + classInstance.setSuccessful(AudienceResponse(200, sampleJson)) + val isCompletedField: Field = BaseAudienceTask::class.java.getDeclaredField("isCompleted") + isCompletedField.isAccessible = true + val isSuccessfulField: Field = BaseAudienceTask::class.java.getDeclaredField("isSuccessful") + isSuccessfulField.isAccessible = true + val successListenersField: Field = + BaseAudienceTask::class.java.getDeclaredField("successListeners") + successListenersField.isAccessible = true + Assert.assertEquals(classInstance.isComplete(), true) + Assert.assertEquals(classInstance.isSuccessful(), true) + val successListener = successListenersField.get(classInstance) as MutableSet<*> + Assert.assertEquals(1, successListener.size) + } @Test - fun setSuccessfulTest_when_Listener_not_register() = runBlocking { - val sampleJson = - "{'dt':'ar','id':'54335128-0b2c-4089-a36d-8b456890dfe8','ct':1713390288601}" - classInstance.setSuccessful(AudienceResponse(200, sampleJson)) - val isCompletedField: Field = BaseAudienceTask::class.java.getDeclaredField("isCompleted") - isCompletedField.isAccessible = true - val isSuccessfulField: Field = BaseAudienceTask::class.java.getDeclaredField("isSuccessful") - isSuccessfulField.isAccessible = true - val successListenersField: Field = - BaseAudienceTask::class.java.getDeclaredField("successListeners") - successListenersField.isAccessible = true - Assert.assertEquals(classInstance.isComplete(), true) - Assert.assertEquals(classInstance.isSuccessful(), true) - val successListener = successListenersField.get(classInstance) as MutableSet<*> - Assert.assertEquals(0, successListener.size) - } + fun setSuccessfulTest_when_Listener_not_register() = + runBlocking { + val sampleJson = + "{'dt':'ar','id':'54335128-0b2c-4089-a36d-8b456890dfe8','ct':1713390288601}" + classInstance.setSuccessful(AudienceResponse(200, sampleJson)) + val isCompletedField: Field = BaseAudienceTask::class.java.getDeclaredField("isCompleted") + isCompletedField.isAccessible = true + val isSuccessfulField: Field = BaseAudienceTask::class.java.getDeclaredField("isSuccessful") + isSuccessfulField.isAccessible = true + val successListenersField: Field = + BaseAudienceTask::class.java.getDeclaredField("successListeners") + successListenersField.isAccessible = true + Assert.assertEquals(classInstance.isComplete(), true) + Assert.assertEquals(classInstance.isSuccessful(), true) + val successListener = successListenersField.get(classInstance) as MutableSet<*> + Assert.assertEquals(0, successListener.size) + } } diff --git a/android-core/src/test/kotlin/com/mparticle/commerce/CommerceEventTest.kt b/android-core/src/test/kotlin/com/mparticle/commerce/CommerceEventTest.kt index 5c74cb92d..075ec1ca7 100644 --- a/android-core/src/test/kotlin/com/mparticle/commerce/CommerceEventTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/commerce/CommerceEventTest.kt @@ -26,14 +26,22 @@ class CommerceEventTest { val event = CommerceEvent.Builder(Product.ADD_TO_CART, product).addProduct(product2).build() Assert.assertEquals("name 2", event.products?.get(1)?.name) val errorMessage = AndroidUtils.Mutable(null) - Logger.setLogHandler(object : DefaultLogHandler() { - override fun log(priority: MParticle.LogLevel, error: Throwable?, messages: String) { - if (priority == MParticle.LogLevel.ERROR) { - errorMessage.value = messages + Logger.setLogHandler( + object : DefaultLogHandler() { + override fun log( + priority: MParticle.LogLevel, + error: Throwable?, + messages: String, + ) { + if (priority == MParticle.LogLevel.ERROR) { + errorMessage.value = messages + } } - } - }) - CommerceEvent.Builder(Promotion.VIEW, Promotion().setId("whatever")).addProduct(product2) + }, + ) + CommerceEvent + .Builder(Promotion.VIEW, Promotion().setId("whatever")) + .addProduct(product2) .build() Assert.assertNotNull("Should have logged Error", errorMessage.value) errorMessage.value = null @@ -46,17 +54,26 @@ class CommerceEventTest { @Throws(Exception::class) fun testTransactionAttributes() { val product = Product.Builder("name", "sku", 0.0).build() - val event = CommerceEvent.Builder(Product.ADD_TO_CART, product) - .transactionAttributes(TransactionAttributes().setId("the id")).build() + val event = + CommerceEvent + .Builder(Product.ADD_TO_CART, product) + .transactionAttributes(TransactionAttributes().setId("the id")) + .build() Assert.assertEquals("the id", event.transactionAttributes?.id) val errorMessage = AndroidUtils.Mutable(null) - Logger.setLogHandler(object : DefaultLogHandler() { - override fun log(priority: MParticle.LogLevel, error: Throwable?, messages: String) { - if (priority == MParticle.LogLevel.ERROR) { - errorMessage.value = messages + Logger.setLogHandler( + object : DefaultLogHandler() { + override fun log( + priority: MParticle.LogLevel, + error: Throwable?, + messages: String, + ) { + if (priority == MParticle.LogLevel.ERROR) { + errorMessage.value = messages + } } - } - }) + }, + ) CommerceEvent.Builder(Product.PURCHASE, product).build() Assert.assertNotNull("Should have logged Error", errorMessage.value) } @@ -85,11 +102,15 @@ class CommerceEventTest { val product = Product.Builder("name", "sku", 0.0).build() val attributes = HashMap() attributes["cool attribute key"] = "cool attribute value" - val event = CommerceEvent.Builder(Product.ADD_TO_CART, product).customAttributes(attributes) - .nonInteraction(true).build() + val event = + CommerceEvent + .Builder(Product.ADD_TO_CART, product) + .customAttributes(attributes) + .nonInteraction(true) + .build() Assert.assertEquals( "cool attribute value", - event.customAttributeStrings?.get("cool attribute key") + event.customAttributeStrings?.get("cool attribute key"), ) } @@ -98,27 +119,42 @@ class CommerceEventTest { fun testAddPromotion() { val product = Product.Builder("name", "sku", 0.0).build() val event: CommerceEvent = - CommerceEvent.Builder("promo", Promotion().setId("promo id")).nonInteraction(true) + CommerceEvent + .Builder("promo", Promotion().setId("promo id")) + .nonInteraction(true) .build() Assert.assertEquals("promo id", event.promotions?.get(0)?.id) val errorMessage = AndroidUtils.Mutable(null) - Logger.setLogHandler(object : DefaultLogHandler() { - override fun log(priority: MParticle.LogLevel, error: Throwable?, messages: String) { - if (priority == MParticle.LogLevel.ERROR) { - errorMessage.value = messages + Logger.setLogHandler( + object : DefaultLogHandler() { + override fun log( + priority: MParticle.LogLevel, + error: Throwable?, + messages: String, + ) { + if (priority == MParticle.LogLevel.ERROR) { + errorMessage.value = messages + } } - } - }) - CommerceEvent.Builder(Product.ADD_TO_CART, product).nonInteraction(true) - .addPromotion(Promotion().setId("promo id")).build() + }, + ) + CommerceEvent + .Builder(Product.ADD_TO_CART, product) + .nonInteraction(true) + .addPromotion(Promotion().setId("promo id")) + .build() Assert.assertNotNull("Should have logged Error", errorMessage.value) } @Test @Throws(Exception::class) fun testCheckoutStep() { - val event = CommerceEvent.Builder("promo", Promotion().setId("promo id")).checkoutStep(100) - .nonInteraction(true).build() + val event = + CommerceEvent + .Builder("promo", Promotion().setId("promo id")) + .checkoutStep(100) + .nonInteraction(true) + .build() Assert.assertEquals(100, event.checkoutStep) } @@ -126,32 +162,49 @@ class CommerceEventTest { @Throws(Exception::class) fun testAddImpression() { val product = Product.Builder("name", "sku", 0.0).build() - val event = CommerceEvent.Builder(Impression("name", product)) - .addImpression(Impression("name 2", product)).nonInteraction(true).build() + val event = + CommerceEvent + .Builder(Impression("name", product)) + .addImpression(Impression("name 2", product)) + .nonInteraction(true) + .build() Assert.assertEquals("name 2", event.impressions?.get(1)?.listName) } @Test @Throws(Exception::class) fun testCheckoutOptions() { - val event = CommerceEvent.Builder("promo", Promotion().setId("promo id")).checkoutStep(100) - .checkoutOptions("some checkout options").nonInteraction(true).build() + val event = + CommerceEvent + .Builder("promo", Promotion().setId("promo id")) + .checkoutStep(100) + .checkoutOptions("some checkout options") + .nonInteraction(true) + .build() Assert.assertEquals("some checkout options", event.checkoutOptions) } @Test @Throws(Exception::class) fun testProductListName() { - val event = CommerceEvent.Builder("promo", Promotion().setId("promo id")) - .productListName("the list name").nonInteraction(true).build() + val event = + CommerceEvent + .Builder("promo", Promotion().setId("promo id")) + .productListName("the list name") + .nonInteraction(true) + .build() Assert.assertEquals("the list name", event.productListName) } @Test @Throws(Exception::class) fun testProductListSource() { - val event = CommerceEvent.Builder("promo", Promotion().setId("promo id")) - .productListSource("the list source").nonInteraction(true).build() + val event = + CommerceEvent + .Builder("promo", Promotion().setId("promo id")) + .productListSource("the list source") + .nonInteraction(true) + .build() Assert.assertEquals("the list source", event.productListSource) } @@ -163,8 +216,10 @@ class CommerceEventTest { var event = builder.build() Assert.assertNull(event.customFlags) - val attributes = RandomUtils.getInstance() - .getRandomCustomFlags(RandomUtils.getInstance().randomInt(1, 10)) + val attributes = + RandomUtils + .getInstance() + .getRandomCustomFlags(RandomUtils.getInstance().randomInt(1, 10)) for (attribute in attributes.entries) { for (value in attribute.value) { builder.addCustomFlag(attribute.key, value) diff --git a/android-core/src/test/kotlin/com/mparticle/commerce/ProductTest.kt b/android-core/src/test/kotlin/com/mparticle/commerce/ProductTest.kt index 2ca42375e..f71bff1cb 100644 --- a/android-core/src/test/kotlin/com/mparticle/commerce/ProductTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/commerce/ProductTest.kt @@ -39,15 +39,17 @@ class ProductTest { @Test fun testSerializationDeserialization() { Product.setEqualityComparator { product1, product2 -> product1.toString() == product2.toString() } - val product = Product.Builder("product name", "product sku", 301.45) - .brand("product brand") - .category("product category") - .couponCode("product coupon code") - .name("product name") - .position(4) - .variant("product variant") - .quantity(12.1) - .build() + val product = + Product + .Builder("product name", "product sku", 301.45) + .brand("product brand") + .category("product category") + .couponCode("product coupon code") + .name("product name") + .position(4) + .variant("product variant") + .quantity(12.1) + .build() val productJson = product.toJson() val product2 = Product.fromJson(productJson) Assert.assertEquals(product, product2) diff --git a/android-core/src/test/kotlin/com/mparticle/consent/ConsentStateTest.kt b/android-core/src/test/kotlin/com/mparticle/consent/ConsentStateTest.kt index 7fa15159a..24c626889 100644 --- a/android-core/src/test/kotlin/com/mparticle/consent/ConsentStateTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/consent/ConsentStateTest.kt @@ -7,24 +7,54 @@ class ConsentStateTest { @Test fun removeAllGDPRConsentState() { val state = ConsentState.builder() - Assert.assertEquals(0, state.build().gdprConsentState.size.toLong()) + Assert.assertEquals( + 0, + state + .build() + .gdprConsentState.size + .toLong(), + ) state.addGDPRConsentState("foo-purpose-1", GDPRConsent.builder(false).build()) state.addGDPRConsentState("foo-purpose-2", GDPRConsent.builder(false).build()) state.setCCPAConsentState(CCPAConsent.builder(false).build()) - Assert.assertEquals(2, state.build().gdprConsentState.size.toLong()) + Assert.assertEquals( + 2, + state + .build() + .gdprConsentState.size + .toLong(), + ) state.setGDPRConsentState(null) state.removeCCPAConsentState() - Assert.assertEquals(0, state.build().gdprConsentState.size.toLong()) + Assert.assertEquals( + 0, + state + .build() + .gdprConsentState.size + .toLong(), + ) Assert.assertNull(state.build().ccpaConsentState) } @Test fun addGDPRConsentState() { val state = ConsentState.builder() - Assert.assertEquals(0, state.build().gdprConsentState.size.toLong()) + Assert.assertEquals( + 0, + state + .build() + .gdprConsentState.size + .toLong(), + ) state.addGDPRConsentState("foo-purpose-1", GDPRConsent.builder(false).build()) state.addGDPRConsentState("foo-purpose-2", GDPRConsent.builder(false).build()) - Assert.assertEquals(2, state.build().gdprConsentState.size.toLong()) + Assert.assertEquals( + 2, + state + .build() + .gdprConsentState.size + .toLong(), + ) } @Test @@ -32,16 +62,34 @@ class ConsentStateTest { val state = ConsentState.builder() state.addGDPRConsentState("foo-purpose-1", GDPRConsent.builder(false).build()) state.addGDPRConsentState("foo-purpose-2", GDPRConsent.builder(false).build()) - Assert.assertEquals(2, state.build().gdprConsentState.size.toLong()) + Assert.assertEquals( + 2, + state + .build() + .gdprConsentState.size + .toLong(), + ) state.removeGDPRConsentState("foo-purpose-1") - Assert.assertEquals(1, state.build().gdprConsentState.size.toLong()) + Assert.assertEquals( + 1, + state + .build() + .gdprConsentState.size + .toLong(), + ) state.removeGDPRConsentState("") } @Test fun addCCPAConsentState() { val state = ConsentState.builder() - Assert.assertEquals(0, state.build().gdprConsentState.size.toLong()) + Assert.assertEquals( + 0, + state + .build() + .gdprConsentState.size + .toLong(), + ) state.setCCPAConsentState(CCPAConsent.builder(true).build()) Assert.assertNotNull(state.build().ccpaConsentState) } @@ -49,7 +97,13 @@ class ConsentStateTest { @Test fun addCCPAConsentStateMultiple() { val state = ConsentState.builder() - Assert.assertEquals(0, state.build().gdprConsentState.size.toLong()) + Assert.assertEquals( + 0, + state + .build() + .gdprConsentState.size + .toLong(), + ) state.setCCPAConsentState(CCPAConsent.builder(true).build()) state.setCCPAConsentState(CCPAConsent.builder(false).build()) Assert.assertNotNull(state.build().ccpaConsentState) @@ -59,7 +113,13 @@ class ConsentStateTest { @Test fun removeCCPAConsentState() { val state = ConsentState.builder() - Assert.assertEquals(0, state.build().gdprConsentState.size.toLong()) + Assert.assertEquals( + 0, + state + .build() + .gdprConsentState.size + .toLong(), + ) state.setCCPAConsentState(CCPAConsent.builder(true).build()) Assert.assertNotNull(state.build().ccpaConsentState) state.removeCCPAConsentState() @@ -78,24 +138,32 @@ class ConsentStateTest { @Test @Throws(Exception::class) fun testSerializeMultipleConsent() { - val state = ConsentState.withConsentState( - ConsentState.builder() - .addGDPRConsentState("foo-purpose-1", GDPRConsent.builder(false).build()) - .addGDPRConsentState("foo-purpose-2", GDPRConsent.builder(true).build()) - .setCCPAConsentState(CCPAConsent.builder(false).build()) + val state = + ConsentState.withConsentState( + ConsentState + .builder() + .addGDPRConsentState("foo-purpose-1", GDPRConsent.builder(false).build()) + .addGDPRConsentState("foo-purpose-2", GDPRConsent.builder(true).build()) + .setCCPAConsentState(CCPAConsent.builder(false).build()) + .build() + .toString(), + ) + Assert.assertNotNull(state) + Assert.assertEquals( + 2, + state .build() - .toString() + .gdprConsentState.size + .toLong(), ) - Assert.assertNotNull(state) - Assert.assertEquals(2, state.build().gdprConsentState.size.toLong()) Assert.assertNotNull(state.build().ccpaConsentState) Assert.assertEquals( false, - state.build().gdprConsentState["foo-purpose-1"]?.isConsented + state.build().gdprConsentState["foo-purpose-1"]?.isConsented, ) Assert.assertEquals( true, - state.build().gdprConsentState["foo-purpose-2"]?.isConsented + state.build().gdprConsentState["foo-purpose-2"]?.isConsented, ) Assert.assertEquals(false, state.build().ccpaConsentState?.isConsented) } @@ -103,23 +171,31 @@ class ConsentStateTest { @Test @Throws(Exception::class) fun testCopyMultipleConsent() { - val state = ConsentState.withConsentState( - ConsentState.builder() - .addGDPRConsentState("foo-purpose-1", GDPRConsent.builder(false).build()) - .addGDPRConsentState("foo-purpose-2", GDPRConsent.builder(true).build()) - .setCCPAConsentState(CCPAConsent.builder(true).build()) + val state = + ConsentState.withConsentState( + ConsentState + .builder() + .addGDPRConsentState("foo-purpose-1", GDPRConsent.builder(false).build()) + .addGDPRConsentState("foo-purpose-2", GDPRConsent.builder(true).build()) + .setCCPAConsentState(CCPAConsent.builder(true).build()) + .build(), + ) + Assert.assertNotNull(state) + Assert.assertEquals( + 2, + state .build() + .gdprConsentState.size + .toLong(), ) - Assert.assertNotNull(state) - Assert.assertEquals(2, state.build().gdprConsentState.size.toLong()) Assert.assertNotNull(state.build().ccpaConsentState) Assert.assertEquals( false, - state.build().gdprConsentState["foo-purpose-1"]?.isConsented + state.build().gdprConsentState["foo-purpose-1"]?.isConsented, ) Assert.assertEquals( true, - state.build().gdprConsentState["foo-purpose-2"]?.isConsented + state.build().gdprConsentState["foo-purpose-2"]?.isConsented, ) Assert.assertEquals(true, state.build().ccpaConsentState?.isConsented) } @@ -127,107 +203,145 @@ class ConsentStateTest { @Test @Throws(Exception::class) fun testSerializeWithAllValues() { - val state = ConsentState.withConsentState( - ConsentState.builder().addGDPRConsentState( - "foo-purpose-1", - GDPRConsent.builder(false) - .document("foo document") - .hardwareId("foo hardware id") - .location("foo location") - .timestamp(5L) - .build() + val state = + ConsentState.withConsentState( + ConsentState + .builder() + .addGDPRConsentState( + "foo-purpose-1", + GDPRConsent + .builder(false) + .document("foo document") + .hardwareId("foo hardware id") + .location("foo location") + .timestamp(5L) + .build(), + ).setCCPAConsentState( + CCPAConsent + .builder(true) + .document("bar document") + .hardwareId("bar hardware id") + .location("bar location") + .timestamp(6L) + .build(), + ).build() + .toString(), ) - .setCCPAConsentState( - CCPAConsent.builder(true) - .document("bar document") - .hardwareId("bar hardware id") - .location("bar location") - .timestamp(6L) - .build() - ) - .build().toString() - ) Assert.assertNotNull(state) - Assert.assertEquals(1, state.build().gdprConsentState.size.toLong()) + Assert.assertEquals( + 1, + state + .build() + .gdprConsentState.size + .toLong(), + ) Assert.assertEquals( false, - state.build().gdprConsentState["foo-purpose-1"]?.isConsented + state.build().gdprConsentState["foo-purpose-1"]?.isConsented, ) Assert.assertEquals( "foo document", - state.build().gdprConsentState["foo-purpose-1"]?.document + state.build().gdprConsentState["foo-purpose-1"]?.document, ) Assert.assertEquals( "foo hardware id", - state.build().gdprConsentState["foo-purpose-1"]?.hardwareId + state.build().gdprConsentState["foo-purpose-1"]?.hardwareId, ) Assert.assertEquals( "foo location", - state.build().gdprConsentState["foo-purpose-1"]?.location + state.build().gdprConsentState["foo-purpose-1"]?.location, ) Assert.assertEquals( 5, - state.build().gdprConsentState["foo-purpose-1"]!!.timestamp + state.build().gdprConsentState["foo-purpose-1"]!!.timestamp, ) Assert.assertNotNull(state.build().ccpaConsentState) Assert.assertEquals(true, state.build().ccpaConsentState?.isConsented) Assert.assertEquals("bar document", state.build().ccpaConsentState?.document) Assert.assertEquals("bar hardware id", state.build().ccpaConsentState?.hardwareId) Assert.assertEquals("bar location", state.build().ccpaConsentState?.location) - Assert.assertEquals(6, state.build().ccpaConsentState?.timestamp?.toInt()) + Assert.assertEquals( + 6, + state + .build() + .ccpaConsentState + ?.timestamp + ?.toInt(), + ) } @Test @Throws(Exception::class) fun testCopyWithAllValues() { - val state = ConsentState.withConsentState( - ConsentState.builder().addGDPRConsentState( - "foo-purpose-1", - GDPRConsent.builder(false) - .document("foo document") - .hardwareId("foo hardware id") - .location("foo location") - .timestamp(5L) - .build() + val state = + ConsentState.withConsentState( + ConsentState + .builder() + .addGDPRConsentState( + "foo-purpose-1", + GDPRConsent + .builder(false) + .document("foo document") + .hardwareId("foo hardware id") + .location("foo location") + .timestamp(5L) + .build(), + ).setCCPAConsentState( + CCPAConsent + .builder(true) + .document("bar document") + .hardwareId("bar hardware id") + .location("bar location") + .timestamp(6L) + .build(), + ).build() + .toString(), ) - .setCCPAConsentState( - CCPAConsent.builder(true) - .document("bar document") - .hardwareId("bar hardware id") - .location("bar location") - .timestamp(6L) - .build() - ) - .build().toString() - ) Assert.assertNotNull(state) - Assert.assertEquals(1, state.build().gdprConsentState.size.toLong()) + Assert.assertEquals( + 1, + state + .build() + .gdprConsentState.size + .toLong(), + ) Assert.assertEquals( false, - state.build().gdprConsentState["foo-purpose-1"]?.isConsented + state.build().gdprConsentState["foo-purpose-1"]?.isConsented, ) Assert.assertEquals( "foo document", - state.build().gdprConsentState["foo-purpose-1"]?.document + state.build().gdprConsentState["foo-purpose-1"]?.document, ) Assert.assertEquals( "foo hardware id", - state.build().gdprConsentState["foo-purpose-1"]?.hardwareId + state.build().gdprConsentState["foo-purpose-1"]?.hardwareId, ) Assert.assertEquals( "foo location", - state.build().gdprConsentState["foo-purpose-1"]?.location + state.build().gdprConsentState["foo-purpose-1"]?.location, ) Assert.assertEquals( 5, - state.build().gdprConsentState["foo-purpose-1"]?.timestamp?.toInt() + state + .build() + .gdprConsentState["foo-purpose-1"] + ?.timestamp + ?.toInt(), ) Assert.assertNotNull(state.build().ccpaConsentState) Assert.assertEquals(true, state.build().ccpaConsentState?.isConsented) Assert.assertEquals("bar document", state.build().ccpaConsentState?.document) Assert.assertEquals("bar hardware id", state.build().ccpaConsentState?.hardwareId) Assert.assertEquals("bar location", state.build().ccpaConsentState?.location) - Assert.assertEquals(6, state.build().ccpaConsentState?.timestamp?.toInt()) + Assert.assertEquals( + 6, + state + .build() + .ccpaConsentState + ?.timestamp + ?.toInt(), + ) } @Test diff --git a/android-core/src/test/kotlin/com/mparticle/identity/AliasRequestTest.kt b/android-core/src/test/kotlin/com/mparticle/identity/AliasRequestTest.kt index 935df5403..e5725a63d 100644 --- a/android-core/src/test/kotlin/com/mparticle/identity/AliasRequestTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/identity/AliasRequestTest.kt @@ -36,11 +36,13 @@ class AliasRequestTest { val endTime = random.nextLong() val sourceMpid = random.nextLong() val destinationMpid = random.nextLong() - val builder = AliasRequest.builder() - .destinationMpid(destinationMpid) - .sourceMpid(sourceMpid) - .startTime(startTime) - .endTime(endTime) + val builder = + AliasRequest + .builder() + .destinationMpid(destinationMpid) + .sourceMpid(sourceMpid) + .startTime(startTime) + .endTime(endTime) val request = builder.build() Assert.assertEquals(sourceMpid, request.sourceMpid) Assert.assertEquals(destinationMpid, request.destinationMpid) @@ -51,8 +53,14 @@ class AliasRequestTest { @Test fun testMaxWindowEnforcement() { MParticle.setInstance(MockMParticle()) - Mockito.`when`(MParticle.getInstance()?.Internal()?.configManager?.aliasMaxWindow) - .thenReturn(1) + Mockito + .`when`( + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.aliasMaxWindow, + ).thenReturn(1) val sourceUser = Mockito.mock(MParticleUser::class.java) val destinationUser = Mockito.mock(MParticleUser::class.java) val earliestLegalStartTime = System.currentTimeMillis() - 24 * 60 * 60 * 1000 diff --git a/android-core/src/test/kotlin/com/mparticle/identity/IdentityApiTest.kt b/android-core/src/test/kotlin/com/mparticle/identity/IdentityApiTest.kt index c46fca4be..4f07b30f3 100644 --- a/android-core/src/test/kotlin/com/mparticle/identity/IdentityApiTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/identity/IdentityApiTest.kt @@ -29,62 +29,78 @@ class IdentityApiTest { @Test fun testAliasUsersValidationRejection() { val identityApi = IdentityApi() - identityApi.mMessageManager = object : MessageManager() { - override fun logAliasRequest(aliasRequest: AliasRequest) { - Assert.fail("should not logged Alias Request:\n$aliasRequest") + identityApi.mMessageManager = + object : MessageManager() { + override fun logAliasRequest(aliasRequest: AliasRequest) { + Assert.fail("should not logged Alias Request:\n$aliasRequest") + } } - } // missing previousMpid - var request = AliasRequest.builder() - .destinationMpid(123) - .startTime(1) - .endTime(2) - .build() + var request = + AliasRequest + .builder() + .destinationMpid(123) + .startTime(1) + .endTime(2) + .build() Assert.assertFalse(identityApi.aliasUsers(request)) // missing newMpid - request = AliasRequest.builder() - .sourceMpid(123) - .startTime(1) - .endTime(2) - .build() + request = + AliasRequest + .builder() + .sourceMpid(123) + .startTime(1) + .endTime(2) + .build() Assert.assertFalse(identityApi.aliasUsers(request)) // newMpid and previousMpid are not unique - request = AliasRequest.builder() - .destinationMpid(123) - .sourceMpid(123) - .startTime(1) - .endTime(2) - .build() + request = + AliasRequest + .builder() + .destinationMpid(123) + .sourceMpid(123) + .startTime(1) + .endTime(2) + .build() Assert.assertFalse(identityApi.aliasUsers(request)) // endTime before startTime - request = AliasRequest.builder() - .destinationMpid(123) - .sourceMpid(456) - .startTime(2) - .endTime(1) - .build() + request = + AliasRequest + .builder() + .destinationMpid(123) + .sourceMpid(456) + .startTime(2) + .endTime(1) + .build() Assert.assertFalse(identityApi.aliasUsers(request)) // endTime and or startTime do not exist - request = AliasRequest.builder() - .destinationMpid(1) - .sourceMpid(2) - .build() + request = + AliasRequest + .builder() + .destinationMpid(1) + .sourceMpid(2) + .build() Assert.assertFalse(identityApi.aliasUsers(request)) - request = AliasRequest.builder() - .destinationMpid(1) - .sourceMpid(2) - .startTime(3) - .build() + request = + AliasRequest + .builder() + .destinationMpid(1) + .sourceMpid(2) + .startTime(3) + .build() Assert.assertFalse(identityApi.aliasUsers(request)) - request = AliasRequest.builder() - .destinationMpid(1) - .sourceMpid(2) - .endTime(3).build() + request = + AliasRequest + .builder() + .destinationMpid(1) + .sourceMpid(2) + .endTime(3) + .build() Assert.assertFalse(identityApi.aliasUsers(request)) } @@ -92,29 +108,30 @@ class IdentityApiTest { fun testAliasUsersValidationAcceptance() { val identityApi = IdentityApi() val requestMade = AndroidUtils.Mutable(false) - identityApi.mMessageManager = object : MessageManager() { - override fun logAliasRequest(aliasRequest: AliasRequest) { - requestMade.value = true + identityApi.mMessageManager = + object : MessageManager() { + override fun logAliasRequest(aliasRequest: AliasRequest) { + requestMade.value = true + } } - } - val request = AliasRequest.builder() - .destinationMpid(1) - .sourceMpid(2) - .startTime(3) - .endTime(4) - .build() + val request = + AliasRequest + .builder() + .destinationMpid(1) + .sourceMpid(2) + .startTime(3) + .endTime(4) + .build() Assert.assertTrue(identityApi.aliasUsers(request)) Assert.assertTrue(requestMade.value) } - internal inner class MockUser(private var mpid: Long, private var mpLastSeenTime: Long) : - AbstractMParticleUser() { - override fun getLastSeenTime(): Long { - return mpLastSeenTime - } + internal inner class MockUser( + private var mpid: Long, + private var mpLastSeenTime: Long, + ) : AbstractMParticleUser() { + override fun getLastSeenTime(): Long = mpLastSeenTime - override fun getId(): Long { - return mpid - } + override fun getId(): Long = mpid } } diff --git a/android-core/src/test/kotlin/com/mparticle/identity/MParticleIdentityClientImplTest.kt b/android-core/src/test/kotlin/com/mparticle/identity/MParticleIdentityClientImplTest.kt index 92f0476d7..eeb05a97f 100644 --- a/android-core/src/test/kotlin/com/mparticle/identity/MParticleIdentityClientImplTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/identity/MParticleIdentityClientImplTest.kt @@ -16,8 +16,8 @@ class MParticleIdentityClientImplTest { Assert.assertEquals( type, MParticleIdentityClientImpl.getIdentityType( - MParticleIdentityClientImpl.getStringValue(type) - ) + MParticleIdentityClientImpl.getStringValue(type), + ), ) } } @@ -29,15 +29,16 @@ class MParticleIdentityClientImplTest { // to update this method val osStringValues = HashSet() for (operatingSystem in MParticle.OperatingSystem.values()) { - val osString = MParticleIdentityClientImpl( - Mockito.mock( - Context::class.java - ), - Mockito.mock( - ConfigManager::class.java - ), - operatingSystem - ).operatingSystemString + val osString = + MParticleIdentityClientImpl( + Mockito.mock( + Context::class.java, + ), + Mockito.mock( + ConfigManager::class.java, + ), + operatingSystem, + ).operatingSystemString Assert.assertFalse(osStringValues.contains(osString)) osStringValues.add(osString) } diff --git a/android-core/src/test/kotlin/com/mparticle/identity/MParticleUserDelegateTest.kt b/android-core/src/test/kotlin/com/mparticle/identity/MParticleUserDelegateTest.kt index 1c1651012..34f192294 100644 --- a/android-core/src/test/kotlin/com/mparticle/identity/MParticleUserDelegateTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/identity/MParticleUserDelegateTest.kt @@ -7,28 +7,30 @@ import org.mockito.Mockito class MParticleUserDelegateTest { @Test fun setUserIdentitiesNull() { - val mockDelegate = Mockito.mock( - MParticleUserDelegate::class.java - ) + val mockDelegate = + Mockito.mock( + MParticleUserDelegate::class.java, + ) MParticleUserDelegate.setUserIdentities(mockDelegate, null, 123L) - Mockito.verify( - mockDelegate, - Mockito.never() - ) - .setUserIdentity( + Mockito + .verify( + mockDelegate, + Mockito.never(), + ).setUserIdentity( Mockito.anyString(), Mockito.any( - IdentityType::class.java + IdentityType::class.java, ), - Mockito.anyLong() + Mockito.anyLong(), ) } @Test fun setUserIdentitiesCustomerIdEmailInOrder() { - val mockDelegate = Mockito.mock( - MParticleUserDelegate::class.java - ) + val mockDelegate = + Mockito.mock( + MParticleUserDelegate::class.java, + ) val identities = HashMap() for (type in IdentityType.values()) { identities[type] = "foo-" + type.name @@ -37,36 +39,40 @@ class MParticleUserDelegateTest { val orderVerifier = Mockito.inOrder(mockDelegate) // first customer id - orderVerifier.verify(mockDelegate) + orderVerifier + .verify(mockDelegate) .setUserIdentity( Mockito.eq("foo-" + IdentityType.CustomerId), Mockito.eq(IdentityType.CustomerId), - Mockito.eq(123L) + Mockito.eq(123L), ) // then email - orderVerifier.verify(mockDelegate) + orderVerifier + .verify(mockDelegate) .setUserIdentity( Mockito.eq("foo-" + IdentityType.Email), Mockito.eq(IdentityType.Email), - Mockito.eq(123L) + Mockito.eq(123L), ) // then verify everything for (type in IdentityType.values()) { - Mockito.verify(mockDelegate) + Mockito + .verify(mockDelegate) .setUserIdentity( Mockito.eq("foo-$type"), Mockito.eq(type), - Mockito.eq(123L) + Mockito.eq(123L), ) } } @Test fun setUserIdentitiesNoCustomerIdEmail() { - val mockDelegate = Mockito.mock( - MParticleUserDelegate::class.java - ) + val mockDelegate = + Mockito.mock( + MParticleUserDelegate::class.java, + ) val identities = HashMap() for (type in IdentityType.values()) { if (type != IdentityType.CustomerId && type != IdentityType.Email) { @@ -76,11 +82,12 @@ class MParticleUserDelegateTest { MParticleUserDelegate.setUserIdentities(mockDelegate, identities, 123L) for (type in IdentityType.values()) { if (type != IdentityType.CustomerId && type != IdentityType.Email) { - Mockito.verify(mockDelegate) + Mockito + .verify(mockDelegate) .setUserIdentity( Mockito.eq("foo-$type"), Mockito.eq(type), - Mockito.eq(123L) + Mockito.eq(123L), ) } } diff --git a/android-core/src/test/kotlin/com/mparticle/identity/MParticleUserTest.kt b/android-core/src/test/kotlin/com/mparticle/identity/MParticleUserTest.kt index 386549e40..b1ca27fd7 100644 --- a/android-core/src/test/kotlin/com/mparticle/identity/MParticleUserTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/identity/MParticleUserTest.kt @@ -37,20 +37,21 @@ class MParticleUserTest { val identities = JSONArray() identities.put(JSONObject("{ \"n\": 8, \"i\": \"alias test\", \"dfs\": 1473869816521, \"f\": true }")) Mockito.`when`(id?.mMessageManager?.getUserIdentityJson(defaultMpId)).thenReturn(identities) - Mockito.`when`( - id?.mMessageManager?.logUserIdentityChangeMessage( - Mockito.any( - JSONObject::class.java - ), - Mockito.any(JSONObject::class.java), - Mockito.any( - JSONArray::class.java + Mockito + .`when`( + id?.mMessageManager?.logUserIdentityChangeMessage( + Mockito.any( + JSONObject::class.java, + ), + Mockito.any(JSONObject::class.java), + Mockito.any( + JSONArray::class.java, + ), + ArgumentMatchers.eq(defaultMpId), ), - ArgumentMatchers.eq(defaultMpId) + ).thenThrow( + AssertionError("Should not log redundent User Identity"), ) - ).thenThrow( - AssertionError("Should not log redundent User Identity") - ) val ids = HashMap() ids[IdentityType.Alias] = "alias test" (id?.currentUser as MParticleUserImpl?)?.userIdentities = ids @@ -64,26 +65,30 @@ class MParticleUserTest { Mockito.`when`(id?.mMessageManager?.getUserIdentityJson(1)).thenReturn(identities) (id?.currentUser as MParticleUserImpl?)?.setUserIdentity( IdentityType.Email, - "email value 2" - ) - val argument1 = ArgumentCaptor.forClass( - JSONObject::class.java - ) - val argument2 = ArgumentCaptor.forClass( - JSONObject::class.java - ) - val argument3 = ArgumentCaptor.forClass( - JSONArray::class.java - ) - Mockito.verify( - id!!.mMessageManager, - Mockito.times(1) - ).logUserIdentityChangeMessage( - argument1.capture(), - argument2.capture(), - argument3.capture(), - ArgumentMatchers.eq(defaultMpId) + "email value 2", ) + val argument1 = + ArgumentCaptor.forClass( + JSONObject::class.java, + ) + val argument2 = + ArgumentCaptor.forClass( + JSONObject::class.java, + ) + val argument3 = + ArgumentCaptor.forClass( + JSONArray::class.java, + ) + Mockito + .verify( + id!!.mMessageManager, + Mockito.times(1), + ).logUserIdentityChangeMessage( + argument1.capture(), + argument2.capture(), + argument3.capture(), + ArgumentMatchers.eq(defaultMpId), + ) val oldIdentity = argument2.value Assert.assertEquals(oldIdentity["i"], "email value 1") Assert.assertEquals(oldIdentity["n"], 7) @@ -94,15 +99,15 @@ class MParticleUserTest { Assert.assertEquals(newIdentity["n"], 7) Assert.assertEquals(newIdentity.getDouble("dfs"), 1473869816521.0, 100.0) Assert.assertEquals(newIdentity["f"], false) - Mockito.verify( - MParticle.getInstance()?.Internal()?.kitManager, - Mockito.times(1) - ) - ?.setUserIdentity( + Mockito + .verify( + MParticle.getInstance()?.Internal()?.kitManager, + Mockito.times(1), + )?.setUserIdentity( ArgumentMatchers.eq("email value 2"), ArgumentMatchers.eq( - IdentityType.Email - ) + IdentityType.Email, + ), ) val allIdentities = argument3.value Assert.assertEquals(1, allIdentities.length().toLong()) @@ -115,11 +120,13 @@ class MParticleUserTest { mp?.currentUser?.removeUserAttribute("")?.let { Assert.assertFalse(it) } mp?.currentUser?.removeUserAttribute("")?.let { Assert.assertFalse(it) } mp?.currentUser?.removeUserAttribute("test")?.let { Assert.assertTrue(it) } - Mockito.verify( - mp?.mMessageManager, - Mockito.times(1) - )?.removeUserAttribute("test", 1) - Mockito.verify(MParticle.getInstance()!!.Internal().kitManager, Mockito.times(1)) + Mockito + .verify( + mp?.mMessageManager, + Mockito.times(1), + )?.removeUserAttribute("test", 1) + Mockito + .verify(MParticle.getInstance()!!.Internal().kitManager, Mockito.times(1)) .removeUserAttribute("test", 1) } @@ -129,71 +136,80 @@ class MParticleUserTest { id?.currentUser?.removeUserAttribute("")?.let { Assert.assertFalse(it) } id?.currentUser?.removeUserAttribute("")?.let { Assert.assertFalse(it) } id?.currentUser?.removeUserAttribute("test")?.let { Assert.assertTrue(it) } - Mockito.verify( - id?.mMessageManager, - Mockito.times(1) - )?.removeUserAttribute("test", 1) - Mockito.verify( - mp?.Internal()?.kitManager, - Mockito.times(1) - )?.removeUserAttribute("test", 1) + Mockito + .verify( + id?.mMessageManager, + Mockito.times(1), + )?.removeUserAttribute("test", 1) + Mockito + .verify( + mp?.Internal()?.kitManager, + Mockito.times(1), + )?.removeUserAttribute("test", 1) } @Test @Throws(Exception::class) fun testGetAllUserAttributes() { - val listener = Mockito.mock( - UserAttributeListener::class.java - ) + val listener = + Mockito.mock( + UserAttributeListener::class.java, + ) id?.currentUser?.getUserAttributes(listener) - Mockito.verify( - mp?.Identity()?.mMessageManager, - Mockito.times(1) - )?.getUserAttributes( - ArgumentMatchers.any( - UserAttributeListenerWrapper::class.java - ), - ArgumentMatchers.eq(defaultMpId) - ) - val typedListener = Mockito.mock( - TypedUserAttributeListener::class.java - ) + Mockito + .verify( + mp?.Identity()?.mMessageManager, + Mockito.times(1), + )?.getUserAttributes( + ArgumentMatchers.any( + UserAttributeListenerWrapper::class.java, + ), + ArgumentMatchers.eq(defaultMpId), + ) + val typedListener = + Mockito.mock( + TypedUserAttributeListener::class.java, + ) id?.currentUser?.getUserAttributes(typedListener) - Mockito.verify( - mp?.Identity()?.mMessageManager, - Mockito.times(2) - )?.getUserAttributes( - ArgumentMatchers.any( - UserAttributeListenerWrapper::class.java - ), - ArgumentMatchers.eq(defaultMpId) - ) + Mockito + .verify( + mp?.Identity()?.mMessageManager, + Mockito.times(2), + )?.getUserAttributes( + ArgumentMatchers.any( + UserAttributeListenerWrapper::class.java, + ), + ArgumentMatchers.eq(defaultMpId), + ) } @Test @Throws(Exception::class) fun testRemoveUserIdentityWhenNoneExist() { val identities = JSONArray() - Mockito.`when`(mp?.Identity()?.mMessageManager?.getUserIdentityJson(defaultMpId)) + Mockito + .`when`(mp?.Identity()?.mMessageManager?.getUserIdentityJson(defaultMpId)) .thenReturn(identities) (id?.currentUser as MParticleUserImpl?)?.setUserIdentity(IdentityType.Alias, null) - Mockito.verify( - mp?.Identity()?.mMessageManager, - Mockito.times(0) - )?.logUserIdentityChangeMessage( - Mockito.any(JSONObject::class.java), - Mockito.any(JSONObject::class.java), - Mockito.any(JSONArray::class.java), - ArgumentMatchers.eq(defaultMpId) - ) - Mockito.verify( - mp?.Internal()?.kitManager, - Mockito.times(0) - )?.removeUserIdentity( - Mockito.any( - IdentityType::class.java + Mockito + .verify( + mp?.Identity()?.mMessageManager, + Mockito.times(0), + )?.logUserIdentityChangeMessage( + Mockito.any(JSONObject::class.java), + Mockito.any(JSONObject::class.java), + Mockito.any(JSONArray::class.java), + ArgumentMatchers.eq(defaultMpId), + ) + Mockito + .verify( + mp?.Internal()?.kitManager, + Mockito.times(0), + )?.removeUserIdentity( + Mockito.any( + IdentityType::class.java, + ), ) - ) } @Test @@ -201,39 +217,45 @@ class MParticleUserTest { fun testRemoveUserIdentity() { val identities = JSONArray() identities.put(JSONObject("{ \"n\": 7, \"i\": \"email value 1\", \"dfs\": 1473869816521, \"f\": true }")) - Mockito.`when`(mp?.Identity()?.mMessageManager?.getUserIdentityJson(defaultMpId)) + Mockito + .`when`(mp?.Identity()?.mMessageManager?.getUserIdentityJson(defaultMpId)) .thenReturn(identities) (id?.currentUser as MParticleUserImpl?)?.setUserIdentity(IdentityType.Email, null) - val argument2 = ArgumentCaptor.forClass( - JSONObject::class.java - ) - val argument3 = ArgumentCaptor.forClass( - JSONArray::class.java - ) - val argument4 = ArgumentCaptor.forClass( - Long::class.java - ) - Mockito.verify( - mp?.Identity()?.mMessageManager, - Mockito.times(1) - )?.logUserIdentityChangeMessage( - Mockito.isNull(JSONObject::class.java), - argument2.capture(), - argument3.capture(), - argument4.capture() - ) + val argument2 = + ArgumentCaptor.forClass( + JSONObject::class.java, + ) + val argument3 = + ArgumentCaptor.forClass( + JSONArray::class.java, + ) + val argument4 = + ArgumentCaptor.forClass( + Long::class.java, + ) + Mockito + .verify( + mp?.Identity()?.mMessageManager, + Mockito.times(1), + )?.logUserIdentityChangeMessage( + Mockito.isNull(JSONObject::class.java), + argument2.capture(), + argument3.capture(), + argument4.capture(), + ) val oldIdentity = argument2.value Assert.assertEquals(oldIdentity["i"], "email value 1") Assert.assertEquals(oldIdentity["n"], 7) Assert.assertEquals(oldIdentity.getDouble("dfs"), 1473869816521.0, 100.0) Assert.assertEquals(oldIdentity["f"], true) Assert.assertTrue(argument4.value == defaultMpId) - Mockito.verify( - mp?.Internal()?.kitManager, - Mockito.times(1) - )?.removeUserIdentity( - IdentityType.Email - ) + Mockito + .verify( + mp?.Internal()?.kitManager, + Mockito.times(1), + )?.removeUserIdentity( + IdentityType.Email, + ) val allIdentities = argument3.value Assert.assertEquals(0, allIdentities.length().toLong()) } @@ -243,45 +265,50 @@ class MParticleUserTest { fun testAddUserIdentity() { val identities = JSONArray() identities.put(JSONObject("{ \"n\": 7, \"i\": \"email value 1\", \"dfs\": 1473869816521, \"f\": true }")) - Mockito.`when`(mp?.Identity()?.mMessageManager?.getUserIdentityJson(Mockito.anyLong())) + Mockito + .`when`(mp?.Identity()?.mMessageManager?.getUserIdentityJson(Mockito.anyLong())) .thenReturn(identities) (id?.currentUser as MParticleUserImpl?)?.setUserIdentity(IdentityType.Alias, "alias test") - val argument2 = ArgumentCaptor.forClass( - JSONObject::class.java - ) - val argument3 = ArgumentCaptor.forClass( - JSONArray::class.java - ) - val argument4 = ArgumentCaptor.forClass( - Long::class.java - ) - Mockito.verify( - mp?.Identity()?.mMessageManager, - Mockito.times(1) - )?.logUserIdentityChangeMessage( - argument2.capture(), - Mockito.isNull(JSONObject::class.java), - argument3.capture(), - argument4.capture() - ) + val argument2 = + ArgumentCaptor.forClass( + JSONObject::class.java, + ) + val argument3 = + ArgumentCaptor.forClass( + JSONArray::class.java, + ) + val argument4 = + ArgumentCaptor.forClass( + Long::class.java, + ) + Mockito + .verify( + mp?.Identity()?.mMessageManager, + Mockito.times(1), + )?.logUserIdentityChangeMessage( + argument2.capture(), + Mockito.isNull(JSONObject::class.java), + argument3.capture(), + argument4.capture(), + ) val oldIdentity = argument2.value Assert.assertEquals(oldIdentity["i"], "alias test") Assert.assertEquals( oldIdentity["n"], - IdentityType.Alias.value + IdentityType.Alias.value, ) Assert.assertEquals( oldIdentity.getDouble("dfs"), System.currentTimeMillis().toDouble(), - 1000.0 + 1000.0, ) Assert.assertEquals(oldIdentity["f"], true) Assert.assertTrue(argument4.value == defaultMpId) Mockito.verify(mp?.Internal()?.kitManager, Mockito.times(1))?.setUserIdentity( ArgumentMatchers.eq("alias test"), ArgumentMatchers.eq( - IdentityType.Alias - ) + IdentityType.Alias, + ), ) val allIdentities = argument3.value Assert.assertEquals(2, allIdentities.length().toLong()) diff --git a/android-core/src/test/kotlin/com/mparticle/internal/AppStateManagerTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/AppStateManagerTest.kt index 7b8990aa7..8edc5a2af 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/AppStateManagerTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/AppStateManagerTest.kt @@ -27,9 +27,10 @@ import org.powermock.modules.junit4.PowerMockRunner class AppStateManagerTest { lateinit var manager: AppStateManager private var mockContext: MockApplication? = null - private val activity = Mockito.mock( - Activity::class.java - ) + private val activity = + Mockito.mock( + Activity::class.java, + ) private var prefs: MockSharedPreferences? = null private var messageManager: MessageManager? = null @@ -68,7 +69,8 @@ class AppStateManagerTest { fun testOnActivityStarted() { Assert.assertEquals(true, manager.isBackgrounded()) manager.onActivityStarted(activity) - Mockito.verify(MParticle.getInstance()!!.Internal().kitManager, Mockito.times(1)) + Mockito + .verify(MParticle.getInstance()!!.Internal().kitManager, Mockito.times(1)) .onActivityStarted(activity) } @@ -87,14 +89,16 @@ class AppStateManagerTest { fun testIntentParameterParsing() { var mockIntent = Mockito.mock(Intent::class.java) Mockito.`when`(mockIntent.dataString).thenReturn("this is data string 1") - var mockCallingActivity = Mockito.mock( - ComponentName::class.java - ) + var mockCallingActivity = + Mockito.mock( + ComponentName::class.java, + ) Mockito.`when`(mockCallingActivity.packageName).thenReturn("package name 1") Mockito.`when`(activity.callingActivity).thenReturn(mockCallingActivity) Mockito.`when`(activity.intent).thenReturn(mockIntent) manager.onActivityResumed(activity) - Mockito.verify(messageManager, Mockito.times(1)) + Mockito + .verify(messageManager, Mockito.times(1)) ?.logStateTransition( Mockito.anyString(), Mockito.anyString(), @@ -103,7 +107,7 @@ class AppStateManagerTest { Mockito.eq("package name 1"), Mockito.anyLong(), Mockito.anyLong(), - Mockito.anyInt() + Mockito.anyInt(), ) mockIntent = Mockito.mock(Intent::class.java) Mockito.`when`(mockIntent.dataString).thenReturn("this is data string 2") @@ -114,7 +118,8 @@ class AppStateManagerTest { manager.onActivityPaused(activity) Thread.sleep(1000) manager.onActivityResumed(activity) - Mockito.verify(messageManager, Mockito.times(1)) + Mockito + .verify(messageManager, Mockito.times(1)) ?.logStateTransition( Mockito.anyString(), Mockito.anyString(), @@ -123,7 +128,7 @@ class AppStateManagerTest { Mockito.eq("package name 2"), Mockito.anyLong(), Mockito.anyLong(), - Mockito.anyInt() + Mockito.anyInt(), ) } @@ -134,25 +139,28 @@ class AppStateManagerTest { */ @Test @Throws(Exception::class) - fun testSecondActivityStart() = runTest(StandardTestDispatcher()) { - manager.onActivityPaused(activity) - Thread.sleep(1000) - Assert.assertEquals(true, manager.isBackgrounded()) - manager.onActivityResumed(activity) - val activity2 = Mockito.mock( - Activity::class.java - ) - val activity3 = Mockito.mock( - Activity::class.java - ) - manager.onActivityPaused(activity2) - manager.onActivityPaused(activity3) - Thread.sleep(1000) - Assert.assertEquals(false, manager.isBackgrounded()) - manager.onActivityPaused(activity) - Thread.sleep(1000) - Assert.assertEquals(true, manager.isBackgrounded()) - } + fun testSecondActivityStart() = + runTest(StandardTestDispatcher()) { + manager.onActivityPaused(activity) + Thread.sleep(1000) + Assert.assertEquals(true, manager.isBackgrounded()) + manager.onActivityResumed(activity) + val activity2 = + Mockito.mock( + Activity::class.java, + ) + val activity3 = + Mockito.mock( + Activity::class.java, + ) + manager.onActivityPaused(activity2) + manager.onActivityPaused(activity3) + Thread.sleep(1000) + Assert.assertEquals(false, manager.isBackgrounded()) + manager.onActivityPaused(activity) + Thread.sleep(1000) + Assert.assertEquals(true, manager.isBackgrounded()) + } @Test @Throws(Exception::class) @@ -167,7 +175,7 @@ class AppStateManagerTest { manager.onActivityResumed(activity) Assert.assertTrue( manager.session.backgroundTime.toString() + " ms", - manager.session.backgroundTime in 1000..1199 + manager.session.backgroundTime in 1000..1199, ) } @@ -192,21 +200,19 @@ class AppStateManagerTest { fun testShouldEndSession() { val isTimedOut = AndroidUtils.Mutable(false) val isBackground = AndroidUtils.Mutable(false) - val session = AndroidUtils.Mutable(object : InternalSession() { - override fun isTimedOut(sessionTimeout: Int): Boolean { - return isTimedOut.value - } - }) + val session = + AndroidUtils.Mutable( + object : InternalSession() { + override fun isTimedOut(sessionTimeout: Int): Boolean = isTimedOut.value + }, + ) session.value?.mSessionStartTime = 1 - manager = object : AppStateManager(MockContext(), true) { - override fun isBackgrounded(): Boolean { - return isBackground.value - } + manager = + object : AppStateManager(MockContext(), true) { + override fun isBackgrounded(): Boolean = isBackground.value - override fun fetchSession(): InternalSession { - return session.value!! + override fun fetchSession(): InternalSession = session.value!! } - } manager.session = session.value!! val configManager = Mockito.mock(ConfigManager::class.java) manager.setConfigManager(configManager) diff --git a/android-core/src/test/kotlin/com/mparticle/internal/ApplicationContextWrapperTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/ApplicationContextWrapperTest.kt index 1a67319f5..cbbbcb5c2 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/ApplicationContextWrapperTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/ApplicationContextWrapperTest.kt @@ -21,6 +21,7 @@ import java.util.LinkedList /** * Created by wpassidomo on 2/21/17. */ + /** * Test that if you add a bunch on mock activiies that it will play back in the same order. * Test that it won't crash if there aren't anuy activiies added. @@ -35,19 +36,21 @@ class ApplicationContextWrapperTest { var activity2 = Mockito.mock(Activity::class.java) var activity3 = Mockito.mock(Activity::class.java) private lateinit var activityLifecycleCallbackRecorder: ActivityLifecycleCallbackRecorder - var applicationContextWrapper = MockApplicationContextWrapper( - Mockito.mock( - Application::class.java + var applicationContextWrapper = + MockApplicationContextWrapper( + Mockito.mock( + Application::class.java, + ), ) - ) var activity1Ref = WeakReference(activity1) var activity2Ref = WeakReference(activity2) var activity3Ref = WeakReference(activity3) var bundle1 = Mockito.mock(Bundle::class.java) var bundle2 = Mockito.mock(Bundle::class.java) - inner class MockApplicationContextWrapper internal constructor(application: Application?) : - ApplicationContextWrapper(application!!) { + inner class MockApplicationContextWrapper internal constructor( + application: Application?, + ) : ApplicationContextWrapper(application!!) { override fun attachBaseContext(base: Context) {} } @@ -139,20 +142,20 @@ class ApplicationContextWrapperTest { applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_CREATED, WeakReference(activity2), - bundle2 - ) + bundle2, + ), ) testList.addLast( applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_STARTED, - WeakReference(activity2) - ) + WeakReference(activity2), + ), ) testList.addLast( applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_RESUMED, - WeakReference(activity2) - ) + WeakReference(activity2), + ), ) return testList } @@ -163,50 +166,53 @@ class ApplicationContextWrapperTest { applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_CREATED, WeakReference(activity1), - bundle1 - ) + bundle1, + ), ) testList.addLast( applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_STARTED, - WeakReference(activity1) - ) + WeakReference(activity1), + ), ) testList.addLast( applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_RESUMED, - WeakReference(activity1) - ) + WeakReference(activity1), + ), ) testList.addLast( applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_PAUSED, - WeakReference(activity1) - ) + WeakReference(activity1), + ), ) testList.addLast( applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_SAVE_INSTANCE_STATE, WeakReference(activity1), - bundle1 - ) + bundle1, + ), ) testList.addLast( applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_STOPPED, - WeakReference(activity1) - ) + WeakReference(activity1), + ), ) testList.addLast( applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_DESTROYED, - WeakReference(activity1) - ) + WeakReference(activity1), + ), ) return testList } - private fun assertListEquals(list1: List, list2: List) { + private fun assertListEquals( + list1: List, + list2: List, + ) { Assert.assertEquals(list1.size.toLong(), list2.size.toLong()) for (i in list1.indices) { Assert.assertTrue(list1[i] == list2[i]) @@ -217,13 +223,17 @@ class ApplicationContextWrapperTest { internal inner class ActivityLifecycleCallbackRecordTester : ActivityLifecycleCallbacks { var lifeCycleEvents = LinkedList() var MAX_LIST_SIZE = 10 - override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { + + override fun onActivityCreated( + activity: Activity, + savedInstanceState: Bundle?, + ) { recordedLifecycleList.addLast( applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_CREATED, WeakReference(activity), - savedInstanceState - ) + savedInstanceState, + ), ) } @@ -231,8 +241,8 @@ class ApplicationContextWrapperTest { recordedLifecycleList.addLast( applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_STARTED, - WeakReference(activity) - ) + WeakReference(activity), + ), ) } @@ -240,8 +250,8 @@ class ApplicationContextWrapperTest { recordedLifecycleList.addLast( applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_RESUMED, - WeakReference(activity) - ) + WeakReference(activity), + ), ) } @@ -249,8 +259,8 @@ class ApplicationContextWrapperTest { recordedLifecycleList.addLast( applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_PAUSED, - WeakReference(activity) - ) + WeakReference(activity), + ), ) } @@ -258,18 +268,21 @@ class ApplicationContextWrapperTest { recordedLifecycleList.addLast( applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_STOPPED, - WeakReference(activity) - ) + WeakReference(activity), + ), ) } - override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) { + override fun onActivitySaveInstanceState( + activity: Activity, + outState: Bundle, + ) { recordedLifecycleList.addLast( applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_SAVE_INSTANCE_STATE, WeakReference(activity), - outState - ) + outState, + ), ) } @@ -277,8 +290,8 @@ class ApplicationContextWrapperTest { recordedLifecycleList.addLast( applicationContextWrapper.getLifeCycleEventInstance( ApplicationContextWrapper.MethodType.ON_DESTROYED, - WeakReference(activity) - ) + WeakReference(activity), + ), ) } diff --git a/android-core/src/test/kotlin/com/mparticle/internal/BaseMPMessageTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/BaseMPMessageTest.kt index fac65c92b..d31b2a27c 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/BaseMPMessageTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/BaseMPMessageTest.kt @@ -16,33 +16,43 @@ class BaseMPMessageTest { fun testEventLength() { val event = MPEvent.Builder("test name", MParticle.EventType.Navigation).build() val session = InternalSession() - val message = BaseMPMessage.Builder(Constants.MessageType.EVENT) - .name(event.eventName) - .timestamp(1235) - .length(event.length) - .attributes(MPUtility.enforceAttributeConstraints(event.customAttributeStrings)) - .build(session, null, 1) + val message = + BaseMPMessage + .Builder(Constants.MessageType.EVENT) + .name(event.eventName) + .timestamp(1235) + .length(event.length) + .attributes(MPUtility.enforceAttributeConstraints(event.customAttributeStrings)) + .build(session, null, 1) Assert.assertNull(message.opt("el")) Assert.assertNull(message.attributes) val info: MutableMap = HashMap(1) info["EventLength"] = "321" - val event2 = MPEvent.Builder("test name", MParticle.EventType.Navigation).duration(123.0) - .customAttributes(info).build() - val message2 = BaseMPMessage.Builder(Constants.MessageType.EVENT) - .name(event2.eventName) - .timestamp(1235) - .length(event2.length) - .attributes(MPUtility.enforceAttributeConstraints(event2.customAttributeStrings)) - .build(session, null, 1) + val event2 = + MPEvent + .Builder("test name", MParticle.EventType.Navigation) + .duration(123.0) + .customAttributes(info) + .build() + val message2 = + BaseMPMessage + .Builder(Constants.MessageType.EVENT) + .name(event2.eventName) + .timestamp(1235) + .length(event2.length) + .attributes(MPUtility.enforceAttributeConstraints(event2.customAttributeStrings)) + .build(session, null, 1) Assert.assertEquals(message2.attributes.getString("EventLength"), "321") val event3 = MPEvent.Builder("test name", MParticle.EventType.Navigation).duration(123.0).build() - val message3 = BaseMPMessage.Builder(Constants.MessageType.EVENT) - .name(event3.eventName) - .timestamp(1235) - .length(event3.length) - .attributes(MPUtility.enforceAttributeConstraints(event.customAttributeStrings)) - .build(session, null, 1) + val message3 = + BaseMPMessage + .Builder(Constants.MessageType.EVENT) + .name(event3.eventName) + .timestamp(1235) + .length(event3.length) + .attributes(MPUtility.enforceAttributeConstraints(event.customAttributeStrings)) + .build(session, null, 1) Assert.assertEquals(message3.attributes.getString("EventLength"), "123") } @@ -51,10 +61,13 @@ class BaseMPMessageTest { fun testNullCartOnCommerceEvent() { MParticle.setInstance(MockMParticle()) val event = - CommerceEvent.Builder(Product.ADD_TO_CART, Product.Builder("foo", "bar", 10.0).build()) + CommerceEvent + .Builder(Product.ADD_TO_CART, Product.Builder("foo", "bar", 10.0).build()) .build() - val builder = MPCommerceMessage.Builder(event) - .timestamp(12345) as MPCommerceMessage.Builder + val builder = + MPCommerceMessage + .Builder(event) + .timestamp(12345) as MPCommerceMessage.Builder val message = builder.build(InternalSession(), null, 0) Assert.assertNotNull(message) } diff --git a/android-core/src/test/kotlin/com/mparticle/internal/ConfigManagerTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/ConfigManagerTest.kt index 18c253cd5..47681f60a 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/ConfigManagerTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/ConfigManagerTest.kt @@ -29,18 +29,19 @@ class ConfigManagerTest { @Throws(Exception::class) fun setUp() { context = MockContext() - manager = ConfigManager( - context, - MParticle.Environment.Production, - "some api key", - "some api secret", - null, - null, - null, - null, - null, - null - ) + manager = + ConfigManager( + context, + MParticle.Environment.Production, + "some api key", + "some api secret", + null, + null, + null, + null, + null, + null, + ) mockMp = MockMParticle() MParticle.setInstance(mockMp) manager.updateConfig(JSONObject(sampleConfig)) @@ -48,18 +49,19 @@ class ConfigManagerTest { @Test fun testInitialization() { - manager = ConfigManager( - context, - MParticle.Environment.Production, - "key1", - "secret1", - null, - null, - null, - null, - null, - null - ) + manager = + ConfigManager( + context, + MParticle.Environment.Production, + "key1", + "secret1", + null, + null, + null, + null, + null, + null, + ) Assert.assertEquals("key1", manager.apiKey) Assert.assertEquals("secret1", manager.apiSecret) Assert.assertEquals(MParticle.Environment.Production, ConfigManager.getEnvironment()) @@ -71,18 +73,19 @@ class ConfigManagerTest { Assert.assertEquals(MParticle.Environment.Production, ConfigManager.getEnvironment()) // updates key/secret if one is non-null - manager = ConfigManager( - context, - MParticle.Environment.Development, - "key2", - null, - null, - null, - null, - null, - null, - null - ) + manager = + ConfigManager( + context, + MParticle.Environment.Development, + "key2", + null, + null, + null, + null, + null, + null, + null, + ) Assert.assertEquals("key2", manager.apiKey) Assert.assertNull(manager.apiSecret) Assert.assertEquals(MParticle.Environment.Development, ConfigManager.getEnvironment()) @@ -96,7 +99,8 @@ class ConfigManagerTest { json.put("test", "value") manager.saveConfigJson(json) val `object` = - ConfigManager.sPreferences.getString(ConfigManager.CONFIG_JSON, null) + ConfigManager.sPreferences + .getString(ConfigManager.CONFIG_JSON, null) ?.let { JSONObject(it) } Assert.assertNotNull(`object`) } @@ -115,7 +119,8 @@ class ConfigManagerTest { Assert.assertEquals(5, ConfigManager.getPushKeys(context).length().toLong()) manager.updateConfig(JSONObject()) val `object` = - ConfigManager.sPreferences.getString(ConfigManager.CONFIG_JSON, null) + ConfigManager.sPreferences + .getString(ConfigManager.CONFIG_JSON, null) ?.let { JSONObject(it) } if (`object` != null) { Assert.assertTrue(!`object`.keys().hasNext()) @@ -128,7 +133,8 @@ class ConfigManagerTest { manager.updateConfig(JSONObject(sampleConfig)) manager.reloadCoreConfig(JSONObject()) val `object` = - ConfigManager.sPreferences.getString(ConfigManager.CONFIG_JSON, null) + ConfigManager.sPreferences + .getString(ConfigManager.CONFIG_JSON, null) ?.let { JSONObject(it) } `object`?.keys()?.hasNext()?.let { Assert.assertTrue(it) } } @@ -143,15 +149,23 @@ class ConfigManagerTest { kitStatusMap[5] = KitStatus.STOPPED kitStatusMap[4] = KitStatus.ACTIVE kitStatusMap[6] = KitStatus.NOT_CONFIGURED - Mockito.`when`( - MParticle.getInstance()?.Internal()?.kitManager?.kitStatus - ) - .thenReturn(kitStatusMap) + Mockito + .`when`( + MParticle + .getInstance() + ?.Internal() + ?.kitManager + ?.kitStatus, + ).thenReturn(kitStatusMap) Assert.assertEquals("1,2,4,5", manager.activeModuleIds) - Mockito.`when`( - MParticle.getInstance()?.Internal()?.kitManager?.kitStatus - ) - .thenReturn(HashMap()) + Mockito + .`when`( + MParticle + .getInstance() + ?.Internal() + ?.kitManager + ?.kitStatus, + ).thenReturn(HashMap()) Assert.assertEquals("", manager.activeModuleIds) } @@ -304,7 +318,7 @@ class ConfigManagerTest { fun testGetBreadcrumbLimit() { Assert.assertEquals( UserStorage.DEFAULT_BREADCRUMB_LIMIT.toLong(), - ConfigManager.getBreadcrumbLimit(context).toLong() + ConfigManager.getBreadcrumbLimit(context).toLong(), ) } @@ -346,11 +360,15 @@ class ConfigManagerTest { @Test @Throws(Exception::class) fun testShouldTrigger() { - var message = BaseMPMessage.Builder(Constants.MessageType.COMMERCE_EVENT) - .build(InternalSession(), null, 1) + var message = + BaseMPMessage + .Builder(Constants.MessageType.COMMERCE_EVENT) + .build(InternalSession(), null, 1) Assert.assertTrue(manager.shouldTrigger(message)) - message = BaseMPMessage.Builder(Constants.MessageType.PUSH_RECEIVED) - .build(InternalSession(), null, 1) + message = + BaseMPMessage + .Builder(Constants.MessageType.PUSH_RECEIVED) + .build(InternalSession(), null, 1) Assert.assertTrue(manager.shouldTrigger(message)) } @@ -383,8 +401,10 @@ class ConfigManagerTest { Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) manager.setIntegrationAttributes(1, null) Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) - ConfigManager.sPreferences.edit() - .putString(ATTRIBUTES, "{\"1\":{\"test-key\":\"test-value\"}}").apply() + ConfigManager.sPreferences + .edit() + .putString(ATTRIBUTES, "{\"1\":{\"test-key\":\"test-value\"}}") + .apply() Assert.assertTrue(ConfigManager.sPreferences.contains(ATTRIBUTES)) manager.setIntegrationAttributes(1, null) Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) @@ -397,8 +417,10 @@ class ConfigManagerTest { val attributes: Map = HashMap() manager.setIntegrationAttributes(1, attributes) Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) - ConfigManager.sPreferences.edit() - .putString(ATTRIBUTES, "{\"1\":{\"test-key\":\"test-value\"}}").apply() + ConfigManager.sPreferences + .edit() + .putString(ATTRIBUTES, "{\"1\":{\"test-key\":\"test-value\"}}") + .apply() Assert.assertTrue(ConfigManager.sPreferences.contains(ATTRIBUTES)) manager.setIntegrationAttributes(1, attributes) Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) @@ -417,8 +439,8 @@ class ConfigManagerTest { "{\"1\":{\"test-key\":\"value 2\"},\"12\":{\"test-key\":\"value 3\"}}", ConfigManager.sPreferences.getString( ATTRIBUTES, - null - ) + null, + ), ) } @@ -427,17 +449,22 @@ class ConfigManagerTest { fun testGetKitIntegrationAttributes() { Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) Assert.assertEquals(0, manager.getIntegrationAttributes(1).size.toLong()) - ConfigManager.sPreferences.edit().putString( - ATTRIBUTES, - "{\"1\":{\"test-key\":\"value 2\"},\"12\":{\"test-key\":\"value 3\"}}" - ).apply() + ConfigManager.sPreferences + .edit() + .putString( + ATTRIBUTES, + "{\"1\":{\"test-key\":\"value 2\"},\"12\":{\"test-key\":\"value 3\"}}", + ).apply() var attributes = manager.getIntegrationAttributes(1) Assert.assertEquals(1, attributes.size.toLong()) Assert.assertEquals("value 2", attributes["test-key"]) attributes = manager.getIntegrationAttributes(12) Assert.assertEquals(1, attributes.size.toLong()) Assert.assertEquals("value 3", attributes["test-key"]) - ConfigManager.sPreferences.edit().remove(ATTRIBUTES).apply() + ConfigManager.sPreferences + .edit() + .remove(ATTRIBUTES) + .apply() Assert.assertEquals(0, manager.getIntegrationAttributes(1).size.toLong()) Assert.assertEquals(0, manager.getIntegrationAttributes(12).size.toLong()) } @@ -447,15 +474,20 @@ class ConfigManagerTest { fun testGetAllIntegrationAttributes() { Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) Assert.assertNull(manager.integrationAttributes) - ConfigManager.sPreferences.edit().putString( - ATTRIBUTES, - "{\"1\":{\"test-key\":\"value 2\"},\"12\":{\"test-key\":\"value 3\"}}" - ).apply() + ConfigManager.sPreferences + .edit() + .putString( + ATTRIBUTES, + "{\"1\":{\"test-key\":\"value 2\"},\"12\":{\"test-key\":\"value 3\"}}", + ).apply() val attributes = manager.integrationAttributes Assert.assertEquals(2, attributes.length().toLong()) Assert.assertEquals("value 2", attributes.getJSONObject("1")["test-key"]) Assert.assertEquals("value 3", attributes.getJSONObject("12")["test-key"]) - ConfigManager.sPreferences.edit().remove(ATTRIBUTES).apply() + ConfigManager.sPreferences + .edit() + .remove(ATTRIBUTES) + .apply() Assert.assertNull(manager.integrationAttributes) } @@ -472,7 +504,7 @@ class ConfigManagerTest { Assert.assertEquals(1, manager.userIdentityJson.length().toLong()) Assert.assertEquals( 1473869816521L, - manager.userIdentityJson.getJSONObject(0).getLong("dfs") + manager.userIdentityJson.getJSONObject(0).getLong("dfs"), ) } @@ -571,13 +603,15 @@ class ConfigManagerTest { // test set via config val maxWindow = ran.nextInt() - val jsonObject = JSONObject() - .put(ConfigManager.ALIAS_MAX_WINDOW, maxWindow) + val jsonObject = + JSONObject() + .put(ConfigManager.ALIAS_MAX_WINDOW, maxWindow) manager.updateConfig(jsonObject) Assert.assertEquals(maxWindow.toLong(), manager.aliasMaxWindow.toLong()) } private val callbackResult = AndroidUtils.Mutable(null) + private fun getCallbackResult(): Long? { val result = callbackResult.value callbackResult.value = null @@ -587,18 +621,19 @@ class ConfigManagerTest { @Test @Throws(JSONException::class) fun testETag() { - manager = ConfigManager( - context, - MParticle.Environment.Production, - "some api key", - "some api secret", - null, - null, - null, - null, - null, - null - ) + manager = + ConfigManager( + context, + MParticle.Environment.Production, + "some api key", + "some api secret", + null, + null, + null, + null, + null, + null, + ) val newEtag = RandomUtils().getAlphaString(24) // test default value Assert.assertNull(manager.etag) @@ -611,18 +646,19 @@ class ConfigManagerTest { @Test @Throws(JSONException::class) fun testLastModified() { - manager = ConfigManager( - context, - MParticle.Environment.Production, - "some api key", - "some api secret", - null, - null, - null, - null, - null, - null - ) + manager = + ConfigManager( + context, + MParticle.Environment.Production, + "some api key", + "some api secret", + null, + null, + null, + null, + null, + null, + ) val lastModified = abs(ran.nextLong()).toString() // test default value @@ -668,7 +704,7 @@ class ConfigManagerTest { for (i in 0 until configSize) { newConfigJson.put( randomUtils.getAlphaNumericString(8), - randomUtils.getAlphaNumericString(12) + randomUtils.getAlphaNumericString(12), ) } diff --git a/android-core/src/test/kotlin/com/mparticle/internal/DeviceAttributesTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/DeviceAttributesTest.kt index 8737eb104..a44452afa 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/DeviceAttributesTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/DeviceAttributesTest.kt @@ -18,8 +18,11 @@ class DeviceAttributesTest { fun testCollectAppInfo() { MParticle.setInstance(MockMParticle()) val context = MockContext() - context.getSharedPreferences(null, 0).edit() - .putString(Constants.PrefKeys.INSTALL_REFERRER, "install referrer").apply() + context + .getSharedPreferences(null, 0) + .edit() + .putString(Constants.PrefKeys.INSTALL_REFERRER, "install referrer") + .apply() val appInfo = DeviceAttributes(MParticle.OperatingSystem.ANDROID).getAppInfo(context) Assert.assertTrue(appInfo.getString("apn") == "com.mparticle.test") Assert.assertTrue(appInfo.getString("abn") == "42") @@ -67,10 +70,10 @@ class DeviceAttributesTest { null, null, null, - null + null, ).deleteUserStorage( context, - ConfigManager.getMpid(context) + ConfigManager.getMpid(context), ) var appInfo: JSONObject? = null val launchCount = 20 diff --git a/android-core/src/test/kotlin/com/mparticle/internal/KitFrameworkWrapperTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/KitFrameworkWrapperTest.kt index c51ed1888..6e5126bc7 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/KitFrameworkWrapperTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/KitFrameworkWrapperTest.kt @@ -41,20 +41,22 @@ class KitFrameworkWrapperTest { @Test @Throws(Exception::class) fun testLoadKitLibrary() { - val mockConfigManager = Mockito.mock( - ConfigManager::class.java - ) - Mockito.`when`(mockConfigManager.latestKitConfiguration).thenReturn(JSONArray()) - val wrapper = KitFrameworkWrapper( + val mockConfigManager = Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - mockConfigManager, - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + ConfigManager::class.java, + ) + Mockito.`when`(mockConfigManager.latestKitConfiguration).thenReturn(JSONArray()) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + mockConfigManager, + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Assert.assertFalse(wrapper.kitsLoaded) Assert.assertFalse(wrapper.frameworkLoadAttempted) wrapper.loadKitLibrary() @@ -65,16 +67,17 @@ class KitFrameworkWrapperTest { @Test @Throws(Exception::class) fun testDisableQueuing() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Assert.assertFalse(wrapper.kitsLoaded) wrapper.kitsLoaded = false val event = MPEvent.Builder("example").build() @@ -92,16 +95,17 @@ class KitFrameworkWrapperTest { @PrepareForTest(CommerceEvent::class) @Throws(Exception::class) fun testReplayEvents() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Mockito.`when`(wrapper.mCoreCallbacks.getPushInstanceId()).thenReturn("instanceId") Mockito.`when`(wrapper.mCoreCallbacks.getPushSenderId()).thenReturn("1234545") MParticle.setInstance(MockMParticle()) @@ -109,20 +113,26 @@ class KitFrameworkWrapperTest { val mockKitManager = Mockito.mock(KitManager::class.java) wrapper.setKitManager(mockKitManager) val registration = PushRegistration("instance id", "1234545") - Mockito.`when`( - MParticle.getInstance()!!.Internal().configManager.pushRegistration - ).thenReturn(registration) + Mockito + .`when`( + MParticle + .getInstance()!! + .Internal() + .configManager.pushRegistration, + ).thenReturn(registration) wrapper.replayEvents() - Mockito.verify( - mockKitManager, - Mockito.times(0) - ).onPushRegistration(Mockito.anyString(), Mockito.anyString()) + Mockito + .verify( + mockKitManager, + Mockito.times(0), + ).onPushRegistration(Mockito.anyString(), Mockito.anyString()) wrapper.onPushRegistration("whatever", "whatever") wrapper.replayEvents() - Mockito.verify( - mockKitManager, - Mockito.times(1) - ).onPushRegistration(Mockito.anyString(), Mockito.anyString()) + Mockito + .verify( + mockKitManager, + Mockito.times(1), + ).onPushRegistration(Mockito.anyString(), Mockito.anyString()) wrapper.replayEvents() wrapper.kitsLoaded = false val event = MPEvent.Builder("example").build() @@ -133,54 +143,63 @@ class KitFrameworkWrapperTest { wrapper.logEvent(screenEvent) wrapper.setUserAttribute("a key", "a value", 1) wrapper.logEvent(commerceEvent) - Mockito.verify( - mockKitManager, - Mockito.times(0) - ).logEvent(Mockito.any(MPEvent::class.java)) - Mockito.verify( - mockKitManager, - Mockito.times(0) - ).logScreen(Mockito.any(MPEvent::class.java)) - Mockito.verify( - mockKitManager, - Mockito.times(0) - ).logEvent(Mockito.any(CommerceEvent::class.java)) - Mockito.verify( - mockKitManager, - Mockito.times(0) - ).setUserAttribute(Mockito.anyString(), Mockito.anyString(), Mockito.anyLong()) + Mockito + .verify( + mockKitManager, + Mockito.times(0), + ).logEvent(Mockito.any(MPEvent::class.java)) + Mockito + .verify( + mockKitManager, + Mockito.times(0), + ).logScreen(Mockito.any(MPEvent::class.java)) + Mockito + .verify( + mockKitManager, + Mockito.times(0), + ).logEvent(Mockito.any(CommerceEvent::class.java)) + Mockito + .verify( + mockKitManager, + Mockito.times(0), + ).setUserAttribute(Mockito.anyString(), Mockito.anyString(), Mockito.anyLong()) wrapper.replayEvents() - Mockito.verify( - mockKitManager, - Mockito.times(1) - ).logEvent(Mockito.any(MPEvent::class.java)) - Mockito.verify( - mockKitManager, - Mockito.times(1) - ).logScreen(Mockito.any(MPEvent::class.java)) - Mockito.verify( - mockKitManager, - Mockito.times(1) - ).logEvent(Mockito.any(CommerceEvent::class.java)) - Mockito.verify( - mockKitManager, - Mockito.times(1) - ).setUserAttribute(Mockito.eq("a key"), Mockito.eq("a value"), Mockito.anyLong()) + Mockito + .verify( + mockKitManager, + Mockito.times(1), + ).logEvent(Mockito.any(MPEvent::class.java)) + Mockito + .verify( + mockKitManager, + Mockito.times(1), + ).logScreen(Mockito.any(MPEvent::class.java)) + Mockito + .verify( + mockKitManager, + Mockito.times(1), + ).logEvent(Mockito.any(CommerceEvent::class.java)) + Mockito + .verify( + mockKitManager, + Mockito.times(1), + ).setUserAttribute(Mockito.eq("a key"), Mockito.eq("a value"), Mockito.anyLong()) } @Test @Throws(Exception::class) fun testReplayAndDisableQueue() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) wrapper.kitsLoaded = false wrapper.replayAndDisableQueue() } @@ -188,136 +207,157 @@ class KitFrameworkWrapperTest { @Test @Throws(Exception::class) fun testQueueStringAttribute() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Assert.assertNull(wrapper.attributeQueue) wrapper.kitsLoaded = false wrapper.queueAttributeSet("a key", "a value", 1) Assert.assertEquals(wrapper.attributeQueue.peek()?.key, "a key") Assert.assertEquals(wrapper.attributeQueue.peek()?.value, "a value") Assert.assertEquals( - wrapper.attributeQueue.peek()?.type?.toLong(), - KitFrameworkWrapper.AttributeChange.SET_ATTRIBUTE.toLong() + wrapper.attributeQueue + .peek() + ?.type + ?.toLong(), + KitFrameworkWrapper.AttributeChange.SET_ATTRIBUTE.toLong(), ) } @Test @Throws(Exception::class) fun testQueueNullAttribute() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Assert.assertNull(wrapper.attributeQueue) wrapper.kitsLoaded = false wrapper.queueAttributeTag("a key", 1) Assert.assertEquals(wrapper.attributeQueue.peek()?.key, "a key") Assert.assertNull(wrapper.attributeQueue.peek()?.value) Assert.assertEquals( - wrapper.attributeQueue.peek()?.type?.toLong(), - KitFrameworkWrapper.AttributeChange.TAG.toLong() + wrapper.attributeQueue + .peek() + ?.type + ?.toLong(), + KitFrameworkWrapper.AttributeChange.TAG.toLong(), ) } @Test @Throws(Exception::class) fun testQueueListAttribute() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Assert.assertNull(wrapper.attributeQueue) wrapper.kitsLoaded = false wrapper.queueAttributeSet("a key", ArrayList(), 1) Assert.assertEquals(wrapper.attributeQueue.peek()?.key, "a key") Assert.assertEquals(wrapper.attributeQueue.peek()?.value, ArrayList()) Assert.assertEquals( - wrapper.attributeQueue.peek()?.type?.toLong(), - KitFrameworkWrapper.AttributeChange.SET_ATTRIBUTE.toLong() + wrapper.attributeQueue + .peek() + ?.type + ?.toLong(), + KitFrameworkWrapper.AttributeChange.SET_ATTRIBUTE.toLong(), ) } @Test @Throws(Exception::class) fun testQueueAttributeRemoval() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Assert.assertNull(wrapper.attributeQueue) wrapper.kitsLoaded = false wrapper.queueAttributeRemove("a key", 1) Assert.assertEquals(wrapper.attributeQueue.peek()?.key, "a key") Assert.assertEquals(wrapper.attributeQueue.peek()?.value, null) Assert.assertEquals( - wrapper.attributeQueue.peek()?.type?.toLong(), - KitFrameworkWrapper.AttributeChange.REMOVE_ATTRIBUTE.toLong() + wrapper.attributeQueue + .peek() + ?.type + ?.toLong(), + KitFrameworkWrapper.AttributeChange.REMOVE_ATTRIBUTE.toLong(), ) } @Test @Throws(Exception::class) fun testQueueAttributeIncrement() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Assert.assertNull(wrapper.attributeQueue) wrapper.kitsLoaded = false wrapper.queueAttributeIncrement("a key", 3, "3", 1) Assert.assertEquals(wrapper.attributeQueue.peek()?.key, "a key") Assert.assertEquals(wrapper.attributeQueue.peek()?.value, "3") Assert.assertEquals( - wrapper.attributeQueue.peek()?.type?.toLong(), - KitFrameworkWrapper.AttributeChange.INCREMENT_ATTRIBUTE.toLong() + wrapper.attributeQueue + .peek() + ?.type + ?.toLong(), + KitFrameworkWrapper.AttributeChange.INCREMENT_ATTRIBUTE.toLong(), ) } @Test @Throws(Exception::class) fun testQueueEvent() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Assert.assertNull(wrapper.eventQueue) wrapper.kitsLoaded = false val event = Mockito.mock(MPEvent::class.java) @@ -332,16 +372,17 @@ class KitFrameworkWrapperTest { @Test @Throws(Exception::class) fun testSetUserAttribute() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Assert.assertNull(wrapper.attributeQueue) wrapper.kitsLoaded = false wrapper.setUserAttribute("a key", "a value", 1) @@ -351,30 +392,33 @@ class KitFrameworkWrapperTest { wrapper.setUserAttribute("a key", "a value", 1) val mockKitManager = Mockito.mock(KitManager::class.java) wrapper.setKitManager(mockKitManager) - Mockito.verify( - mockKitManager, - Mockito.times(0) - ).setUserAttribute(Mockito.anyString(), Mockito.anyString(), Mockito.anyLong()) + Mockito + .verify( + mockKitManager, + Mockito.times(0), + ).setUserAttribute(Mockito.anyString(), Mockito.anyString(), Mockito.anyLong()) wrapper.setUserAttribute("a key", "a value", 1) - Mockito.verify( - mockKitManager, - Mockito.times(1) - ).setUserAttribute(Mockito.eq("a key"), Mockito.eq("a value"), Mockito.eq(1L)) + Mockito + .verify( + mockKitManager, + Mockito.times(1), + ).setUserAttribute(Mockito.eq("a key"), Mockito.eq("a value"), Mockito.eq(1L)) } @Test @Throws(Exception::class) fun testLogEvent() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Assert.assertNull(wrapper.eventQueue) wrapper.kitsLoaded = false val event = Mockito.mock(MPEvent::class.java) @@ -388,31 +432,34 @@ class KitFrameworkWrapperTest { wrapper.logEvent(event) val mockKitManager = Mockito.mock(KitManager::class.java) wrapper.setKitManager(mockKitManager) - Mockito.verify( - mockKitManager, - Mockito.times(0) - ).logEvent(Mockito.any(MPEvent::class.java)) + Mockito + .verify( + mockKitManager, + Mockito.times(0), + ).logEvent(Mockito.any(MPEvent::class.java)) wrapper.logEvent(event) - Mockito.verify( - mockKitManager, - Mockito.times(1) - ).logEvent(Mockito.any(MPEvent::class.java)) + Mockito + .verify( + mockKitManager, + Mockito.times(1), + ).logEvent(Mockito.any(MPEvent::class.java)) } @Test @PrepareForTest(CommerceEvent::class) @Throws(Exception::class) fun testLogCommerceEvent() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Assert.assertNull(wrapper.eventQueue) wrapper.kitsLoaded = false val event = Mockito.mock(CommerceEvent::class.java) @@ -426,30 +473,33 @@ class KitFrameworkWrapperTest { wrapper.logEvent(event) val mockKitManager = Mockito.mock(KitManager::class.java) wrapper.setKitManager(mockKitManager) - Mockito.verify( - mockKitManager, - Mockito.times(0) - ).logEvent(Mockito.any(CommerceEvent::class.java)) + Mockito + .verify( + mockKitManager, + Mockito.times(0), + ).logEvent(Mockito.any(CommerceEvent::class.java)) wrapper.logEvent(event) - Mockito.verify( - mockKitManager, - Mockito.times(1) - ).logEvent(Mockito.any(CommerceEvent::class.java)) + Mockito + .verify( + mockKitManager, + Mockito.times(1), + ).logEvent(Mockito.any(CommerceEvent::class.java)) } @Test @PrepareForTest(CommerceEvent::class) fun testLogBaseEvent() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Assert.assertNull(wrapper.eventQueue) wrapper.kitsLoaded = false val event = Mockito.mock(BaseEvent::class.java) @@ -463,30 +513,33 @@ class KitFrameworkWrapperTest { wrapper.logEvent(event) val mockKitManager = Mockito.mock(KitManager::class.java) wrapper.setKitManager(mockKitManager) - Mockito.verify( - mockKitManager, - Mockito.times(0) - ).logEvent(Mockito.any(BaseEvent::class.java)) + Mockito + .verify( + mockKitManager, + Mockito.times(0), + ).logEvent(Mockito.any(BaseEvent::class.java)) wrapper.logEvent(event) - Mockito.verify( - mockKitManager, - Mockito.times(1) - ).logEvent(Mockito.any(BaseEvent::class.java)) + Mockito + .verify( + mockKitManager, + Mockito.times(1), + ).logEvent(Mockito.any(BaseEvent::class.java)) } @Test @Throws(Exception::class) fun testLogScreen() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Assert.assertNull(wrapper.eventQueue) wrapper.kitsLoaded = false val event = Mockito.mock(MPEvent::class.java) @@ -501,38 +554,42 @@ class KitFrameworkWrapperTest { wrapper.logScreen(event) val mockKitManager = Mockito.mock(KitManager::class.java) wrapper.setKitManager(mockKitManager) - Mockito.verify( - mockKitManager, - Mockito.times(0) - ).logScreen(Mockito.any(MPEvent::class.java)) + Mockito + .verify( + mockKitManager, + Mockito.times(0), + ).logScreen(Mockito.any(MPEvent::class.java)) wrapper.logScreen(event) - Mockito.verify( - mockKitManager, - Mockito.times(1) - ).logScreen(Mockito.any(MPEvent::class.java)) + Mockito + .verify( + mockKitManager, + Mockito.times(1), + ).logScreen(Mockito.any(MPEvent::class.java)) } @Test @Throws(Exception::class) fun testIsKitActive() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Assert.assertFalse(wrapper.isKitActive(0)) val mockKitManager = Mockito.mock(KitManager::class.java) wrapper.setKitManager(mockKitManager) Assert.assertFalse(wrapper.isKitActive(0)) - Mockito.verify( - mockKitManager, - Mockito.times(1) - ).isKitActive(Mockito.anyInt()) + Mockito + .verify( + mockKitManager, + Mockito.times(1), + ).isKitActive(Mockito.anyInt()) Mockito.`when`(mockKitManager.isKitActive(Mockito.anyInt())).thenReturn(true) Assert.assertTrue(wrapper.isKitActive(0)) } @@ -540,16 +597,17 @@ class KitFrameworkWrapperTest { @Test @Throws(Exception::class) fun testGetSupportedKits() { - val wrapper = KitFrameworkWrapper( - Mockito.mock( - Context::class.java - ), - Mockito.mock(ReportingManager::class.java), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - true, - Mockito.mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + Mockito.mock( + Context::class.java, + ), + Mockito.mock(ReportingManager::class.java), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + true, + Mockito.mock(MParticleOptions::class.java), + ) Assert.assertNull(wrapper.supportedKits) val mockKitManager = Mockito.mock(KitManager::class.java) wrapper.setKitManager(mockKitManager) @@ -563,19 +621,22 @@ class KitFrameworkWrapperTest { fun testCoreCallbacksImpl() { val randomUtils = RandomUtils() val ran = Random() - val mockConfigManager = Mockito.mock( - ConfigManager::class.java - ) - val mockAppStateManager = Mockito.mock( - AppStateManager::class.java - ) - val mockActivity = Mockito.mock( - Activity::class.java - ) + val mockConfigManager = + Mockito.mock( + ConfigManager::class.java, + ) + val mockAppStateManager = + Mockito.mock( + AppStateManager::class.java, + ) + val mockActivity = + Mockito.mock( + Activity::class.java, + ) val mockKitConfiguration = JSONArray() for (i in 0 until randomUtils.randomInt(1, 10)) { mockKitConfiguration.put( - randomUtils.getAlphaNumericString(randomUtils.randomInt(1, 30)) + randomUtils.getAlphaNumericString(randomUtils.randomInt(1, 30)), ) } val mockLaunchUri = Mockito.mock(Uri::class.java) @@ -596,17 +657,20 @@ class KitFrameworkWrapperTest { Mockito.`when`(mockConfigManager.userBucket).thenReturn(mockUserBucket) Mockito.`when`(mockConfigManager.isEnabled).thenReturn(isEnabled) Mockito.`when`(mockConfigManager.isPushEnabled).thenReturn(isPushEnabled) - Mockito.`when`(mockConfigManager.getIntegrationAttributes(1)) + Mockito + .`when`(mockConfigManager.getIntegrationAttributes(1)) .thenReturn(mockIntegrationAttributes1) - Mockito.`when`(mockConfigManager.getIntegrationAttributes(2)) + Mockito + .`when`(mockConfigManager.getIntegrationAttributes(2)) .thenReturn(mockIntegrationAttributes2) - val coreCallbacks: CoreCallbacks = KitFrameworkWrapper.CoreCallbacksImpl( - Mockito.mock( - KitFrameworkWrapper::class.java - ), - mockConfigManager, - mockAppStateManager - ) + val coreCallbacks: CoreCallbacks = + KitFrameworkWrapper.CoreCallbacksImpl( + Mockito.mock( + KitFrameworkWrapper::class.java, + ), + mockConfigManager, + mockAppStateManager, + ) Assert.assertEquals(mockActivity, coreCallbacks.getCurrentActivity()?.get()) Assert.assertEquals(mockKitConfiguration, coreCallbacks.getLatestKitConfiguration()) Assert.assertEquals(mockLaunchUri, coreCallbacks.getLaunchUri()) @@ -622,16 +686,17 @@ class KitFrameworkWrapperTest { @Test fun testSetWrapperSdkVersion_noCalls() { - val wrapper = KitFrameworkWrapper( - mock( - Context::class.java - ), - mock(ReportingManager::class.java), - mock(ConfigManager::class.java), - mock(AppStateManager::class.java), - true, - mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + mock( + Context::class.java, + ), + mock(ReportingManager::class.java), + mock(ConfigManager::class.java), + mock(AppStateManager::class.java), + true, + mock(MParticleOptions::class.java), + ) val mockKitManager = mock(KitManager::class.java) wrapper.setKitManager(mockKitManager) @@ -641,16 +706,17 @@ class KitFrameworkWrapperTest { @Test fun testSetWrapperSdkVersion_kitManagerSet_setWrapperVersionCalled() { - val wrapper = KitFrameworkWrapper( - mock( - Context::class.java - ), - mock(ReportingManager::class.java), - mock(ConfigManager::class.java), - mock(AppStateManager::class.java), - true, - mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + mock( + Context::class.java, + ), + mock(ReportingManager::class.java), + mock(ConfigManager::class.java), + mock(AppStateManager::class.java), + true, + mock(MParticleOptions::class.java), + ) val mockKitManager = mock(KitManager::class.java) wrapper.setKitManager(mockKitManager) @@ -663,16 +729,17 @@ class KitFrameworkWrapperTest { @Test fun testEvents_kitManagerNull_returnsEmptyFlow() { - val wrapper = KitFrameworkWrapper( - mock( - Context::class.java - ), - mock(ReportingManager::class.java), - mock(ConfigManager::class.java), - mock(AppStateManager::class.java), - true, - mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + mock( + Context::class.java, + ), + mock(ReportingManager::class.java), + mock(ConfigManager::class.java), + mock(AppStateManager::class.java), + true, + mock(MParticleOptions::class.java), + ) val result = wrapper.events("test-identifier") @@ -684,16 +751,17 @@ class KitFrameworkWrapperTest { @Test fun testEvents_kitManagerSet_delegatesToKitManager() { - val wrapper = KitFrameworkWrapper( - mock( - Context::class.java - ), - mock(ReportingManager::class.java), - mock(ConfigManager::class.java), - mock(AppStateManager::class.java), - true, - mock(MParticleOptions::class.java) - ) + val wrapper = + KitFrameworkWrapper( + mock( + Context::class.java, + ), + mock(ReportingManager::class.java), + mock(ConfigManager::class.java), + mock(AppStateManager::class.java), + true, + mock(MParticleOptions::class.java), + ) val mockKitManager = mock(KitManager::class.java) val expectedFlow: Flow = flowOf() diff --git a/android-core/src/test/kotlin/com/mparticle/internal/LoggerTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/LoggerTest.kt index 9c56d0063..1f4e994a3 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/LoggerTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/LoggerTest.kt @@ -50,7 +50,7 @@ class LoggerTest { null, null, null, - null + null, ) Assert.assertNotNull(Logger.getLogHandler()) Assert.assertTrue(Logger.getLogHandler() is DefaultLogHandler) @@ -74,7 +74,10 @@ class LoggerTest { Assert.assertTrue(Logger.getLogHandler() is DefaultLogHandler) } - private fun assertTrueUpTo(limit: Int, called: BooleanArray) { + private fun assertTrueUpTo( + limit: Int, + called: BooleanArray, + ) { for (i in called.indices) { if (i < limit) { Assert.assertTrue(called[i]) @@ -84,28 +87,46 @@ class LoggerTest { } } - internal inner class LogHandlerTest(private val called: BooleanArray) : AbstractLogHandler() { - override fun isADBLoggable(tag: String, logLevel: Int): Boolean { - return true - } + internal inner class LogHandlerTest( + private val called: BooleanArray, + ) : AbstractLogHandler() { + override fun isADBLoggable( + tag: String, + logLevel: Int, + ): Boolean = true - override fun verbose(error: Throwable?, message: String) { + override fun verbose( + error: Throwable?, + message: String, + ) { called[0] = true } - override fun info(error: Throwable?, message: String) { + override fun info( + error: Throwable?, + message: String, + ) { called[1] = true } - override fun debug(error: Throwable?, message: String) { + override fun debug( + error: Throwable?, + message: String, + ) { called[2] = true } - override fun warning(error: Throwable?, message: String) { + override fun warning( + error: Throwable?, + message: String, + ) { called[3] = true } - override fun error(error: Throwable?, message: String) { + override fun error( + error: Throwable?, + message: String, + ) { called[4] = true } } diff --git a/android-core/src/test/kotlin/com/mparticle/internal/MPUtilityTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/MPUtilityTest.kt index b96144c70..50a0b7e23 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/MPUtilityTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/MPUtilityTest.kt @@ -22,7 +22,6 @@ import java.util.Collections import java.util.UUID class MPUtilityTest { - @Mock private lateinit var mockContext: Context @@ -62,11 +61,11 @@ class MPUtilityTest { UUID.fromString(MPUtility.getBuildUUID(null)) Assert.assertTrue( "UUIDs should have been the same", - MPUtility.getBuildUUID("12345678") == MPUtility.getBuildUUID("12345678") + MPUtility.getBuildUUID("12345678") == MPUtility.getBuildUUID("12345678"), ) Assert.assertFalse( "UUIDs should have been different", - MPUtility.getBuildUUID("1234567") == MPUtility.getBuildUUID("12345678") + MPUtility.getBuildUUID("1234567") == MPUtility.getBuildUUID("12345678"), ) } @@ -105,12 +104,14 @@ class MPUtilityTest { @Test @Throws(Exception::class) fun testIsAppDebuggableTrue() { - val context = Mockito.mock( - Context::class.java - ) - val applicationInfo = Mockito.mock( - ApplicationInfo::class.java - ) + val context = + Mockito.mock( + Context::class.java, + ) + val applicationInfo = + Mockito.mock( + ApplicationInfo::class.java, + ) applicationInfo.flags = ApplicationInfo.FLAG_DEBUGGABLE Mockito.`when`(context.applicationInfo).thenReturn(applicationInfo) Assert.assertTrue(MPUtility.isAppDebuggable(context)) @@ -119,12 +120,14 @@ class MPUtilityTest { @Test @Throws(Exception::class) fun testIsAppDebuggableFalse() { - val context = Mockito.mock( - Context::class.java - ) - val applicationInfo = Mockito.mock( - ApplicationInfo::class.java - ) + val context = + Mockito.mock( + Context::class.java, + ) + val applicationInfo = + Mockito.mock( + ApplicationInfo::class.java, + ) applicationInfo.flags = 0 Mockito.`when`(context.applicationInfo).thenReturn(applicationInfo) Assert.assertFalse(MPUtility.isAppDebuggable(context)) @@ -133,9 +136,10 @@ class MPUtilityTest { @Test @Throws(Exception::class) fun testIsAppDebuggableDoesNotModify() { - val context = Mockito.mock( - Context::class.java - ) + val context = + Mockito.mock( + Context::class.java, + ) val applicationInfo = ApplicationInfo() applicationInfo.flags = 5 Mockito.`when`(context.applicationInfo).thenReturn(applicationInfo) @@ -146,12 +150,14 @@ class MPUtilityTest { @Test @Throws(Exception::class) fun testGetNetworkType() { - val context = Mockito.mock( - Context::class.java - ) - val telephonyManager = Mockito.mock( - TelephonyManager::class.java - ) + val context = + Mockito.mock( + Context::class.java, + ) + val telephonyManager = + Mockito.mock( + TelephonyManager::class.java, + ) var result = MPUtility.getNetworkType(context, telephonyManager) Assert.assertEquals(0, result) result = MPUtility.getNetworkType(context, null) @@ -200,7 +206,10 @@ class MPUtilityTest { } } - private fun assertUnorderedJsonEqual(object1: JSONObject, object2: JSONObject) { + private fun assertUnorderedJsonEqual( + object1: JSONObject, + object2: JSONObject, + ) { if (object1 === object2) { return } @@ -225,7 +234,10 @@ class MPUtilityTest { } } - private fun assertUnorderedJsonEqual(object1: JSONArray, object2: JSONArray) { + private fun assertUnorderedJsonEqual( + object1: JSONArray, + object2: JSONArray, + ) { if (object1 === object2) { return } @@ -262,11 +274,11 @@ class MPUtilityTest { // too big for a Long, should return a String Assert.assertEquals( 3.245987293478593E47, - MPUtility.toNumberOrString("324598729347859283749857293487598237459872398475") + MPUtility.toNumberOrString("324598729347859283749857293487598237459872398475"), ) Assert.assertEquals( 3.245987293478593E46, - MPUtility.toNumberOrString("32459872934785928374985729348759823745987239847.5") + MPUtility.toNumberOrString("32459872934785928374985729348759823745987239847.5"), ) Assert.assertEquals("asdvasd", MPUtility.toNumberOrString("asdvasd")) Assert.assertEquals("234sdvsda", MPUtility.toNumberOrString("234sdvsda")) @@ -275,15 +287,18 @@ class MPUtilityTest { @Test fun testGetOrientation() { - val mockResources = Mockito.mock( - Resources::class.java - ) - val context = Mockito.mock( - Context::class.java - ) - val displayMetrics = Mockito.mock( - DisplayMetrics::class.java - ) + val mockResources = + Mockito.mock( + Resources::class.java, + ) + val context = + Mockito.mock( + Context::class.java, + ) + val displayMetrics = + Mockito.mock( + DisplayMetrics::class.java, + ) `when`(context.getResources()).thenReturn(mockResources) `when`(mockResources.getDisplayMetrics()).thenReturn(displayMetrics) displayMetrics.widthPixels = 1080 @@ -294,15 +309,18 @@ class MPUtilityTest { @Test fun testGetOrientation_When_ORIENTATION_LANDSCAPE() { - val mockResources = Mockito.mock( - Resources::class.java - ) - val context = Mockito.mock( - Context::class.java - ) - val displayMetrics = Mockito.mock( - DisplayMetrics::class.java - ) + val mockResources = + Mockito.mock( + Resources::class.java, + ) + val context = + Mockito.mock( + Context::class.java, + ) + val displayMetrics = + Mockito.mock( + DisplayMetrics::class.java, + ) `when`(context.getResources()).thenReturn(mockResources) `when`(mockResources.getDisplayMetrics()).thenReturn(displayMetrics) displayMetrics.widthPixels = 1953 @@ -313,15 +331,18 @@ class MPUtilityTest { @Test fun testGetOrientation_When_ORIENTATION_SQUARE() { - val mockResources = Mockito.mock( - Resources::class.java - ) - val context = Mockito.mock( - Context::class.java - ) - val displayMetrics = Mockito.mock( - DisplayMetrics::class.java - ) + val mockResources = + Mockito.mock( + Resources::class.java, + ) + val context = + Mockito.mock( + Context::class.java, + ) + val displayMetrics = + Mockito.mock( + DisplayMetrics::class.java, + ) `when`(context.getResources()).thenReturn(mockResources) `when`(mockResources.getDisplayMetrics()).thenReturn(displayMetrics) displayMetrics.widthPixels = 850 diff --git a/android-core/src/test/kotlin/com/mparticle/internal/MParticleApiClientImplTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/MParticleApiClientImplTest.kt index 8ab2ed303..5fd6f14dc 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/MParticleApiClientImplTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/MParticleApiClientImplTest.kt @@ -34,11 +34,12 @@ class MParticleApiClientImplTest { Mockito.`when`(configManager.apiKey).thenReturn("some api key") Mockito.`when`(configManager.apiSecret).thenReturn("some api secret") sharedPrefs = MockSharedPreferences() - client = MParticleApiClientImpl( - configManager, - sharedPrefs, - MockContext() - ) + client = + MParticleApiClientImpl( + configManager, + sharedPrefs, + MockContext(), + ) client.mDeviceRampNumber = 50 val mockUrl = PowerMockito.mock(MPUrl::class.java) mockConnection = PowerMockito.mock(MPConnection::class.java) @@ -52,21 +53,25 @@ class MParticleApiClientImplTest { @Test @PrepareForTest(URL::class, MParticleApiClientImpl::class, MPUtility::class) @Throws( - Exception::class + Exception::class, ) fun testAddMessageSignature() { setup() PowerMockito.mockStatic(MPUtility::class.java) - Mockito.`when`(MPUtility.hmacSha256Encode(Mockito.anyString(), Mockito.anyString())) + Mockito + .`when`(MPUtility.hmacSha256Encode(Mockito.anyString(), Mockito.anyString())) .thenReturn("encoded") - val headerCapture = ArgumentCaptor.forClass( - String::class.java - ) - val headerValueCapture = ArgumentCaptor.forClass( - String::class.java - ) + val headerCapture = + ArgumentCaptor.forClass( + String::class.java, + ) + val headerValueCapture = + ArgumentCaptor.forClass( + String::class.java, + ) client.addMessageSignature(mockConnection, "this is a sample batch") - Mockito.verify(mockConnection, Mockito.times(2)) + Mockito + .verify(mockConnection, Mockito.times(2)) .setRequestProperty(headerCapture.capture(), headerValueCapture.capture()) val headerKeys = headerCapture.allValues val headerValues = headerValueCapture.allValues @@ -88,40 +93,46 @@ class MParticleApiClientImplTest { val context = MockContext() val sharedPreferences: SharedPreferences = MockSharedPreferences() context.setSharedPreferences(sharedPreferences) - val test = MPUtility.hashFnv1A(MPUtility.getRampUdid(context).toByteArray()) - .mod(BigInteger.valueOf(100)) - .toInt() + val test = + MPUtility + .hashFnv1A(MPUtility.getRampUdid(context).toByteArray()) + .mod(BigInteger.valueOf(100)) + .toInt() Assert.assertTrue("Ramp should be between 0 and 100: $test", test in 0..99) - val test2 = MPUtility.hashFnv1A(MPUtility.getRampUdid(context).toByteArray()) - .mod(BigInteger.valueOf(100)) - .toInt() + val test2 = + MPUtility + .hashFnv1A(MPUtility.getRampUdid(context).toByteArray()) + .mod(BigInteger.valueOf(100)) + .toInt() Assert.assertTrue(test == test2) } @Test @PrepareForTest(URL::class, MParticleApiClientImpl::class, MPUtility::class) @Throws( - Exception::class + Exception::class, ) fun testFetchConfigSuccess() { setup() PowerMockito.mockStatic(MPUtility::class.java) - Mockito.`when`(MPUtility.hmacSha256Encode(Mockito.anyString(), Mockito.anyString())) + Mockito + .`when`(MPUtility.hmacSha256Encode(Mockito.anyString(), Mockito.anyString())) .thenReturn("encoded") Mockito.`when`(mockConnection.responseCode).thenReturn(200) val response = JSONObject() response.put("test", "value") Mockito.`when`(MPUtility.getJsonResponse(mockConnection)).thenReturn(response) - val captor = ArgumentCaptor.forClass( - JSONObject::class.java - ) + val captor = + ArgumentCaptor.forClass( + JSONObject::class.java, + ) client.fetchConfig() Mockito.verify(configManager)?.updateConfig( captor.capture(), Mockito.nullable( - String::class.java + String::class.java, ), - Mockito.nullable(String::class.java) + Mockito.nullable(String::class.java), ) Assert.assertEquals(response, captor.value) } @@ -129,12 +140,13 @@ class MParticleApiClientImplTest { @Test @PrepareForTest(URL::class, MParticleApiClientImpl::class, MPUtility::class) @Throws( - Exception::class + Exception::class, ) fun testFetchConfigFailure() { setup() PowerMockito.mockStatic(MPUtility::class.java) - Mockito.`when`(MPUtility.hmacSha256Encode(Mockito.anyString(), Mockito.anyString())) + Mockito + .`when`(MPUtility.hmacSha256Encode(Mockito.anyString(), Mockito.anyString())) .thenReturn("encoded") Mockito.`when`(mockConnection.responseCode).thenReturn(400) var e: Exception? = null @@ -149,12 +161,13 @@ class MParticleApiClientImplTest { @Test @PrepareForTest(URL::class, MParticleApiClientImpl::class, MPUtility::class) @Throws( - Exception::class + Exception::class, ) fun testConfigDelay() { setup() PowerMockito.mockStatic(MPUtility::class.java) - Mockito.`when`(MPUtility.hmacSha256Encode(Mockito.anyString(), Mockito.anyString())) + Mockito + .`when`(MPUtility.hmacSha256Encode(Mockito.anyString(), Mockito.anyString())) .thenReturn("encoded") Mockito.`when`(mockConnection.responseCode).thenReturn(400) var e: Exception? = null @@ -183,7 +196,7 @@ class MParticleApiClientImplTest { @Test @PrepareForTest(URL::class, MParticleApiClientImpl::class, MPUtility::class) @Throws( - Exception::class + Exception::class, ) fun testCheckThrottleTime() { setup() @@ -203,12 +216,13 @@ class MParticleApiClientImplTest { @Test @PrepareForTest(URL::class, MParticleApiClientImpl::class, MPUtility::class) @Throws( - Exception::class + Exception::class, ) fun testMessageBatchWhileThrottled() { setup() PowerMockito.mockStatic(MPUtility::class.java) - Mockito.`when`(MPUtility.hmacSha256Encode(Mockito.anyString(), Mockito.anyString())) + Mockito + .`when`(MPUtility.hmacSha256Encode(Mockito.anyString(), Mockito.anyString())) .thenReturn("encoded") try { client.sendMessageBatch("", configManager.uploadSettings) @@ -219,7 +233,7 @@ class MParticleApiClientImplTest { } client.requestHandler.setNextRequestTime( MParticleBaseClientImpl.Endpoint.EVENTS, - System.currentTimeMillis() + 1000 + System.currentTimeMillis() + 1000, ) var e: Exception? = null try { @@ -233,7 +247,7 @@ class MParticleApiClientImplTest { @Test @PrepareForTest(URL::class, MParticleApiClientImpl::class, MPUtility::class) @Throws( - Exception::class + Exception::class, ) fun testConfigRequestWhileThrottled() { setup() @@ -246,16 +260,17 @@ class MParticleApiClientImplTest { val response = JSONObject() response.put("test", "value") Mockito.`when`(MPUtility.getJsonResponse(mockConnection)).thenReturn(response) - val captor = ArgumentCaptor.forClass( - JSONObject::class.java - ) + val captor = + ArgumentCaptor.forClass( + JSONObject::class.java, + ) client.fetchConfig() Mockito.verify(configManager)?.updateConfig( captor.capture(), Mockito.nullable( - String::class.java + String::class.java, ), - Mockito.nullable(String::class.java) + Mockito.nullable(String::class.java), ) Assert.assertEquals(response, captor.value) } @@ -263,12 +278,13 @@ class MParticleApiClientImplTest { @Test @PrepareForTest(URL::class, MParticleApiClientImpl::class, MPUtility::class) @Throws( - Exception::class + Exception::class, ) fun testAliasRequestWhileThrottled() { setup() PowerMockito.mockStatic(MPUtility::class.java) - Mockito.`when`(MPUtility.hmacSha256Encode(Mockito.anyString(), Mockito.anyString())) + Mockito + .`when`(MPUtility.hmacSha256Encode(Mockito.anyString(), Mockito.anyString())) .thenReturn("encoded") try { client.sendAliasRequest("", configManager.uploadSettings) @@ -279,7 +295,7 @@ class MParticleApiClientImplTest { } client.requestHandler.setNextRequestTime( MParticleBaseClientImpl.Endpoint.ALIAS, - System.currentTimeMillis() + 1000 + System.currentTimeMillis() + 1000, ) var e: Exception? = null try { @@ -298,12 +314,13 @@ class MParticleApiClientImplTest { @Test @PrepareForTest(URL::class, MParticleApiClientImpl::class, MPUtility::class) @Throws( - Exception::class + Exception::class, ) fun testAliasEventsOnSeparateThrottles() { setup() PowerMockito.mockStatic(MPUtility::class.java) - Mockito.`when`(MPUtility.hmacSha256Encode(Mockito.anyString(), Mockito.anyString())) + Mockito + .`when`(MPUtility.hmacSha256Encode(Mockito.anyString(), Mockito.anyString())) .thenReturn("encoded") try { client.sendMessageBatch("", configManager.uploadSettings) @@ -317,11 +334,11 @@ class MParticleApiClientImplTest { // make sure Events still works when Alias is throttled client.requestHandler.setNextRequestTime( MParticleBaseClientImpl.Endpoint.ALIAS, - System.currentTimeMillis() + 1000 + System.currentTimeMillis() + 1000, ) client.requestHandler.setNextRequestTime( MParticleBaseClientImpl.Endpoint.EVENTS, - System.currentTimeMillis() - 1000 + System.currentTimeMillis() - 1000, ) var ex: MPThrottleException? = null try { @@ -341,11 +358,11 @@ class MParticleApiClientImplTest { // make sure Alias still works when Events is throttled client.requestHandler.setNextRequestTime( MParticleBaseClientImpl.Endpoint.ALIAS, - System.currentTimeMillis() - 1000 + System.currentTimeMillis() - 1000, ) client.requestHandler.setNextRequestTime( MParticleBaseClientImpl.Endpoint.EVENTS, - System.currentTimeMillis() + 1000 + System.currentTimeMillis() + 1000, ) ex = null try { @@ -366,7 +383,7 @@ class MParticleApiClientImplTest { @LargeTest @PrepareForTest(URL::class, MParticleApiClientImpl::class) @Throws( - Exception::class + Exception::class, ) fun testSetNextAllowedRequestTime() { setup() @@ -375,26 +392,42 @@ class MParticleApiClientImplTest { // need a delta to account for test timing variation val delta: Long = 50 client.requestHandler.setNextAllowedRequestTime(null, endpoint) - Assert.assertTrue(client.getNextRequestTime(endpoint) <= MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS + System.currentTimeMillis()) - Assert.assertTrue(client.getNextRequestTime(endpoint) > System.currentTimeMillis() + MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS - delta) + Assert.assertTrue( + client.getNextRequestTime(endpoint) <= MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS + System.currentTimeMillis(), + ) + Assert.assertTrue( + client.getNextRequestTime(endpoint) > System.currentTimeMillis() + MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS - delta, + ) Mockito.`when`(mockConnection.getHeaderField(Mockito.anyString())).thenReturn(null) client.requestHandler.setNextRequestTime(endpoint, 0) Assert.assertEquals(0, client.getNextRequestTime(endpoint)) client.requestHandler.setNextAllowedRequestTime(mockConnection, endpoint) - Assert.assertTrue(client.getNextRequestTime(endpoint) <= MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS + System.currentTimeMillis()) - Assert.assertTrue(client.getNextRequestTime(endpoint) > MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS + System.currentTimeMillis() - delta) + Assert.assertTrue( + client.getNextRequestTime(endpoint) <= MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS + System.currentTimeMillis(), + ) + Assert.assertTrue( + client.getNextRequestTime(endpoint) > MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS + System.currentTimeMillis() - delta, + ) Mockito.`when`(mockConnection.getHeaderField("Retry-After")).thenReturn("") client.requestHandler.setNextRequestTime(endpoint, 0) Assert.assertEquals(0, client.getNextRequestTime(endpoint)) client.requestHandler.setNextAllowedRequestTime(mockConnection, endpoint) - Assert.assertTrue(client.getNextRequestTime(endpoint) <= MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS + System.currentTimeMillis()) - Assert.assertTrue(client.getNextRequestTime(endpoint) > MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS + System.currentTimeMillis() - delta) + Assert.assertTrue( + client.getNextRequestTime(endpoint) <= MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS + System.currentTimeMillis(), + ) + Assert.assertTrue( + client.getNextRequestTime(endpoint) > MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS + System.currentTimeMillis() - delta, + ) Mockito.`when`(mockConnection.getHeaderField("Retry-After")).thenReturn("-1000") client.requestHandler.setNextRequestTime(endpoint, 0) Assert.assertEquals(0, client.getNextRequestTime(endpoint)) client.requestHandler.setNextAllowedRequestTime(mockConnection, endpoint) - Assert.assertTrue(client.getNextRequestTime(endpoint) <= MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS + System.currentTimeMillis()) - Assert.assertTrue(client.getNextRequestTime(endpoint) > MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS + System.currentTimeMillis() - delta) + Assert.assertTrue( + client.getNextRequestTime(endpoint) <= MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS + System.currentTimeMillis(), + ) + Assert.assertTrue( + client.getNextRequestTime(endpoint) > MParticleApiClientImpl.DEFAULT_THROTTLE_MILLIS + System.currentTimeMillis() - delta, + ) Mockito.`when`(mockConnection.getHeaderField("Retry-After")).thenReturn("60") client.requestHandler.setNextRequestTime(endpoint, 0) Assert.assertEquals(0, client.getNextRequestTime(endpoint)) @@ -409,13 +442,17 @@ class MParticleApiClientImplTest { Assert.assertTrue(client.getNextRequestTime(endpoint) <= 100 * 1000 + System.currentTimeMillis()) Assert.assertTrue(client.getNextRequestTime(endpoint) > 100 * 1000 + System.currentTimeMillis() - 10) Mockito.`when`(mockConnection.getHeaderField("Retry-After")).thenReturn( - (60 * 60 * 25).toString() + (60 * 60 * 25).toString(), ) client.requestHandler.setNextRequestTime(endpoint, 0) Assert.assertEquals(0, client.getNextRequestTime(endpoint)) client.requestHandler.setNextAllowedRequestTime(mockConnection, endpoint) - Assert.assertTrue(client.getNextRequestTime(endpoint) <= MParticleApiClientImpl.MAX_THROTTLE_MILLIS + System.currentTimeMillis()) - Assert.assertTrue(client.getNextRequestTime(endpoint) > MParticleApiClientImpl.MAX_THROTTLE_MILLIS + System.currentTimeMillis() - delta) + Assert.assertTrue( + client.getNextRequestTime(endpoint) <= MParticleApiClientImpl.MAX_THROTTLE_MILLIS + System.currentTimeMillis(), + ) + Assert.assertTrue( + client.getNextRequestTime(endpoint) > MParticleApiClientImpl.MAX_THROTTLE_MILLIS + System.currentTimeMillis() - delta, + ) } } } diff --git a/android-core/src/test/kotlin/com/mparticle/internal/MParticleJSInterfaceTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/MParticleJSInterfaceTest.kt index 3b8f76b76..716061712 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/MParticleJSInterfaceTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/MParticleJSInterfaceTest.kt @@ -18,7 +18,6 @@ import org.mockito.Mockito import java.util.TreeMap class MParticleJSInterfaceTest : MParticleJSInterface() { - private lateinit var mProduct1: Product private lateinit var mProduct2: Product private lateinit var jsInterfaceInstance: MParticleJSInterface @@ -62,8 +61,8 @@ class MParticleJSInterfaceTest : MParticleJSInterface() { val mockMp = Mockito.mock(MParticle::class.java) Mockito.`when`(mockMp.Internal()).thenReturn( Mockito.mock( - MParticle.Internal::class.java - ) + MParticle.Internal::class.java, + ), ) Mockito.`when`(mockMp.Internal().configManager).thenReturn(ConfigManager(MockContext())) val mockCurrentUser = Mockito.mock(MParticleUser::class.java) @@ -73,22 +72,27 @@ class MParticleJSInterfaceTest : MParticleJSInterface() { Mockito.`when`(mockMp.environment).thenReturn(MParticle.Environment.Development) MParticle.setInstance(mockMp) jsInterfaceInstance = MParticleJSInterface() - Mockito.`when`(MParticle.getInstance()?.environment) + Mockito + .`when`(MParticle.getInstance()?.environment) .thenReturn(MParticle.Environment.Development) - mProduct1 = Product.Builder("iPhone", "12345", 400.0) - .quantity(1.0) - .build() + mProduct1 = + Product + .Builder("iPhone", "12345", 400.0) + .quantity(1.0) + .build() val customAttributes: MutableMap = TreeMap() customAttributes["customkey"] = "customvalue" - mProduct2 = Product.Builder("Android", "98765", 600.0) - .quantity(4.0) - .couponCode("my-coupon-code-2") - .variant("SuperDuper") - .brand("Samsung") - .position(2) - .category("CellPhones") - .customAttributes(customAttributes) - .build() + mProduct2 = + Product + .Builder("Android", "98765", 600.0) + .quantity(4.0) + .couponCode("my-coupon-code-2") + .variant("SuperDuper") + .brand("Samsung") + .position(2) + .category("CellPhones") + .customAttributes(customAttributes) + .build() } @Test @@ -121,7 +125,11 @@ class MParticleJSInterfaceTest : MParticleJSInterface() { Assert.assertEquals(product.name, mProduct2.name) Assert.assertEquals(product.sku, mProduct2.sku) Assert.assertEquals(product.customAttributes?.size, 1) - val key = product.customAttributes?.keys?.toTypedArray()?.get(0) as String + val key = + product.customAttributes + ?.keys + ?.toTypedArray() + ?.get(0) as String Assert.assertEquals(key, "customkey") Assert.assertEquals(product.customAttributes?.get(key), "customvalue") Assert.assertEquals(product.couponCode, mProduct2.couponCode) @@ -263,16 +271,17 @@ class MParticleJSInterfaceTest : MParticleJSInterface() { identityArray.put( JSONObject() .put(TYPE, entry.key.name) - .put(IDENTITY, entry.value) + .put(IDENTITY, entry.value), ) } - val jsonObject = JSONObject() - .put(USER_IDENTITIES, identityArray) + val jsonObject = + JSONObject() + .put(USER_IDENTITIES, identityArray) login(jsonObject.toString()) Mockito.verify(MParticle.getInstance()?.Identity(), Mockito.times(1))?.login( Mockito.any( - IdentityApiRequest::class.java - ) + IdentityApiRequest::class.java, + ), ) } @@ -285,16 +294,17 @@ class MParticleJSInterfaceTest : MParticleJSInterface() { identityArray.put( JSONObject() .put(TYPE, entry.key.name) - .put(IDENTITY, entry.value) + .put(IDENTITY, entry.value), ) } - val jsonObject = JSONObject() - .put(USER_IDENTITIES, identityArray) + val jsonObject = + JSONObject() + .put(USER_IDENTITIES, identityArray) logout(jsonObject.toString()) Mockito.verify(MParticle.getInstance()?.Identity(), Mockito.times(1))?.logout( Mockito.any( - IdentityApiRequest::class.java - ) + IdentityApiRequest::class.java, + ), ) } @@ -307,16 +317,17 @@ class MParticleJSInterfaceTest : MParticleJSInterface() { identityArray.put( JSONObject() .put(TYPE, entry.key.name) - .put(IDENTITY, entry.value) + .put(IDENTITY, entry.value), ) } - val jsonObject = JSONObject() - .put(USER_IDENTITIES, identityArray) + val jsonObject = + JSONObject() + .put(USER_IDENTITIES, identityArray) modify(jsonObject.toString()) Mockito.verify(MParticle.getInstance()?.Identity(), Mockito.times(1))?.modify( Mockito.any( - IdentityApiRequest::class.java - ) + IdentityApiRequest::class.java, + ), ) } @@ -335,13 +346,16 @@ class MParticleJSInterfaceTest : MParticleJSInterface() { Assert.assertEquals( i.toString() + "", MParticle.EventType.values()[i], - jsInterfaceInstance.convertEventType(i) + jsInterfaceInstance.convertEventType(i), ) } } - fun isEqual(product1: Product, product2: Product?): Boolean { - return try { + fun isEqual( + product1: Product, + product2: Product?, + ): Boolean = + try { val object1 = JSONObject(product1.toString()) val object2 = JSONObject(product2.toString()) object1.remove("act") @@ -350,5 +364,4 @@ class MParticleJSInterfaceTest : MParticleJSInterface() { } catch (ignore: JSONException) { false } - } } diff --git a/android-core/src/test/kotlin/com/mparticle/internal/MessageBatchTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/MessageBatchTest.kt index 0bdd15c1b..9f8b46166 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/MessageBatchTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/MessageBatchTest.kt @@ -18,18 +18,19 @@ class MessageBatchTest { val mockMp = Mockito.mock(MParticle::class.java) Mockito.`when`(mockMp.environment).thenReturn(MParticle.Environment.Development) MParticle.setInstance(mockMp) - val manager = ConfigManager( - MockContext(), - MParticle.Environment.Production, - "some api key", - "some api secret", - null, - null, - null, - null, - null, - null - ) + val manager = + ConfigManager( + MockContext(), + MParticle.Environment.Production, + "some api key", + "some api secret", + null, + null, + null, + null, + null, + null, + ) var sessionHistory = true val batchId = BatchId(manager.mpid, null, null, null) var batch = MessageBatch.create(sessionHistory, manager, JSONObject(), batchId) @@ -67,18 +68,19 @@ class MessageBatchTest { val mockMp = Mockito.mock(MParticle::class.java) Mockito.`when`(mockMp.environment).thenReturn(MParticle.Environment.Development) MParticle.setInstance(mockMp) - val manager = ConfigManager( - MockContext(), - MParticle.Environment.Production, - "some api key", - "some api secret", - null, - null, - null, - null, - null, - null - ) + val manager = + ConfigManager( + MockContext(), + MParticle.Environment.Production, + "some api key", + "some api secret", + null, + null, + null, + null, + null, + null, + ) val sessionHistory = true val batchId = BatchId(manager.mpid, null, null, null) val batch = MessageBatch.create(sessionHistory, manager, JSONObject(), batchId) @@ -87,24 +89,26 @@ class MessageBatchTest { var consent = batch.optJSONObject("con") Assert.assertNotNull(consent) batch.addConsentState( - ConsentState.builder().addGDPRConsentState( - "foo purpose", - GDPRConsent.builder(true) - .timestamp(10L) - .location("foo location") - .hardwareId("foo hardware id") - .document("foo document") - .build() - ) - .setCCPAConsentState( - CCPAConsent.builder(true) + ConsentState + .builder() + .addGDPRConsentState( + "foo purpose", + GDPRConsent + .builder(true) + .timestamp(10L) + .location("foo location") + .hardwareId("foo hardware id") + .document("foo document") + .build(), + ).setCCPAConsentState( + CCPAConsent + .builder(true) .timestamp(20L) .location("bar location") .hardwareId("bar hardware id") .document("bar document") - .build() - ) - .build() + .build(), + ).build(), ) val consentJSON = batch.optJSONObject(Constants.MessageKey.CONSENT_STATE) Assert.assertNotNull(consent) @@ -116,15 +120,15 @@ class MessageBatchTest { Assert.assertEquals(10L, consent?.getLong(Constants.MessageKey.CONSENT_STATE_TIMESTAMP)) Assert.assertEquals( "foo location", - consent?.getString(Constants.MessageKey.CONSENT_STATE_LOCATION) + consent?.getString(Constants.MessageKey.CONSENT_STATE_LOCATION), ) Assert.assertEquals( "foo hardware id", - consent?.getString(Constants.MessageKey.CONSENT_STATE_HARDWARE_ID) + consent?.getString(Constants.MessageKey.CONSENT_STATE_HARDWARE_ID), ) Assert.assertEquals( "foo document", - consent?.getString(Constants.MessageKey.CONSENT_STATE_DOCUMENT) + consent?.getString(Constants.MessageKey.CONSENT_STATE_DOCUMENT), ) consent = consentJSON?.optJSONObject(Constants.MessageKey.CONSENT_STATE_CCPA) Assert.assertNotNull(consent) @@ -134,15 +138,15 @@ class MessageBatchTest { Assert.assertEquals(20L, consent?.getLong(Constants.MessageKey.CONSENT_STATE_TIMESTAMP)) Assert.assertEquals( "bar location", - consent?.getString(Constants.MessageKey.CONSENT_STATE_LOCATION) + consent?.getString(Constants.MessageKey.CONSENT_STATE_LOCATION), ) Assert.assertEquals( "bar hardware id", - consent?.getString(Constants.MessageKey.CONSENT_STATE_HARDWARE_ID) + consent?.getString(Constants.MessageKey.CONSENT_STATE_HARDWARE_ID), ) Assert.assertEquals( "bar document", - consent?.getString(Constants.MessageKey.CONSENT_STATE_DOCUMENT) + consent?.getString(Constants.MessageKey.CONSENT_STATE_DOCUMENT), ) } diff --git a/android-core/src/test/kotlin/com/mparticle/internal/MessageHandlerTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/MessageHandlerTest.kt index b919f6100..7f3720f97 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/MessageHandlerTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/MessageHandlerTest.kt @@ -33,25 +33,28 @@ class MessageHandlerTest { @Throws(Exception::class) fun setUp() { MParticle.setInstance(MockMParticle()) - val stateManager = Mockito.mock( - AppStateManager::class.java - ) + val stateManager = + Mockito.mock( + AppStateManager::class.java, + ) mConfigManager = MParticle.getInstance()?.Internal()?.configManager!! mMessageManager = Mockito.mock(MessageManager::class.java) Mockito.`when`(mMessageManager.apiKey).thenReturn("apiKey") - Mockito.`when`(mMessageManager.uploadSettings).thenReturn(UploadSettings("apiKey", "secret", NetworkOptions.builder().build(), "", "")) + Mockito + .`when`( + mMessageManager.uploadSettings, + ).thenReturn(UploadSettings("apiKey", "secret", NetworkOptions.builder().build(), "", "")) mParticleDatabaseManager = Mockito.mock(MParticleDBManager::class.java) - handler = object : MessageHandler( - mMessageManager, - MockContext(), - mParticleDatabaseManager, - "dataplan1", - 1 - ) { - public override fun databaseAvailable(): Boolean { - return true + handler = + object : MessageHandler( + mMessageManager, + MockContext(), + mParticleDatabaseManager, + "dataplan1", + 1, + ) { + public override fun databaseAvailable(): Boolean = true } - } } @Test @@ -59,22 +62,25 @@ class MessageHandlerTest { fun testInsertAliasRequest() { val insertedAliasRequest = AndroidUtils.Mutable(null) Mockito.`when`(mConfigManager.deviceApplicationStamp).thenReturn("das") - val database: MParticleDBManager = object : MParticleDBManager(MockContext()) { - override fun insertAliasRequest(request: JSONObject, uploadSettings: UploadSettings) { - insertedAliasRequest.value = request - } + val database: MParticleDBManager = + object : MParticleDBManager(MockContext()) { + override fun insertAliasRequest( + request: JSONObject, + uploadSettings: UploadSettings, + ) { + insertedAliasRequest.value = request + } - override fun getDatabase(): MPDatabase? { - return null + override fun getDatabase(): MPDatabase? = null } - } handler.mMParticleDBManager = database TestCase.assertNull(insertedAliasRequest.value) val aliasRequest = TestingUtils.getInstance().randomAliasRequest val aliasMessage = MPAliasMessage(aliasRequest, "das", "apiKey") - val mockMessage = Mockito.mock( - Message::class.java - ) + val mockMessage = + Mockito.mock( + Message::class.java, + ) mockMessage.what = MessageHandler.STORE_ALIAS_MESSAGE mockMessage.obj = aliasMessage handler.handleMessageImpl(mockMessage) diff --git a/android-core/src/test/kotlin/com/mparticle/internal/MessageManagerTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/MessageManagerTest.kt index 82fb801fd..36b798576 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/MessageManagerTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/MessageManagerTest.kt @@ -49,10 +49,17 @@ class MessageManagerTest { context = MockContext() configManager = Mockito.mock(ConfigManager::class.java) Mockito.`when`(configManager.apiKey).thenReturn("123456789") - Mockito.`when`(configManager.userStorage) + Mockito + .`when`(configManager.userStorage) .thenReturn(UserStorage.create(context, Random().nextInt().toLong())) - Mockito.`when`(MParticle.getInstance()?.Internal()?.configManager?.mpid) - .thenReturn(defaultId) + Mockito + .`when`( + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.mpid, + ).thenReturn(defaultId) Mockito.`when`(configManager.mpid).thenReturn(defaultId) // Prepare and mock the Looper class PowerMockito.mockStatic(Looper::class.java) @@ -61,17 +68,18 @@ class MessageManagerTest { appStateManager = AppStateManager(context, true) messageHandler = Mockito.mock(MessageHandler::class.java) uploadHandler = Mockito.mock(UploadHandler::class.java) - manager = MessageManager( - context, - configManager, - MParticle.InstallType.AutoDetect, - appStateManager, - Mockito.mock(MParticleDBManager::class.java), - messageHandler, - uploadHandler - ) + manager = + MessageManager( + context, + configManager, + MParticle.InstallType.AutoDetect, + appStateManager, + Mockito.mock(MParticleDBManager::class.java), + messageHandler, + uploadHandler, + ) Mockito.`when`(messageHandler.obtainMessage(Mockito.anyInt(), Mockito.any())).thenReturn( - Message() + Message(), ) Mockito.`when`(messageHandler.obtainMessage(Mockito.anyInt())).thenReturn(Message()) } @@ -125,7 +133,7 @@ class MessageManagerTest { Assert.assertEquals(memory, newMemory) Assert.assertEquals( memory, - prefs.getLong(Constants.MiscStorageKeys.MEMORY_THRESHOLD, -1234) + prefs.getLong(Constants.MiscStorageKeys.MEMORY_THRESHOLD, -1234), ) } @@ -146,8 +154,8 @@ class MessageManagerTest { var sessionStart = manager.startSession(appStateManager.session) Mockito.verify(messageHandler, Mockito.times(2)).sendMessage( Mockito.any( - Message::class.java - ) + Message::class.java, + ), ) Assert.assertNotNull(sessionStart) Assert.assertEquals(Constants.MessageType.SESSION_START, sessionStart.messageType) @@ -156,13 +164,13 @@ class MessageManagerTest { Assert.assertFalse(sessionStart.has(MessageKey.PREVIOUS_SESSION_START)) Assert.assertEquals( appStateManager.session.mSessionID, - configManager.userStorage.getPreviousSessionId(null) + configManager.userStorage.getPreviousSessionId(null), ) Assert.assertFalse( prefs.getBoolean( Constants.PrefKeys.FIRSTRUN_MESSAGE + configManager.apiKey, - true - ) + true, + ), ) configManager.userStorage.setPreviousSessionForeground(42000) configManager.userStorage.setPreviousSessionStart(24000) @@ -173,7 +181,7 @@ class MessageManagerTest { Assert.assertEquals(42, sessionStart.getLong(MessageKey.PREVIOUS_SESSION_LENGTH)) Assert.assertEquals(24000, sessionStart.getLong(MessageKey.PREVIOUS_SESSION_START)) Mockito.verify(messageHandler, Mockito.times(1)).sendMessage( - messageHandler.obtainMessage(MessageHandler.END_ORPHAN_SESSIONS, configManager.mpid) + messageHandler.obtainMessage(MessageHandler.END_ORPHAN_SESSIONS, configManager.mpid), ) } @@ -201,8 +209,8 @@ class MessageManagerTest { manager.updateSessionEnd(session) Mockito.verify(messageHandler, Mockito.times(1)).sendMessage( Mockito.any( - Message::class.java - ) + Message::class.java, + ), ) val time = configManager.userStorage.getPreviousSessionForegound(-1) Assert.assertEquals(5000, time) @@ -224,23 +232,28 @@ class MessageManagerTest { manager.logEvent(null, null) val info: MutableMap = HashMap(1) info["test key"] = "test value" - val event = MPEvent.Builder("test event name", MParticle.EventType.Location).duration(100.0) - .addCustomFlag("flag 1", "value 1") - .addCustomFlag("flag 1", "value 2").addCustomFlag("flag 2", "value 3") - .customAttributes(info).build() + val event = + MPEvent + .Builder("test event name", MParticle.EventType.Location) + .duration(100.0) + .addCustomFlag("flag 1", "value 1") + .addCustomFlag("flag 1", "value 2") + .addCustomFlag("flag 2", "value 3") + .customAttributes(info) + .build() val message = manager.logEvent(event, "test screen name") Assert.assertNotNull(message) Assert.assertEquals(Constants.MessageType.EVENT, message.messageType) Assert.assertEquals(appStateManager.session.mSessionID, message.sessionId) Assert.assertEquals( message.getLong(MessageKey.EVENT_START_TIME), - appStateManager.session.mLastEventTime + appStateManager.session.mLastEventTime, ) event.length?.let { lenght -> Assert.assertEquals( message.getDouble(MessageKey.EVENT_DURATION), lenght, - 2.0 + 2.0, ) } val attrs = message.getJSONObject(MessageKey.ATTRIBUTES) @@ -251,8 +264,10 @@ class MessageManagerTest { Assert.assertEquals("test screen name", message.getString(MessageKey.CURRENT_ACTIVITY)) Assert.assertEquals( 1, - context.getSharedPreferences("name", 0).getInt(Constants.PrefKeys.EVENT_COUNTER, -1) - .toLong() + context + .getSharedPreferences("name", 0) + .getInt(Constants.PrefKeys.EVENT_COUNTER, -1) + .toLong(), ) for (i in 0..99) { manager.logEvent(event, "test screen name") @@ -267,13 +282,15 @@ class MessageManagerTest { Assert.assertEquals(flag2[0], "value 3") Assert.assertEquals( 101, - context.getSharedPreferences("name", 0).getInt(Constants.PrefKeys.EVENT_COUNTER, -1) - .toLong() + context + .getSharedPreferences("name", 0) + .getInt(Constants.PrefKeys.EVENT_COUNTER, -1) + .toLong(), ) Mockito.verify(messageHandler, Mockito.times(101)).sendMessage( Mockito.any( - Message::class.java - ) + Message::class.java, + ), ) } @@ -281,7 +298,8 @@ class MessageManagerTest { @Throws(Exception::class) fun testLogCommerceEventWithNullUser() { val event = - CommerceEvent.Builder(Product.ADD_TO_CART, Product.Builder("foo", "bar", 10.0).build()) + CommerceEvent + .Builder(Product.ADD_TO_CART, Product.Builder("foo", "bar", 10.0).build()) .build() val message = manager.logEvent(event) Assert.assertNotNull(message) @@ -298,12 +316,17 @@ class MessageManagerTest { appStateManager.session.start(context) val info: MutableMap = HashMap() info["test key"] = "test value" - var message = manager.logScreen( - MPEvent.Builder("screen name").addCustomFlag("flag 1", "value 1") - .addCustomFlag("flag 1", "value 2").addCustomFlag("flag 2", "value 3") - .customAttributes(info).build(), - true - ) + var message = + manager.logScreen( + MPEvent + .Builder("screen name") + .addCustomFlag("flag 1", "value 1") + .addCustomFlag("flag 1", "value 2") + .addCustomFlag("flag 2", "value 3") + .customAttributes(info) + .build(), + true, + ) Assert.assertNotNull(message) Assert.assertEquals(Constants.MessageType.SCREEN_VIEW, message.messageType) Assert.assertEquals(appStateManager.session.mSessionID, message.sessionId) @@ -311,7 +334,7 @@ class MessageManagerTest { Assert.assertEquals(message.getString(MessageKey.SCREEN_STARTED), "activity_started") Assert.assertEquals( message.getLong(MessageKey.EVENT_START_TIME), - appStateManager.session.mLastEventTime + appStateManager.session.mLastEventTime, ) val flags = message.getJSONObject("flags") val flag1 = flags.getJSONArray("flag 1") @@ -325,15 +348,16 @@ class MessageManagerTest { Assert.assertNotNull(attrs) Assert.assertEquals("test value", attrs.getString("test key")) Assert.assertEquals("screen name", message.name) - message = manager.logScreen( - MPEvent.Builder("screen name 2").customAttributes(info).build(), - false - ) + message = + manager.logScreen( + MPEvent.Builder("screen name 2").customAttributes(info).build(), + false, + ) Assert.assertEquals(message.getString(MessageKey.SCREEN_STARTED), "activity_stopped") Mockito.verify(messageHandler, Mockito.times(3)).sendMessage( Mockito.any( - Message::class.java - ) + Message::class.java, + ), ) } @@ -349,17 +373,17 @@ class MessageManagerTest { Assert.assertEquals(appStateManager.session.mSessionID, message.sessionId) Assert.assertEquals( message.getLong(MessageKey.EVENT_START_TIME), - appStateManager.session.mLastEventTime + appStateManager.session.mLastEventTime, ) Assert.assertEquals( message.getInt(MessageKey.BREADCRUMB_SESSION_COUNTER).toLong(), - configManager.userStorage.currentSessionCounter.toLong() + configManager.userStorage.currentSessionCounter.toLong(), ) Assert.assertEquals(message.getString(MessageKey.BREADCRUMB_LABEL), "test crumb") Mockito.verify(messageHandler, Mockito.times(2)).sendMessage( Mockito.any( - Message::class.java - ) + Message::class.java, + ), ) } @@ -375,8 +399,8 @@ class MessageManagerTest { Assert.assertEquals(message.getLong(MessageKey.TIMESTAMP), optOutTime) Mockito.verify(messageHandler, Mockito.times(1)).sendMessage( Mockito.any( - Message::class.java - ) + Message::class.java, + ), ) val message2 = manager.optOut(optOutTime, false) Assert.assertFalse(message2.getBoolean(MessageKey.OPT_OUT_STATUS)) @@ -406,16 +430,16 @@ class MessageManagerTest { t.printStackTrace(PrintWriter(stringWriter)) Assert.assertEquals( message.getString(MessageKey.ERROR_STACK_TRACE), - stringWriter.toString() + stringWriter.toString(), ) Assert.assertEquals( message.getInt(MessageKey.ERROR_SESSION_COUNT).toLong(), - configManager.userStorage.currentSessionCounter.toLong() + configManager.userStorage.currentSessionCounter.toLong(), ) Mockito.verify(messageHandler, Mockito.times(3)).sendMessage( Mockito.any( - Message::class.java - ) + Message::class.java, + ), ) message = manager.logErrorEvent(errorMessage, t, attrs, false) Assert.assertNotNull(message) @@ -428,16 +452,16 @@ class MessageManagerTest { t.printStackTrace(PrintWriter(stringWriter)) Assert.assertEquals( message.getString(MessageKey.ERROR_STACK_TRACE), - stringWriter.toString() + stringWriter.toString(), ) Assert.assertEquals( message.getInt(MessageKey.ERROR_SESSION_COUNT).toLong(), - configManager.userStorage.currentSessionCounter.toLong() + configManager.userStorage.currentSessionCounter.toLong(), ) Mockito.verify(messageHandler, Mockito.times(4)).sendMessage( Mockito.any( - Message::class.java - ) + Message::class.java, + ), ) message = manager.logErrorEvent(errorMessage, t, attrs) Assert.assertNotNull(message) @@ -450,16 +474,16 @@ class MessageManagerTest { t.printStackTrace(PrintWriter(stringWriter)) Assert.assertEquals( message.getString(MessageKey.ERROR_STACK_TRACE), - stringWriter.toString() + stringWriter.toString(), ) Assert.assertEquals( message.getInt(MessageKey.ERROR_SESSION_COUNT).toLong(), - configManager.userStorage.currentSessionCounter.toLong() + configManager.userStorage.currentSessionCounter.toLong(), ) Mockito.verify(messageHandler, Mockito.times(5)).sendMessage( Mockito.any( - Message::class.java - ) + Message::class.java, + ), ) } @@ -469,15 +493,16 @@ class MessageManagerTest { appStateManager.session.start(context) var message = manager.logNetworkPerformanceEvent(0, null, null, 0, 0, 0, null) Assert.assertNull(message) - message = manager.logNetworkPerformanceEvent( - 1, - "GET", - "someurl", - 12, - 123, - 1234, - "request string" - ) + message = + manager.logNetworkPerformanceEvent( + 1, + "GET", + "someurl", + 12, + 123, + 1234, + "request string", + ) Assert.assertNotNull(message) Assert.assertEquals(Constants.MessageType.NETWORK_PERFORMNACE, message.messageType) Assert.assertEquals(message.getString(MessageKey.NPE_METHOD), "GET") @@ -489,8 +514,8 @@ class MessageManagerTest { Assert.assertEquals(message.getLong(MessageKey.TIMESTAMP), 1) Mockito.verify(messageHandler, Mockito.times(1)).sendMessage( Mockito.any( - Message::class.java - ) + Message::class.java, + ), ) } @@ -512,8 +537,8 @@ class MessageManagerTest { Assert.assertEquals(message.getBoolean(MessageKey.PUSH_REGISTER_FLAG), false) Mockito.verify(messageHandler, Mockito.times(2)).sendMessage( Mockito.any( - Message::class.java - ) + Message::class.java, + ), ) } @@ -523,8 +548,8 @@ class MessageManagerTest { manager.setSessionAttributes() Mockito.verify(messageHandler, Mockito.times(1)).sendMessage( Mockito.any( - Message::class.java - ) + Message::class.java, + ), ) } @@ -532,11 +557,12 @@ class MessageManagerTest { @Throws(Exception::class) fun testStartUploadLoop() { manager.startUploadLoop() - Mockito.verify(uploadHandler, Mockito.times(1)) + Mockito + .verify(uploadHandler, Mockito.times(1)) .removeMessages(UploadHandler.UPLOAD_MESSAGES, configManager.mpid) Mockito.verify(uploadHandler, Mockito.times(1)).sendMessageDelayed( uploadHandler.obtainMessage(UploadHandler.UPLOAD_MESSAGES, configManager.mpid), - Constants.INITIAL_UPLOAD_DELAY + Constants.INITIAL_UPLOAD_DELAY, ) } @@ -546,17 +572,18 @@ class MessageManagerTest { manager.doUpload() Mockito.verify(messageHandler, Mockito.times(1)).sendMessage( Mockito.any( - Message::class.java - ) + Message::class.java, + ), ) } @Test @Throws(Exception::class) fun testSetLocation() { - val location = Mockito.mock( - Location::class.java - ) + val location = + Mockito.mock( + Location::class.java, + ) manager.location = location Assert.assertEquals(location, manager.location) } @@ -574,21 +601,22 @@ class MessageManagerTest { val launchUri = "some uri" val launchExtras = "some extras" val launchSourcePackage = "com.some.package" - message = manager.logStateTransition( - Constants.StateTransitionType.STATE_TRANS_INIT, - currentActivity, - launchUri, - launchExtras, - launchSourcePackage, - 42, - 24, - 123 - ) + message = + manager.logStateTransition( + Constants.StateTransitionType.STATE_TRANS_INIT, + currentActivity, + launchUri, + launchExtras, + launchSourcePackage, + 42, + 24, + 123, + ) Assert.assertNotNull(message) Assert.assertEquals(Constants.MessageType.APP_STATE_TRANSITION, message.messageType) Assert.assertEquals( message.getString(MessageKey.STATE_TRANSITION_TYPE), - Constants.StateTransitionType.STATE_TRANS_INIT + Constants.StateTransitionType.STATE_TRANS_INIT, ) Assert.assertEquals(message.sessionId, appStateManager.session.mSessionID) Assert.assertEquals(message.getString(MessageKey.CURRENT_ACTIVITY), currentActivity) @@ -596,7 +624,7 @@ class MessageManagerTest { Assert.assertEquals(message.getString(MessageKey.ST_LAUNCH_PARAMS), launchExtras) Assert.assertEquals( message.getString(MessageKey.ST_LAUNCH_SOURCE_PACKAGE), - launchSourcePackage + launchSourcePackage, ) Assert.assertEquals(message.getLong(MessageKey.ST_LAUNCH_PRV_FORE_TIME), 42) Assert.assertEquals(message.getLong(MessageKey.ST_LAUNCH_TIME_SUSPENDED), 24) @@ -605,23 +633,24 @@ class MessageManagerTest { Assert.assertEquals(message.getBoolean(MessageKey.APP_INIT_FIRST_RUN), true) Mockito.verify(messageHandler, Mockito.times(1))?.sendMessage( Mockito.any( - Message::class.java - ) + Message::class.java, + ), ) } @Test @Throws(Exception::class) fun testLogUserAttributeChange() { - var message = manager.logUserAttributeChangeMessage( - "this is a key", - "this is the new value", - "this is the old value", - false, - false, - 0, - 1 - ) + var message = + manager.logUserAttributeChangeMessage( + "this is a key", + "this is the new value", + "this is the old value", + false, + false, + 0, + 1, + ) Assert.assertEquals("this is a key", message.getString("n")) Assert.assertEquals("this is the new value", message.getString("nv")) Assert.assertEquals("this is the old value", message.getString("ov")) @@ -633,15 +662,16 @@ class MessageManagerTest { val oldValue: MutableList = ArrayList() oldValue.add("this is an old value") oldValue.add("this is another old value") - message = manager.logUserAttributeChangeMessage( - "this is a key", - newValue, - oldValue, - false, - true, - 0, - 1 - ) + message = + manager.logUserAttributeChangeMessage( + "this is a key", + newValue, + oldValue, + false, + true, + 0, + 1, + ) Assert.assertEquals("this is a key", message.getString("n")) Assert.assertEquals(2, message.getJSONArray("nv").length().toLong()) Assert.assertEquals(2, message.getJSONArray("ov").length().toLong()) @@ -654,15 +684,16 @@ class MessageManagerTest { @Test @Throws(Exception::class) fun testLogUserAttributeChangeNewAttribute() { - val message = manager.logUserAttributeChangeMessage( - "this is a key", - "this is the new value", - null, - false, - false, - 0, - 1 - ) + val message = + manager.logUserAttributeChangeMessage( + "this is a key", + "this is the new value", + null, + false, + false, + 0, + 1, + ) Assert.assertEquals("this is a key", message.getString("n")) Assert.assertEquals("this is the new value", message.getString("nv")) Assert.assertEquals(JSONObject.NULL, message["ov"]) @@ -683,15 +714,16 @@ class MessageManagerTest { @Test @Throws(Exception::class) fun testLogUserAttributeChangeTagToAttribute() { - val message = manager.logUserAttributeChangeMessage( - "this is a key", - "this is the new value", - null, - false, - false, - 0, - 1 - ) + val message = + manager.logUserAttributeChangeMessage( + "this is a key", + "this is the new value", + null, + false, + false, + 0, + 1, + ) Assert.assertEquals("this is a key", message.getString("n")) Assert.assertEquals(JSONObject.NULL, message["ov"]) Assert.assertEquals("this is the new value", message["nv"]) @@ -704,15 +736,16 @@ class MessageManagerTest { val newValue: MutableList = ArrayList() newValue.add("this is a new value") newValue.add("this is another new value") - val message = manager.logUserAttributeChangeMessage( - "this is a key", - newValue, - "this is the old value", - false, - false, - 0, - 1 - ) + val message = + manager.logUserAttributeChangeMessage( + "this is a key", + newValue, + "this is the old value", + false, + false, + 0, + 1, + ) Assert.assertEquals("this is a key", message.getString("n")) Assert.assertEquals(2, message.getJSONArray("nv").length().toLong()) Assert.assertEquals("this is a new value", message.getJSONArray("nv")[0]) @@ -734,15 +767,16 @@ class MessageManagerTest { @Test @Throws(Exception::class) fun testLogUserAttributeChangeRemoveAttribute() { - val message = manager.logUserAttributeChangeMessage( - "this is a key", - null, - "this is the old value", - true, - false, - 0, - 1 - ) + val message = + manager.logUserAttributeChangeMessage( + "this is a key", + null, + "this is the old value", + true, + false, + 0, + 1, + ) Assert.assertEquals("this is a key", message.getString("n")) Assert.assertEquals("this is the old value", message["ov"]) Assert.assertEquals(JSONObject.NULL, message["nv"]) diff --git a/android-core/src/test/kotlin/com/mparticle/internal/UploadHandlerTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/UploadHandlerTest.kt index d01c8180e..7e8bcad26 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/UploadHandlerTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/UploadHandlerTest.kt @@ -42,24 +42,26 @@ class UploadHandlerTest { @Throws(Exception::class) fun setUp() { MParticle.setInstance(MockMParticle()) - val stateManager = Mockito.mock( - AppStateManager::class.java - ) - mConfigManager = MParticle.getInstance()?.Internal()?.configManager!! - handler = UploadHandler( - MockContext(), - mConfigManager, - stateManager, - Mockito.mock( - MessageManager::class.java - ), - Mockito.mock( - MParticleDBManager::class.java - ), + val stateManager = Mockito.mock( - KitFrameworkWrapper::class.java + AppStateManager::class.java, + ) + mConfigManager = MParticle.getInstance()?.Internal()?.configManager!! + handler = + UploadHandler( + MockContext(), + mConfigManager, + stateManager, + Mockito.mock( + MessageManager::class.java, + ), + Mockito.mock( + MParticleDBManager::class.java, + ), + Mockito.mock( + KitFrameworkWrapper::class.java, + ), ) - ) } @Test @@ -117,9 +119,10 @@ class UploadHandlerTest { @Throws(Exception::class) fun testRampSampling() { handler.handleMessage(Message()) - val apiClient = Mockito.mock( - MParticleApiClientImpl::class.java - ) + val apiClient = + Mockito.mock( + MParticleApiClientImpl::class.java, + ) val rampException = MPRampException() Mockito.`when`(apiClient.sendMessageBatch(Mockito.anyString(), Mockito.any())).thenThrow(rampException) Mockito.`when`(handler.mParticleDBManager.deleteUpload(Mockito.anyInt())).thenReturn(1) @@ -148,42 +151,47 @@ class UploadHandlerTest { IOException::class, MPThrottleException::class, JSONException::class, - MPRampException::class + MPRampException::class, ) fun testRetryLogic() { val deleteId = AndroidUtils.Mutable(null) - val database: MParticleDBManager = object : MParticleDBManager(MockContext()) { - override fun deleteUpload(id: Int): Int { - deleteId.value = id - return id + val database: MParticleDBManager = + object : MParticleDBManager(MockContext()) { + override fun deleteUpload(id: Int): Int { + deleteId.value = id + return id + } } - } - val uploadHandler: UploadHandler = object : UploadHandler( - MockContext(), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - Mockito.mock(MessageManager::class.java), - database, - Mockito.mock(KitFrameworkWrapper::class.java) - ) { - override fun shouldDelete(statusCode: Int): Boolean { - return false + val uploadHandler: UploadHandler = + object : UploadHandler( + MockContext(), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + Mockito.mock(MessageManager::class.java), + database, + Mockito.mock(KitFrameworkWrapper::class.java), + ) { + override fun shouldDelete(statusCode: Int): Boolean = false } - } - val mockApiClient = Mockito.mock( - MParticleApiClient::class.java - ) - Mockito.`when`( - mockApiClient.sendAliasRequest( - Mockito.any( - String::class.java - ), - Mockito.any( - UploadSettings::class.java - ) + val mockApiClient = + Mockito.mock( + MParticleApiClient::class.java, ) - ).thenReturn(AliasNetworkResponse(0)) - Mockito.`when`(mConfigManager.uploadSettings).thenReturn(UploadSettings("apiKey", "secret", NetworkOptions.builder().build(), "", "")) + Mockito + .`when`( + mockApiClient.sendAliasRequest( + Mockito.any( + String::class.java, + ), + Mockito.any( + UploadSettings::class.java, + ), + ), + ).thenReturn(AliasNetworkResponse(0)) + Mockito + .`when`( + mConfigManager.uploadSettings, + ).thenReturn(UploadSettings("apiKey", "secret", NetworkOptions.builder().build(), "", "")) uploadHandler.setApiClient(mockApiClient) TestCase.assertNull(deleteId.value) val aliasRequest = TestingUtils.getInstance().randomAliasRequest @@ -197,49 +205,54 @@ class UploadHandlerTest { IOException::class, MPThrottleException::class, JSONException::class, - MPRampException::class + MPRampException::class, ) fun testDeleteLogic() { val deletedUpload = AndroidUtils.Mutable(null) - val database: MParticleDBManager = object : MParticleDBManager(MockContext()) { - override fun deleteUpload(id: Int): Int { - deletedUpload.value = id - return id + val database: MParticleDBManager = + object : MParticleDBManager(MockContext()) { + override fun deleteUpload(id: Int): Int { + deletedUpload.value = id + return id + } } - } - val uploadHandler: UploadHandler = object : UploadHandler( - MockContext(), - Mockito.mock(ConfigManager::class.java), - Mockito.mock(AppStateManager::class.java), - Mockito.mock(MessageManager::class.java), - database, - Mockito.mock(KitFrameworkWrapper::class.java) - ) { - override fun shouldDelete(statusCode: Int): Boolean { - return true + val uploadHandler: UploadHandler = + object : UploadHandler( + MockContext(), + Mockito.mock(ConfigManager::class.java), + Mockito.mock(AppStateManager::class.java), + Mockito.mock(MessageManager::class.java), + database, + Mockito.mock(KitFrameworkWrapper::class.java), + ) { + override fun shouldDelete(statusCode: Int): Boolean = true } - } - val mockApiClient = Mockito.mock( - MParticleApiClient::class.java - ) - Mockito.`when`( - mockApiClient.sendAliasRequest( - Mockito.any( - String::class.java - ), - Mockito.any( - UploadSettings::class.java - ) + val mockApiClient = + Mockito.mock( + MParticleApiClient::class.java, ) - ).thenReturn(AliasNetworkResponse(0)) - Mockito.`when`(mConfigManager.uploadSettings).thenReturn(UploadSettings("apiKey", "secret", NetworkOptions.builder().build(), "", "")) + Mockito + .`when`( + mockApiClient.sendAliasRequest( + Mockito.any( + String::class.java, + ), + Mockito.any( + UploadSettings::class.java, + ), + ), + ).thenReturn(AliasNetworkResponse(0)) + Mockito + .`when`( + mConfigManager.uploadSettings, + ).thenReturn(UploadSettings("apiKey", "secret", NetworkOptions.builder().build(), "", "")) uploadHandler.setApiClient(mockApiClient) TestCase.assertNull(deletedUpload.value) val aliasRequest = TestingUtils.getInstance().randomAliasRequest uploadHandler.uploadAliasRequest( 1, MPAliasMessage(aliasRequest, "das", "apiKey").toString(), - mConfigManager.uploadSettings + mConfigManager.uploadSettings, ) Assert.assertNotNull(deletedUpload.value) } @@ -249,41 +262,45 @@ class UploadHandlerTest { MPRampException::class, MPThrottleException::class, JSONException::class, - IOException::class + IOException::class, ) fun testAliasCallback() { val ran = RandomUtils() PowerMockito.mockStatic(MPUtility::class.java) - Mockito.`when`( - MPUtility.isAppDebuggable( - Mockito.any( - Context::class.java - ) - ) - ).thenReturn(true) + Mockito + .`when`( + MPUtility.isAppDebuggable( + Mockito.any( + Context::class.java, + ), + ), + ).thenReturn(true) val capturedResponse = AndroidUtils.Mutable(null) - val sdkListener: SdkListener = object : SdkListener() { - override fun onAliasRequestFinished(aliasResponse: AliasResponse) { - capturedResponse.value = aliasResponse + val sdkListener: SdkListener = + object : SdkListener() { + override fun onAliasRequestFinished(aliasResponse: AliasResponse) { + capturedResponse.value = aliasResponse + } } - } MParticle.addListener(MockContext(), sdkListener) - val mockApiClient = Mockito.mock( - MParticleApiClient::class.java - ) + val mockApiClient = + Mockito.mock( + MParticleApiClient::class.java, + ) handler.setApiClient(mockApiClient) // test successful request - Mockito.`when`( - mockApiClient.sendAliasRequest( - Mockito.any( - String::class.java + Mockito + .`when`( + mockApiClient.sendAliasRequest( + Mockito.any( + String::class.java, + ), + Mockito.any( + UploadSettings::class.java, + ), ), - Mockito.any( - UploadSettings::class.java - ) - ) - ).thenReturn(AliasNetworkResponse(202)) + ).thenReturn(AliasNetworkResponse(202)) TestCase.assertNull(capturedResponse.value) var aliasRequest = TestingUtils.getInstance().randomAliasRequest var aliasRequestMessage = MPAliasMessage(aliasRequest, "das", "apiKey") @@ -297,16 +314,17 @@ class UploadHandlerTest { capturedResponse.value = null // test retry request - Mockito.`when`( - mockApiClient.sendAliasRequest( - Mockito.any( - String::class.java + Mockito + .`when`( + mockApiClient.sendAliasRequest( + Mockito.any( + String::class.java, + ), + Mockito.any( + UploadSettings::class.java, + ), ), - Mockito.any( - UploadSettings::class.java - ) - ) - ).thenReturn(AliasNetworkResponse(429)) + ).thenReturn(AliasNetworkResponse(429)) TestCase.assertNull(capturedResponse.value) aliasRequest = TestingUtils.getInstance().randomAliasRequest aliasRequestMessage = MPAliasMessage(aliasRequest, "das", "apiKey") @@ -321,16 +339,17 @@ class UploadHandlerTest { // test error message present val error = ran.getAlphaNumericString(20) - Mockito.`when`( - mockApiClient.sendAliasRequest( - Mockito.any( - String::class.java + Mockito + .`when`( + mockApiClient.sendAliasRequest( + Mockito.any( + String::class.java, + ), + Mockito.any( + UploadSettings::class.java, + ), ), - Mockito.any( - UploadSettings::class.java - ) - ) - ).thenReturn(AliasNetworkResponse(400, error)) + ).thenReturn(AliasNetworkResponse(400, error)) TestCase.assertNull(capturedResponse.value) aliasRequest = TestingUtils.getInstance().randomAliasRequest aliasRequestMessage = MPAliasMessage(aliasRequest, "das", "apiKey") @@ -349,38 +368,44 @@ class UploadHandlerTest { IOException::class, MPThrottleException::class, JSONException::class, - MPRampException::class + MPRampException::class, ) fun testFullUploadLogic() { val database = MockMParticleDBManager() - val mockConfigManager = Mockito.mock( - ConfigManager::class.java - ) + val mockConfigManager = + Mockito.mock( + ConfigManager::class.java, + ) Mockito.`when`(mockConfigManager.uploadInterval).thenReturn(100) - Mockito.`when`(mockConfigManager.uploadSettings).thenReturn(UploadSettings("apiKey", "secret", NetworkOptions.builder().build(), "", "")) - val mockAppStateManager = Mockito.mock( - AppStateManager::class.java - ) - val session: InternalSession = object : InternalSession() { - override fun isActive(): Boolean { - return true + Mockito + .`when`( + mockConfigManager.uploadSettings, + ).thenReturn(UploadSettings("apiKey", "secret", NetworkOptions.builder().build(), "", "")) + val mockAppStateManager = + Mockito.mock( + AppStateManager::class.java, + ) + val session: InternalSession = + object : InternalSession() { + override fun isActive(): Boolean = true } - } Mockito.`when`(mockAppStateManager.session).thenReturn(session) val uploadHandler = MockUploadHandler(database, mockConfigManager, mockAppStateManager) - val mockApiClient = Mockito.mock( - MParticleApiClient::class.java - ) - Mockito.`when`( - mockApiClient.sendMessageBatch( - Mockito.any( - String::class.java - ), - Mockito.any( - UploadSettings::class.java - ) + val mockApiClient = + Mockito.mock( + MParticleApiClient::class.java, ) - ).thenReturn(200) + Mockito + .`when`( + mockApiClient.sendMessageBatch( + Mockito.any( + String::class.java, + ), + Mockito.any( + UploadSettings::class.java, + ), + ), + ).thenReturn(200) uploadHandler.setApiClient(mockApiClient) // send a regular "upload loop" message @@ -403,31 +428,29 @@ class UploadHandlerTest { internal inner class MockMParticleDBManager : MParticleDBManager(MockContext()) { var hasMessagesTrueCount = 0 - override fun hasMessagesForUpload(): Boolean { - return hasMessagesTrueCount-- > 0 - } - override fun getDatabase(): MPDatabase? { - return null - } + override fun hasMessagesForUpload(): Boolean = hasMessagesTrueCount-- > 0 + + override fun getDatabase(): MPDatabase? = null } internal inner class MockUploadHandler( database: MParticleDBManager?, configManager: ConfigManager?, - appStateManager: AppStateManager? + appStateManager: AppStateManager?, ) : UploadHandler( - MockContext(), - configManager, - appStateManager, - Mockito.mock(MessageManager::class.java), - database, - Mockito.mock(KitFrameworkWrapper::class.java) - ) { + MockContext(), + configManager, + appStateManager, + Mockito.mock(MessageManager::class.java), + database, + Mockito.mock(KitFrameworkWrapper::class.java), + ) { var message: Message? = null var messageDelay: Long? = null var uploadCalledCount = 0 var prepareMessageUploadsCalledCount = 0 + override fun upload() { uploadCalledCount++ } @@ -442,7 +465,10 @@ class UploadHandlerTest { messageDelay = null } - public override fun sendEmptyDelayed(what: Int, uptimeMillis: Long) { + public override fun sendEmptyDelayed( + what: Int, + uptimeMillis: Long, + ) { message?.what = what messageDelay = uptimeMillis } diff --git a/android-core/src/test/kotlin/com/mparticle/internal/listeners/InternalListenerManagerTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/listeners/InternalListenerManagerTest.kt index b384c5b6e..70eaf860d 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/listeners/InternalListenerManagerTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/listeners/InternalListenerManagerTest.kt @@ -87,8 +87,6 @@ class InternalListenerManagerTest { return applicationInfo } - override fun getPackageName(): String { - return "test.package.name" - } + override fun getPackageName(): String = "test.package.name" } } diff --git a/android-core/src/test/kotlin/com/mparticle/networking/CustomAttributesTests.kt b/android-core/src/test/kotlin/com/mparticle/networking/CustomAttributesTests.kt index 9e665f715..daae94edd 100644 --- a/android-core/src/test/kotlin/com/mparticle/networking/CustomAttributesTests.kt +++ b/android-core/src/test/kotlin/com/mparticle/networking/CustomAttributesTests.kt @@ -8,13 +8,13 @@ import kotlin.test.assertNotNull import kotlin.test.assertTrue class CustomAttributesTests { - @Test fun testListSerialization() { val customAttributesList = mutableMapOf("list" to listOf("foo", "bar", "this", "that")) val serialized = "[foo, bar, this, that]" - MPEvent.Builder("Test Event") + MPEvent + .Builder("Test Event") .customAttributes(customAttributesList) .build() .let { @@ -25,7 +25,8 @@ class CustomAttributesTests { val customAttributesArrayList = mutableMapOf("list" to arrayListOf("foo", "bar", "this", "that")) - MPEvent.Builder("Test Event") + MPEvent + .Builder("Test Event") .customAttributes(customAttributesArrayList) .build() .let { @@ -52,7 +53,8 @@ class CustomAttributesTests { val customAttributesMap = mutableMapOf("list" to mapOf("foo" to "bar", "this" to "that")) - MPEvent.Builder("Test Event") + MPEvent + .Builder("Test Event") .customAttributes(customAttributesMap) .build() .let { @@ -62,7 +64,8 @@ class CustomAttributesTests { val customAttributesHashMap = mutableMapOf("list" to hashMapOf("foo" to "bar", "this" to "that")) - MPEvent.Builder("Test Event") + MPEvent + .Builder("Test Event") .customAttributes(customAttributesHashMap) .build() .let { @@ -72,14 +75,17 @@ class CustomAttributesTests { @Test fun testJSONSerialization() { - val customAttributesMap = mutableMapOf( - "list" to mapOf( - "foo" to "bar", - "this" to "that" - ).let { JSONObject(it.toMap()) } - ) + val customAttributesMap = + mutableMapOf( + "list" to + mapOf( + "foo" to "bar", + "this" to "that", + ).let { JSONObject(it.toMap()) }, + ) val serialized = "{\"foo\":\"bar\",\"this\":\"that\"}" - MPEvent.Builder("Test Event") + MPEvent + .Builder("Test Event") .customAttributes(customAttributesMap) .build() .let { diff --git a/android-core/src/test/kotlin/com/mparticle/networking/DomainMappingTest.kt b/android-core/src/test/kotlin/com/mparticle/networking/DomainMappingTest.kt index f3102a803..aba1ec895 100644 --- a/android-core/src/test/kotlin/com/mparticle/networking/DomainMappingTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/networking/DomainMappingTest.kt @@ -13,26 +13,32 @@ class DomainMappingTest { fun nullCertificatesNotAdded() { val certificates: MutableList = ArrayList() certificates.add(null) - val domainMapping = DomainMapping.eventsMapping("test") - .setCertificates(certificates) - .build() + val domainMapping = + DomainMapping + .eventsMapping("test") + .setCertificates(certificates) + .build() Assert.assertEquals(0, domainMapping.certificates.size.toLong()) } @Test fun malformedCertificateNotAdded() { - val domainMapping = DomainMapping.eventsMapping("test") - .addCertificate("", "") - .build() + val domainMapping = + DomainMapping + .eventsMapping("test") + .addCertificate("", "") + .build() Assert.assertEquals(0, domainMapping.certificates.size.toLong()) } @Test fun addCertificateTest() { val certificate = Certificate.with("alias", "certificate") - val domainMapping = DomainMapping.eventsMapping("test") - .addCertificate(certificate!!.alias, certificate.certificate) - .build() + val domainMapping = + DomainMapping + .eventsMapping("test") + .addCertificate(certificate!!.alias, certificate.certificate) + .build() Assert.assertEquals(1, domainMapping.certificates.size.toLong()) Assert.assertEquals(certificate.alias, domainMapping.certificates[0].alias) Assert.assertEquals(certificate.certificate, domainMapping.certificates[0].certificate) @@ -53,9 +59,11 @@ class DomainMappingTest { } var domainMapping = builder.build() assertContainsCertificates(certificates, domainMapping) - domainMapping = DomainMapping.eventsMapping("test") - .setCertificates(ArrayList(certificates.values)) - .build() + domainMapping = + DomainMapping + .eventsMapping("test") + .setCertificates(ArrayList(certificates.values)) + .build() assertContainsCertificates(certificates, domainMapping) builder = DomainMapping.eventsMapping("test") for (certificate in certificates.values) { @@ -67,11 +75,11 @@ class DomainMappingTest { private fun assertContainsCertificates( certificates: Map, - domainMapping: DomainMapping + domainMapping: DomainMapping, ) { Assert.assertEquals( certificates.values.size.toLong(), - domainMapping.certificates.size.toLong() + domainMapping.certificates.size.toLong(), ) for (certificate in domainMapping.certificates) { val match = certificates[certificate.alias] diff --git a/android-core/src/test/kotlin/com/mparticle/networking/NetworkOptionsTest.kt b/android-core/src/test/kotlin/com/mparticle/networking/NetworkOptionsTest.kt index a41a7c74c..45938a5ad 100644 --- a/android-core/src/test/kotlin/com/mparticle/networking/NetworkOptionsTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/networking/NetworkOptionsTest.kt @@ -9,37 +9,49 @@ class NetworkOptionsTest { @Throws(Exception::class) fun testNetworkOptionsSerialization() { val random = RandomUtils.getInstance() - val options = NetworkOptions.builder().addDomainMapping( - DomainMapping.configMapping("www.configUrl.com") - .addCertificate("godaddy", random.getAlphaNumericString(24, 256)) - .addCertificate( - Certificate.with( - "random", - random.getAlphaNumericString(24, 256) - )!! - ).build() - ).addDomainMapping( - DomainMapping.identityMapping("www.identityUrl.com") - .addCertificate("random1", random.getAlphaNumericString(24, 256)) - .addCertificate( - Certificate.with( - "random2", - random.getAlphaNumericString(24, 256) - )!! - ).addCertificate("random3", random.getAlphaNumericString(24, 256)).build() - ).addDomainMapping( - DomainMapping.eventsMapping("www.eventsUrl.com") - .addCertificate("random3", random.getAlphaNumericString(24, 256)) - .addCertificate("random4", random.getAlphaNumericString(24, 256)) - .addCertificate("random5", random.getAlphaNumericString(24, 256)).build() - ).setPinningDisabledInDevelopment(true).build() + val options = + NetworkOptions + .builder() + .addDomainMapping( + DomainMapping + .configMapping("www.configUrl.com") + .addCertificate("godaddy", random.getAlphaNumericString(24, 256)) + .addCertificate( + Certificate.with( + "random", + random.getAlphaNumericString(24, 256), + )!!, + ).build(), + ).addDomainMapping( + DomainMapping + .identityMapping("www.identityUrl.com") + .addCertificate("random1", random.getAlphaNumericString(24, 256)) + .addCertificate( + Certificate.with( + "random2", + random.getAlphaNumericString(24, 256), + )!!, + ).addCertificate("random3", random.getAlphaNumericString(24, 256)) + .build(), + ).addDomainMapping( + DomainMapping + .eventsMapping("www.eventsUrl.com") + .addCertificate("random3", random.getAlphaNumericString(24, 256)) + .addCertificate("random4", random.getAlphaNumericString(24, 256)) + .addCertificate("random5", random.getAlphaNumericString(24, 256)) + .build(), + ).setPinningDisabledInDevelopment(true) + .build() val optionsString = options.toString() val optionsDeserialized = NetworkOptions.withNetworkOptions(optionsString) Assert.assertTrue(equals(options, optionsDeserialized)) } companion object { - fun equals(networkOptions1: NetworkOptions, networkOptions2: NetworkOptions?): Boolean { + fun equals( + networkOptions1: NetworkOptions, + networkOptions2: NetworkOptions?, + ): Boolean { if (networkOptions1 === networkOptions2) { return true } @@ -55,7 +67,10 @@ class NetworkOptionsTest { return true } - fun equals(domainMapping1: DomainMapping, domainMapping2: DomainMapping): Boolean { + fun equals( + domainMapping1: DomainMapping, + domainMapping2: DomainMapping, + ): Boolean { if (domainMapping1 === domainMapping2) { return true } @@ -63,7 +78,7 @@ class NetworkOptionsTest { for (i in domainMapping1.certificates.indices) { if (!equals( domainMapping1.certificates[i], - domainMapping2.certificates[i] + domainMapping2.certificates[i], ) ) { return false @@ -73,11 +88,17 @@ class NetworkOptionsTest { return true } - fun equals(certificate1: Certificate, certificate2: Certificate): Boolean { + fun equals( + certificate1: Certificate, + certificate2: Certificate, + ): Boolean { if (certificate1 == certificate2) { return true } - return ((certificate1.certificate === certificate2.certificate || certificate1.certificate == certificate2.certificate) && (certificate1.alias === certificate2.alias || certificate1.alias == certificate2.alias)) + return ( + (certificate1.certificate === certificate2.certificate || certificate1.certificate == certificate2.certificate) && + (certificate1.alias === certificate2.alias || certificate1.alias == certificate2.alias) + ) } } } diff --git a/android-core/src/test/kotlin/com/mparticle/rokt/RoktOptionsTest.kt b/android-core/src/test/kotlin/com/mparticle/rokt/RoktOptionsTest.kt index 11ab265ba..86cc33582 100644 --- a/android-core/src/test/kotlin/com/mparticle/rokt/RoktOptionsTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/rokt/RoktOptionsTest.kt @@ -8,7 +8,6 @@ import org.junit.Assert.assertTrue import org.junit.Test class RoktOptionsTest { - @Test fun testDefaultConstructor_shouldCreateEmptyOptions() { val roktOptions = RoktOptions() @@ -19,10 +18,11 @@ class RoktOptionsTest { @Test fun testConstructorWithFontFilePathMap_shouldSetCorrectValues() { - val fontMap = mapOf( - "font1" to "/path/to/font1.ttf", - "font2" to "/path/to/font2.otf" - ) + val fontMap = + mapOf( + "font1" to "/path/to/font1.ttf", + "font2" to "/path/to/font2.otf", + ) val roktOptions = RoktOptions(fontFilePathMap = fontMap) @@ -35,11 +35,12 @@ class RoktOptionsTest { @Test fun testConstructorWithFontPostScriptNames_shouldSetCorrectValues() { - val fontNames = setOf( - "Arial-Bold", - "Helvetica-Light", - "CustomFont-Regular" - ) + val fontNames = + setOf( + "Arial-Bold", + "Helvetica-Light", + "CustomFont-Regular", + ) val roktOptions = RoktOptions(fontPostScriptNames = fontNames) @@ -56,10 +57,11 @@ class RoktOptionsTest { val fontMap = mapOf("font1" to "/path/to/font1.ttf") val fontNames = setOf("Arial-Bold") - val roktOptions = RoktOptions( - fontFilePathMap = fontMap, - fontPostScriptNames = fontNames - ) + val roktOptions = + RoktOptions( + fontFilePathMap = fontMap, + fontPostScriptNames = fontNames, + ) assertEquals("fontFilePathMap should match", fontMap, roktOptions.fontFilePathMap) assertEquals("fontPostScriptNames should match", fontNames, roktOptions.fontPostScriptNames) @@ -69,10 +71,11 @@ class RoktOptionsTest { @Test fun testConstructorWithEmptyCollections_shouldCreateEmptyOptions() { - val roktOptions = RoktOptions( - fontFilePathMap = emptyMap(), - fontPostScriptNames = emptySet() - ) + val roktOptions = + RoktOptions( + fontFilePathMap = emptyMap(), + fontPostScriptNames = emptySet(), + ) assertTrue("fontFilePathMap should be empty", roktOptions.fontFilePathMap.isEmpty()) assertTrue("fontPostScriptNames should be empty", roktOptions.fontPostScriptNames.isEmpty()) @@ -124,10 +127,11 @@ class RoktOptionsTest { val largeFontMap = (1..100).associate { "font$it" to "/path/to/font$it.ttf" } val largeFontNames = (1..100).map { "Font-$it" }.toSet() - val roktOptions = RoktOptions( - fontFilePathMap = largeFontMap, - fontPostScriptNames = largeFontNames - ) + val roktOptions = + RoktOptions( + fontFilePathMap = largeFontMap, + fontPostScriptNames = largeFontNames, + ) assertEquals("Should have 100 font files", 100, roktOptions.fontFilePathMap.size) assertEquals("Should have 100 font names", 100, roktOptions.fontPostScriptNames.size) @@ -153,30 +157,36 @@ class RoktOptionsTest { @Test fun testSpecialCharactersInPaths_shouldHandleCorrectly() { - val fontMap = mapOf( - "font with spaces" to "/path with spaces/font file.ttf", - "font-with-dashes" to "/path-with-dashes/font-file.ttf", - "font_with_underscores" to "/path_with_underscores/font_file.ttf", - "fontWithUnicode" to "/path/with/unicode/字体.ttf" - ) + val fontMap = + mapOf( + "font with spaces" to "/path with spaces/font file.ttf", + "font-with-dashes" to "/path-with-dashes/font-file.ttf", + "font_with_underscores" to "/path_with_underscores/font_file.ttf", + "fontWithUnicode" to "/path/with/unicode/字体.ttf", + ) val roktOptions = RoktOptions(fontFilePathMap = fontMap) assertEquals("Should handle spaces", "/path with spaces/font file.ttf", roktOptions.fontFilePathMap["font with spaces"]) assertEquals("Should handle dashes", "/path-with-dashes/font-file.ttf", roktOptions.fontFilePathMap["font-with-dashes"]) - assertEquals("Should handle underscores", "/path_with_underscores/font_file.ttf", roktOptions.fontFilePathMap["font_with_underscores"]) + assertEquals( + "Should handle underscores", + "/path_with_underscores/font_file.ttf", + roktOptions.fontFilePathMap["font_with_underscores"], + ) assertEquals("Should handle unicode", "/path/with/unicode/字体.ttf", roktOptions.fontFilePathMap["fontWithUnicode"]) } @Test fun testSpecialCharactersInFontNames_shouldHandleCorrectly() { - val fontNames = setOf( - "Arial-Bold", - "Helvetica_Light", - "Font With Spaces", - "Font.With.Dots", - "字体名称" // Unicode font name - ) + val fontNames = + setOf( + "Arial-Bold", + "Helvetica_Light", + "Font With Spaces", + "Font.With.Dots", + "字体名称", // Unicode font name + ) val roktOptions = RoktOptions(fontPostScriptNames = fontNames) diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/BaseKitOptionsTest.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/BaseKitOptionsTest.kt index 261c339d6..b6c95ac96 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/BaseKitOptionsTest.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/BaseKitOptionsTest.kt @@ -10,30 +10,34 @@ import org.json.JSONArray import org.json.JSONObject open class BaseKitOptionsTest : BaseCleanInstallEachTest() { - override fun startMParticle(optionsBuilder: MParticleOptions.Builder) { startMParticle(optionsBuilder, true) } - fun startMParticle(optionsBuilder: MParticleOptions.Builder, awaitKitLoaded: Boolean) { + fun startMParticle( + optionsBuilder: MParticleOptions.Builder, + awaitKitLoaded: Boolean, + ) { AccessUtils.setCredentialsIfEmpty(optionsBuilder) val kitsLoadedLatch = MPLatch(1) var kitCount = 0 - val kitsLoadedListener = object : Configuration { - override fun configures() = KitManagerImpl::class.java + val kitsLoadedListener = + object : Configuration { + override fun configures() = KitManagerImpl::class.java - override fun apply(kitManager: KitManagerImpl) { - kitManager.addKitsLoadedListener { kits, previousKits, kitConfigs -> - if (kitConfigs.size == kitCount) { - kitsLoadedLatch.countDown() + override fun apply(kitManager: KitManagerImpl) { + kitManager.addKitsLoadedListener { kits, previousKits, kitConfigs -> + if (kitConfigs.size == kitCount) { + kitsLoadedLatch.countDown() + } } } } - } - val options: MParticleOptions = optionsBuilder - .configuration(kitsLoadedListener) - .build() + val options: MParticleOptions = + optionsBuilder + .configuration(kitsLoadedListener) + .build() val kitOptions = options.getConfiguration(KitOptions::class.java) ?: KitOptions() val configuredKitOptions = options.getConfiguration(ConfiguredKitOptions::class.java) ?: ConfiguredKitOptions() @@ -52,8 +56,7 @@ open class BaseKitOptionsTest : BaseCleanInstallEachTest() { .let { kitCount = it.length() JSONObject().put("eks", it) - } - .let { + }.let { mServer.setupConfigResponse(it.toString()) } if (kitConfigurations.isEmpty()) { @@ -68,7 +71,8 @@ open class BaseKitOptionsTest : BaseCleanInstallEachTest() { protected fun waitForKitToStart(kitId: Int) { val latch = MPLatch(1) // wait for kit to start/reload - com.mparticle.internal.AccessUtils.getKitManager() + com.mparticle.internal.AccessUtils + .getKitManager() .addKitsLoadedListener { kits, previousKits, kitConfigs -> if (kits.containsKey(kitId)) { latch.countDown() @@ -85,7 +89,8 @@ open class BaseKitOptionsTest : BaseCleanInstallEachTest() { @JvmOverloads fun waitForKitReload(after: (() -> Unit)? = null) { val latch = MPLatch(1) - com.mparticle.internal.AccessUtils.getKitManager() + com.mparticle.internal.AccessUtils + .getKitManager() .addKitsLoadedListener { _: Map, _: Map?, _: List? -> latch.countDown() } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/ConfiguredKitOptions.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/ConfiguredKitOptions.kt index 290627208..2deb4ce22 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/ConfiguredKitOptions.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/ConfiguredKitOptions.kt @@ -5,14 +5,15 @@ import org.json.JSONObject class ConfiguredKitOptions : KitOptions() { val testingConfiguration = mutableMapOf() - override fun addKit(kitId: Int, type: Class): ConfiguredKitOptions { - return addKit(kitId, type, JSONObject().put("id", kitId)) - } + override fun addKit( + kitId: Int, + type: Class, + ): ConfiguredKitOptions = addKit(kitId, type, JSONObject().put("id", kitId)) fun addKit( kitId: Int, type: Class, - config: JSONObject? + config: JSONObject?, ): ConfiguredKitOptions { testingConfiguration[kitId] = config?.put("id", kitId) super.addKit(kitId, type) @@ -20,6 +21,5 @@ class ConfiguredKitOptions : KitOptions() { } } -fun ConfiguredKitOptions(configuredKitOptions: ConfiguredKitOptions.() -> Unit): ConfiguredKitOptions { - return ConfiguredKitOptions().apply(configuredKitOptions) -} +fun ConfiguredKitOptions(configuredKitOptions: ConfiguredKitOptions.() -> Unit): ConfiguredKitOptions = + ConfiguredKitOptions().apply(configuredKitOptions) diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/DataplanBlockingUserTests.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/DataplanBlockingUserTests.kt index 9a4e20328..69f488624 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/DataplanBlockingUserTests.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/DataplanBlockingUserTests.kt @@ -32,13 +32,14 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { @Before fun beforeTests() { - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .configuration( KitOptions { addKit(-1, AttributeListenerTestKit::class.java) addKit(-2, IdentityListenerTestKit::class.java) addKit(-3, UserAttributeListenerTestKit::class.java) - } + }, ).let { startMParticle(it) } @@ -68,8 +69,8 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { Random.nextBoolean(), Random.nextBoolean(), true, - Random.nextBoolean() - ) + Random.nextBoolean(), + ), ) userAttributeListenerKitKit.onSetUserAttribute = { key, _, _ -> @@ -80,7 +81,11 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { assertTrue(allowedAttributes.containsKey(key)) assertFalse(blockedAttributes.containsKey(key)) } - MParticle.getInstance()?.Identity()?.currentUser?.userAttributes = + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.userAttributes = allowedAttributes + blockedAttributes AccessUtils.awaitMessageHandler() @@ -90,7 +95,11 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { // sanity check to make sure the non-filtered User has the blocked identities assertEquals( allowedAttributes + blockedAttributes, - MParticle.getInstance()?.Identity()?.currentUser?.userAttributes + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.userAttributes, ) } @@ -108,8 +117,8 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { Random.nextBoolean(), Random.nextBoolean(), blockUserAttributes = true, - blockUserIdentities = false - ) + blockUserIdentities = false, + ), ) kitIntegrationTestKits.forEach { kit -> @@ -119,7 +128,11 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { } } (allowedAttributes + blockedAttributes).entries.forEach { - MParticle.getInstance()?.Identity()?.currentUser?.setUserAttribute(it.key, it.value) + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.setUserAttribute(it.key, it.value) } AccessUtils.awaitMessageHandler() @@ -145,10 +158,18 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { count++ } (allowedAttributes + blockedAttributes).keys.forEach { - MParticle.getInstance()?.Identity()?.currentUser?.removeUserAttribute(it) + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.removeUserAttribute(it) } - MParticle.getInstance()?.Identity()?.currentUser?.userAttributes = mapOf() + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.userAttributes = mapOf() AccessUtils.awaitMessageHandler() assertEquals(count, allowedAttributes.size * 4) @@ -156,7 +177,15 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { assertEquals(0, it.allUserAttributes.size) } // sanity check to make sure the non-filtered User has the blocked identities - assertEquals(0, MParticle.getInstance()?.Identity()?.currentUser?.userAttributes?.size) + assertEquals( + 0, + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.userAttributes + ?.size, + ) } @Test @@ -166,8 +195,11 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { val datapoints = getRandomDataplanPoints() val allowedAttributes = randomAttributes().map { it.key to listOf(it.value) }.toMap() - val blockedAttributes = randomAttributes().map { it.key to listOf(it.value) }.toMap() - .filterKeys { !allowedAttributes.containsKey(it) } + val blockedAttributes = + randomAttributes() + .map { it.key to listOf(it.value) } + .toMap() + .filterKeys { !allowedAttributes.containsKey(it) } assertTrue(blockedAttributes.isNotEmpty()) datapoints[DataplanFilterImpl.USER_ATTRIBUTES_KEY] = allowedAttributes.keys.toHashSet() @@ -177,8 +209,8 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { Random.nextBoolean(), Random.nextBoolean(), true, - Random.nextBoolean() - ) + Random.nextBoolean(), + ), ) var count = 0 @@ -199,7 +231,11 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { assertFalse(blockedAttributes.containsKey(key)) count++ } - MParticle.getInstance()?.Identity()?.currentUser?.userAttributes = + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.userAttributes = allowedAttributes + blockedAttributes AccessUtils.awaitMessageHandler() @@ -211,7 +247,11 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { // sanity check to make sure the non-filtered User has the blocked attributes assertEquals( allowedAttributes + blockedAttributes, - MParticle.getInstance()?.Identity()?.currentUser?.userAttributes + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.userAttributes, ) } @@ -229,14 +269,15 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { Random.nextBoolean(), Random.nextBoolean(), Random.nextBoolean(), - true - ) + true, + ), ) MParticle.getInstance()?.Identity()?.login( - IdentityApiRequest.withEmptyUser() + IdentityApiRequest + .withEmptyUser() .userIdentities(blockIdentities + allowedIdentities) - .build() + .build(), ) val latch = MPLatch(1) kitIntegrationTestKits.forEach { kit -> @@ -256,7 +297,11 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { // sanity check to make sure the non-filtered User has the blocked identities assertEquals( allowedIdentities + blockIdentities, - MParticle.getInstance()?.Identity()?.currentUser?.userIdentities + MParticle + .getInstance() + ?.Identity() + ?.currentUser + ?.userIdentities, ) } @@ -293,32 +338,32 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { // assertEquals(allowedIdentities + blockedIdentities, MParticle.getInstance()?.Identity()?.currentUser?.userIdentities) // } - private fun getRandomDataplanEventKey(): DataplanFilterImpl.DataPoint { - return when (Random.Default.nextInt(0, 5)) { - 0 -> DataplanFilterImpl.DataPoint( - DataplanFilterImpl.CUSTOM_EVENT_KEY, - randomString(5), - randomEventType().ordinal.toString() - ) + private fun getRandomDataplanEventKey(): DataplanFilterImpl.DataPoint = + when (Random.Default.nextInt(0, 5)) { + 0 -> + DataplanFilterImpl.DataPoint( + DataplanFilterImpl.CUSTOM_EVENT_KEY, + randomString(5), + randomEventType().ordinal.toString(), + ) 1 -> DataplanFilterImpl.DataPoint(DataplanFilterImpl.SCREEN_EVENT_KEY, randomString(8)) - 2 -> DataplanFilterImpl.DataPoint( - DataplanFilterImpl.PRODUCT_ACTION_KEY, - randomProductAction() - ) - 3 -> DataplanFilterImpl.DataPoint( - DataplanFilterImpl.PROMOTION_ACTION_KEY, - randomPromotionAction() - ) + 2 -> + DataplanFilterImpl.DataPoint( + DataplanFilterImpl.PRODUCT_ACTION_KEY, + randomProductAction(), + ) + 3 -> + DataplanFilterImpl.DataPoint( + DataplanFilterImpl.PROMOTION_ACTION_KEY, + randomPromotionAction(), + ) 4 -> DataplanFilterImpl.DataPoint(DataplanFilterImpl.PRODUCT_IMPRESSION_KEY) else -> throw IllegalArgumentException("messed this implementation up :/") } - } - private fun getRandomDataplanPoints(): MutableMap> { - return (0..Random.Default.nextInt(0, 10)) + private fun getRandomDataplanPoints(): MutableMap> = + (0..Random.Default.nextInt(0, 10)) .associate { getRandomDataplanEventKey().toString() to randomAttributes().keys.toHashSet() - } - .toMutableMap() - } + }.toMutableMap() } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/GCMPushMessageForwardingTest.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/GCMPushMessageForwardingTest.kt index 07d0f073b..1f76e0dc5 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/GCMPushMessageForwardingTest.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/GCMPushMessageForwardingTest.kt @@ -12,24 +12,25 @@ import org.junit.Assert.assertNotNull import org.junit.Test class GCMPushMessageForwardingTest : BaseKitOptionsTest() { - @Test fun testPushForwardedAfterSDKStarted() { var receivedIntent: Intent? = null - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .credentials("key", "secret") .configuration(KitOptions().addKit(1, PushListenerTestKit::class.java)) .let { startMParticle(it) } - val intent = Intent() - .apply { - action = "com.google.android.c2dm.intent.RECEIVE" - data = Uri.EMPTY - putExtras(Bundle()) - } + val intent = + Intent() + .apply { + action = "com.google.android.c2dm.intent.RECEIVE" + data = Uri.EMPTY + putExtras(Bundle()) + } (MParticle.getInstance()?.getKitInstance(1) as PushListenerTestKit).onPushMessageReceived = { context, intent -> receivedIntent = intent diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KitBatchingTest.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KitBatchingTest.kt index c7e14c7f3..98b369c3e 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KitBatchingTest.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KitBatchingTest.kt @@ -16,15 +16,16 @@ import org.junit.Before import org.junit.Test class KitBatchingTest : BaseKitOptionsTest() { - @Before fun before() { - val options = MParticleOptions.builder(mContext) - .configuration( - KitOptions() - .addKit(123, BatchKit::class.java) - .addKit(456, EventTestKit::class.java) - ) + val options = + MParticleOptions + .builder(mContext) + .configuration( + KitOptions() + .addKit(123, BatchKit::class.java) + .addKit(456, EventTestKit::class.java), + ) startMParticle(options) } @@ -39,16 +40,17 @@ class KitBatchingTest : BaseKitOptionsTest() { null } } - val event = MPEvent.Builder("some event") - .customAttributes( - mapOf( - "String" to "String", - "Long" to 100L, - "Double" to 1.1, - "Map" to mapOf("foo" to "bar", "buzz" to false) - ) - ) - .build() + val event = + MPEvent + .Builder("some event") + .customAttributes( + mapOf( + "String" to "String", + "Long" to 100L, + "Double" to 1.1, + "Map" to mapOf("foo" to "bar", "buzz" to false), + ), + ).build() MParticle.getInstance()?.logEvent(event) latch.await() @@ -114,9 +116,13 @@ class KitBatchingTest : BaseKitOptionsTest() { assertEquals(2, batchKit.batches.size) } - class BatchKit : BaseTestKit(), KitIntegration.BatchListener { + class BatchKit : + BaseTestKit(), + KitIntegration.BatchListener { var batches = mutableListOf() + override fun getName() = "Batch Kit" + private var latch = MPLatch(1) fun await() { diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KitManagerImplTests.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KitManagerImplTests.kt index f50d63592..e98cb5e67 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KitManagerImplTests.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KitManagerImplTests.kt @@ -19,7 +19,6 @@ import org.junit.Assert.assertTrue import org.junit.Test class KitManagerImplTests : BaseKitOptionsTest() { - @Test fun testKitIntializationViaKitOptions() { KitOptions() @@ -27,12 +26,13 @@ class KitManagerImplTests : BaseKitOptionsTest() { .addKit(1002, IdentityListenerTestKit::class.java) .addKit(1003, UserAttributeListenerTestKit::class.java) .let { - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .configuration(it) - } - .let { + }.let { startMParticle(it) } + fun getKit(kitId: Int) = MParticle.getInstance()?.getKitInstance(kitId) assertTrue(getKit(1001) is AttributeListenerTestKit) @@ -47,7 +47,8 @@ class KitManagerImplTests : BaseKitOptionsTest() { Handler(Looper.getMainLooper()).post { latch.await() } // Force the SDK to make a config request (using the ugly internals) - JSONObject().put("eks", ConfigManager.getInstance(mContext).latestKitConfiguration) + JSONObject() + .put("eks", ConfigManager.getInstance(mContext).latestKitConfiguration) .let { ConfigManager.getInstance(mContext).updateConfig(it) } @@ -57,7 +58,8 @@ class KitManagerImplTests : BaseKitOptionsTest() { @Test fun testActiveKitReporting() { - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .configuration( ConfiguredKitOptions { addKit(-1, AttributeListenerTestKit::class.java, JSONObject().put("eau", true)) @@ -71,14 +73,23 @@ class KitManagerImplTests : BaseKitOptionsTest() { // kit dependency in the classpath, but not in the /config response testingConfiguration[-2] = null testingConfiguration[-5] = null - } + }, ).let { startMParticle(it) - waitForKitReload() { - MParticle.getInstance()?.Internal()?.configManager?.setMpid(123, false) + waitForKitReload { + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.setMpid(123, false) } } - val kitStatus = MParticle.getInstance()?.Internal()?.kitManager?.kitStatus + val kitStatus = + MParticle + .getInstance() + ?.Internal() + ?.kitManager + ?.kitStatus assertNotNull(kitStatus) if (kitStatus == null) { return @@ -96,7 +107,11 @@ class KitManagerImplTests : BaseKitOptionsTest() { val expectedBundledKits = "-6,-5,-4,-3,-2.-1" assertEquals( expectedActiveKits, - MParticle.getInstance()?.Internal()?.configManager?.activeModuleIds + MParticle + .getInstance() + ?.Internal() + ?.configManager + ?.activeModuleIds, ) // check that the active kits value is sent to the server diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KnownUserKitsLifecycleTest.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KnownUserKitsLifecycleTest.kt index 5307874de..d93250868 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KnownUserKitsLifecycleTest.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KnownUserKitsLifecycleTest.kt @@ -11,35 +11,34 @@ class KnownUserKitsLifecycleTest : BaseKitOptionsTest() { @Before @Throws(JSONException::class) fun before() { - val builder = MParticleOptions.builder(mContext) - .configuration( - ConfiguredKitOptions() - .addKit(-1, TestKit1::class.java, JSONObject().put("eau", true)) - .addKit(-2, TestKit2::class.java, JSONObject().put("eau", false)) - .addKit(-3, TestKit3::class.java, JSONObject().put("eau", true)) - ) + val builder = + MParticleOptions + .builder(mContext) + .configuration( + ConfiguredKitOptions() + .addKit(-1, TestKit1::class.java, JSONObject().put("eau", true)) + .addKit(-2, TestKit2::class.java, JSONObject().put("eau", false)) + .addKit(-3, TestKit3::class.java, JSONObject().put("eau", true)), + ) startMParticle(builder) } class TestKit1 : TestKit() + class TestKit2 : TestKit() + class TestKit3 : TestKit() + open class TestKit : ListenerTestKit() { - override fun getName(): String { - return "test kit" + i++ - } + override fun getName(): String = "test kit" + i++ @Throws(IllegalArgumentException::class) override fun onKitCreate( settings: Map?, - context: Context - ): List { - return emptyList() - } + context: Context, + ): List = emptyList() - override fun setOptOut(optedOut: Boolean): List { - return emptyList() - } + override fun setOptOut(optedOut: Boolean): List = emptyList() companion object { var i = 0 diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/UpdateConfigTest.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/UpdateConfigTest.kt index 33b3bda04..f2670e0a4 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/UpdateConfigTest.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/UpdateConfigTest.kt @@ -14,11 +14,11 @@ import org.junit.Assert.assertTrue import org.junit.Test class UpdateConfigTest : BaseKitOptionsTest() { - @Test fun testKitsLoadFromRemoteConfig() { setCachedConfig(null) - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .configuration( ConfiguredKitOptions { addKit(1, BaseTestKit::class.java) @@ -26,7 +26,7 @@ class UpdateConfigTest : BaseKitOptionsTest() { addKit(3, BaseTestKit::class.java) addKit(4, BaseTestKit::class.java, null) addKit(5, BaseTestKit::class.java) - } + }, ).let { startMParticle(it) } @@ -45,12 +45,13 @@ class UpdateConfigTest : BaseKitOptionsTest() { @Test fun testStartKitWithNewRemoteConfig() { setCachedConfig(null) - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .configuration( ConfiguredKitOptions { addKit(1, BaseTestKit::class.java) addKit(2, BaseTestKit::class.java, null) - } + }, ).let { startMParticle(it) } @@ -63,8 +64,8 @@ class UpdateConfigTest : BaseKitOptionsTest() { "eks", JSONArray() .put(JSONObject().put("id", 1)) - .put(JSONObject().put("id", 2)) - ).toString() + .put(JSONObject().put("id", 2)), + ).toString(), ) AccessUtils.getKitManager().addKitsLoadedListener { kits, previousKits, kitConfigs -> @@ -79,12 +80,13 @@ class UpdateConfigTest : BaseKitOptionsTest() { @Test fun testShutdownKitWithNewRemoteConfig() { setCachedConfig(null) - MParticleOptions.builder(mContext) + MParticleOptions + .builder(mContext) .configuration( ConfiguredKitOptions { addKit(1, BaseTestKit::class.java) addKit(2, BaseTestKit::class.java) - } + }, ).let { startMParticle(it) } @@ -94,8 +96,8 @@ class UpdateConfigTest : BaseKitOptionsTest() { .put( "eks", JSONArray() - .put(JSONObject().put("id", 1)) - ).toString() + .put(JSONObject().put("id", 1)), + ).toString(), ) val latch = MPLatch(1) diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/AttributeListenerTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/AttributeListenerTestKit.kt index 644c9ecd9..e186da9ed 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/AttributeListenerTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/AttributeListenerTestKit.kt @@ -4,7 +4,9 @@ import com.mparticle.MParticle import com.mparticle.kits.KitIntegration import com.mparticle.kits.ReportingMessage -open class AttributeListenerTestKit : ListenerTestKit(), KitIntegration.AttributeListener { +open class AttributeListenerTestKit : + ListenerTestKit(), + KitIntegration.AttributeListener { var setUserAttribute: ((attributeKey: String?, attributeValue: String?) -> Unit)? = null var setUserAttributeList: ((attributeKey: String?, attributeValueList: List?) -> Unit)? = null @@ -21,7 +23,7 @@ open class AttributeListenerTestKit : ListenerTestKit(), KitIntegration.Attribut override fun setUserAttributeList( attributeKey: String, - attributeValueList: MutableList + attributeValueList: MutableList, ) { setUserAttributeList?.invoke(attributeKey, attributeValueList) onAttributeReceived?.invoke(attributeKey, attributeValueList) @@ -29,19 +31,25 @@ open class AttributeListenerTestKit : ListenerTestKit(), KitIntegration.Attribut override fun setAllUserAttributes( userAttributes: Map, - userAttributeLists: Map> + userAttributeLists: Map>, ) { setAllUserAttributes?.invoke(userAttributes, userAttributeLists) userAttributes.forEach { onAttributeReceived?.invoke(it.key, it.value) } userAttributeLists.forEach { onAttributeReceived?.invoke(it.key, it.value) } } - override fun setUserAttribute(attributeKey: String, attributeValue: String?) { + override fun setUserAttribute( + attributeKey: String, + attributeValue: String?, + ) { setUserAttribute?.invoke(attributeKey, attributeValue) onAttributeReceived?.invoke(attributeKey, attributeValue) } - override fun setUserIdentity(identityType: MParticle.IdentityType, identity: String?) { + override fun setUserIdentity( + identityType: MParticle.IdentityType, + identity: String?, + ) { setUserIdentity?.invoke(identityType, identity) onIdentityReceived?.invoke(identityType, identity) } @@ -56,7 +64,5 @@ open class AttributeListenerTestKit : ListenerTestKit(), KitIntegration.Attribut onAttributeReceived?.invoke(key, null) } - override fun logout(): List { - return logout?.invoke() ?: listOf() - } + override fun logout(): List = logout?.invoke() ?: listOf() } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/BaseTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/BaseTestKit.kt index 821fb50f8..ab13cc94c 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/BaseTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/BaseTestKit.kt @@ -7,19 +7,15 @@ import com.mparticle.kits.ReportingMessage open class BaseTestKit : KitIntegration() { open override fun onKitCreate( settings: Map?, - context: Context - ): List { - return listOf() - } + context: Context, + ): List = listOf() open override fun setOptOut(optedOut: Boolean): List { // do nothing return listOf() } - open override fun getName(): String { - return this::class.java.simpleName - } + open override fun getName(): String = this::class.java.simpleName open override fun getInstance() = this } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/CommerceListenerTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/CommerceListenerTestKit.kt index e38a6d7b2..c59f095a4 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/CommerceListenerTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/CommerceListenerTestKit.kt @@ -5,22 +5,21 @@ import com.mparticle.kits.KitIntegration import com.mparticle.kits.ReportingMessage import java.math.BigDecimal -class CommerceListenerTestKit : ListenerTestKit(), KitIntegration.CommerceListener { +class CommerceListenerTestKit : + ListenerTestKit(), + KitIntegration.CommerceListener { var logEvent: ((CommerceEvent?) -> List)? = null var logLtvIncrease: ((BigDecimal?, BigDecimal?, String?, Map?) -> List)? = null - override fun logEvent(event: CommerceEvent?): List { - return logEvent?.invoke(event) ?: listOf() - } + override fun logEvent(event: CommerceEvent?): List = logEvent?.invoke(event) ?: listOf() override fun logLtvIncrease( valueIncreased: BigDecimal?, valueTotal: BigDecimal?, eventName: String?, - contextInfo: Map? - ): List { - return logLtvIncrease?.invoke(valueIncreased, valueTotal, eventName, contextInfo) + contextInfo: Map?, + ): List = + logLtvIncrease?.invoke(valueIncreased, valueTotal, eventName, contextInfo) ?: listOf() - } } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/EventTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/EventTestKit.kt index 11a0ae7a6..f93a60117 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/EventTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/EventTestKit.kt @@ -4,12 +4,12 @@ import com.mparticle.MPEvent import com.mparticle.kits.KitIntegration import com.mparticle.kits.ReportingMessage -class EventTestKit : ListenerTestKit(), KitIntegration.EventListener { +class EventTestKit : + ListenerTestKit(), + KitIntegration.EventListener { var onLogEvent: (MPEvent) -> MutableList? = { null } - override fun logEvent(baseEvent: MPEvent): MutableList? { - return onLogEvent(baseEvent) - } + override fun logEvent(baseEvent: MPEvent): MutableList? = onLogEvent(baseEvent) override fun leaveBreadcrumb(breadcrumb: String?): MutableList { TODO("Not yet implemented") @@ -17,7 +17,7 @@ class EventTestKit : ListenerTestKit(), KitIntegration.EventListener { override fun logError( message: String?, - errorAttributes: MutableMap? + errorAttributes: MutableMap?, ): MutableList { TODO("Not yet implemented") } @@ -25,14 +25,14 @@ class EventTestKit : ListenerTestKit(), KitIntegration.EventListener { override fun logException( exception: Exception?, exceptionAttributes: MutableMap?, - message: String? + message: String?, ): MutableList { TODO("Not yet implemented") } override fun logScreen( screenName: String?, - screenAttributes: MutableMap? + screenAttributes: MutableMap?, ): MutableList { TODO("Not yet implemented") } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/IdentityListenerTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/IdentityListenerTestKit.kt index 000d2e743..11132b302 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/IdentityListenerTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/IdentityListenerTestKit.kt @@ -4,7 +4,9 @@ import com.mparticle.identity.MParticleUser import com.mparticle.kits.FilteredIdentityApiRequest import com.mparticle.kits.KitIntegration -open class IdentityListenerTestKit : ListenerTestKit(), KitIntegration.IdentityListener { +open class IdentityListenerTestKit : + ListenerTestKit(), + KitIntegration.IdentityListener { var onIdentifyCompleted: ((mParticleUser: MParticleUser?, identityApiRequest: FilteredIdentityApiRequest?) -> Unit)? = null var onLoginCompleted: ((mParticleUser: MParticleUser?, identityApiRequest: FilteredIdentityApiRequest?) -> Unit)? = @@ -17,7 +19,7 @@ open class IdentityListenerTestKit : ListenerTestKit(), KitIntegration.IdentityL override fun onLogoutCompleted( mParticleUser: MParticleUser?, - identityApiRequest: FilteredIdentityApiRequest? + identityApiRequest: FilteredIdentityApiRequest?, ) { onLogoutCompleted?.invoke(mParticleUser, identityApiRequest) onUserReceived?.invoke(mParticleUser) @@ -25,7 +27,7 @@ open class IdentityListenerTestKit : ListenerTestKit(), KitIntegration.IdentityL override fun onLoginCompleted( mParticleUser: MParticleUser?, - identityApiRequest: FilteredIdentityApiRequest? + identityApiRequest: FilteredIdentityApiRequest?, ) { onLoginCompleted?.invoke(mParticleUser, identityApiRequest) onUserReceived?.invoke(mParticleUser) @@ -33,7 +35,7 @@ open class IdentityListenerTestKit : ListenerTestKit(), KitIntegration.IdentityL override fun onIdentifyCompleted( mParticleUser: MParticleUser?, - identityApiRequest: FilteredIdentityApiRequest? + identityApiRequest: FilteredIdentityApiRequest?, ) { onIdentifyCompleted?.invoke(mParticleUser, identityApiRequest) onUserReceived?.invoke(mParticleUser) @@ -41,7 +43,7 @@ open class IdentityListenerTestKit : ListenerTestKit(), KitIntegration.IdentityL override fun onModifyCompleted( mParticleUser: MParticleUser?, - identityApiRequest: FilteredIdentityApiRequest? + identityApiRequest: FilteredIdentityApiRequest?, ) { onModifyCompleted?.invoke(mParticleUser, identityApiRequest) onUserReceived?.invoke(mParticleUser) diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/ListenerTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/ListenerTestKit.kt index 0b7979d36..bb3b41b0a 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/ListenerTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/ListenerTestKit.kt @@ -16,12 +16,15 @@ abstract class ListenerTestKit : BaseTestKit() { var getName: (() -> String)? = null override fun getName() = getName?.invoke() ?: "Test Kit thing" - override fun setOptOut(optedOut: Boolean) = setOptOut?.invoke(optedOut) - ?: listOf() + + override fun setOptOut(optedOut: Boolean) = + setOptOut?.invoke(optedOut) + ?: listOf() override fun onKitCreate( settings: Map?, - context: Context - ): List = onKitCreate?.invoke(settings, context) - ?: listOf() + context: Context, + ): List = + onKitCreate?.invoke(settings, context) + ?: listOf() } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/PushListenerTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/PushListenerTestKit.kt index 837346d70..8475f9508 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/PushListenerTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/PushListenerTestKit.kt @@ -4,16 +4,23 @@ import android.content.Context import android.content.Intent import com.mparticle.kits.KitIntegration -class PushListenerTestKit : BaseTestKit(), KitIntegration.PushListener { +class PushListenerTestKit : + BaseTestKit(), + KitIntegration.PushListener { var onPushMessageReceived: (Context, Intent?) -> Unit = { _, _ -> } var onPushRegistration: (String?, String?) -> Boolean = { _, _ -> false } + override fun willHandlePushMessage(intent: Intent?) = true - override fun onPushMessageReceived(context: Context, pushIntent: Intent?) { + override fun onPushMessageReceived( + context: Context, + pushIntent: Intent?, + ) { onPushMessageReceived.invoke(context, pushIntent) } - override fun onPushRegistration(instanceId: String?, senderId: String?): Boolean { - return onPushRegistration.invoke(instanceId, senderId) - } + override fun onPushRegistration( + instanceId: String?, + senderId: String?, + ): Boolean = onPushRegistration.invoke(instanceId, senderId) } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt index ab59245b4..3eebfc018 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt @@ -4,7 +4,9 @@ import com.mparticle.consent.ConsentState import com.mparticle.kits.FilteredMParticleUser import com.mparticle.kits.KitIntegration -open class UserAttributeListenerTestKit : ListenerTestKit(), KitIntegration.UserAttributeListener { +open class UserAttributeListenerTestKit : + ListenerTestKit(), + KitIntegration.UserAttributeListener { var onIncrementUserAttribute: ((key: String?, incrementedBy: Number, value: String?, user: FilteredMParticleUser?) -> Unit)? = null var onRemoveUserAttribute: ((key: String?, user: FilteredMParticleUser?) -> Unit)? = null @@ -13,7 +15,9 @@ open class UserAttributeListenerTestKit : ListenerTestKit(), KitIntegration.User var onSetUserTag: ((key: String?, user: FilteredMParticleUser?) -> Unit)? = null var onSetUserAttributeList: ((attributeKey: String?, attributeValueList: List?, user: FilteredMParticleUser?) -> Unit)? = null - var onSetAllUserAttributes: ((userAttributes: Map?, userAttributeLists: Map?>?, user: FilteredMParticleUser?) -> Unit)? = + var onSetAllUserAttributes: ( + (userAttributes: Map?, userAttributeLists: Map?>?, user: FilteredMParticleUser?) -> Unit + )? = null var supportsAttributeLists: (() -> Boolean)? = null var onConsentStateUpdated: ((oldState: ConsentState?, newState: ConsentState?, user: FilteredMParticleUser?) -> Unit)? = @@ -22,7 +26,7 @@ open class UserAttributeListenerTestKit : ListenerTestKit(), KitIntegration.User override fun onConsentStateUpdated( oldState: ConsentState?, newState: ConsentState?, - user: FilteredMParticleUser? + user: FilteredMParticleUser?, ) { onConsentStateUpdated?.invoke(oldState, newState, user) } @@ -30,19 +34,26 @@ open class UserAttributeListenerTestKit : ListenerTestKit(), KitIntegration.User override fun onSetAllUserAttributes( userAttributes: Map?, userAttributeLists: Map>?, - user: FilteredMParticleUser? + user: FilteredMParticleUser?, ) { onSetAllUserAttributes?.invoke(userAttributes, userAttributeLists, user) userAttributes?.forEach { onAttributeReceived?.invoke(it.key, it.value) } } - override fun onSetUserAttribute(key: String?, value: Any?, user: FilteredMParticleUser?) { + override fun onSetUserAttribute( + key: String?, + value: Any?, + user: FilteredMParticleUser?, + ) { onSetUserAttribute?.invoke(key, value, user) onAttributeReceived?.invoke(key, value) onUserReceived?.invoke(user) } - override fun onSetUserTag(key: String?, user: FilteredMParticleUser?) { + override fun onSetUserTag( + key: String?, + user: FilteredMParticleUser?, + ) { onSetUserTag?.invoke(key, user) onAttributeReceived?.invoke(key, null) onUserReceived?.invoke(user) @@ -52,7 +63,7 @@ open class UserAttributeListenerTestKit : ListenerTestKit(), KitIntegration.User key: String?, incrementedBy: Number, value: String?, - user: FilteredMParticleUser? + user: FilteredMParticleUser?, ) { onIncrementUserAttribute?.invoke(key, incrementedBy, value, user) onAttributeReceived?.invoke(key, value) @@ -62,14 +73,17 @@ open class UserAttributeListenerTestKit : ListenerTestKit(), KitIntegration.User override fun onSetUserAttributeList( attributeKey: String?, attributeValueList: MutableList?, - user: FilteredMParticleUser? + user: FilteredMParticleUser?, ) { onSetUserAttributeList?.invoke(attributeKey, attributeValueList, user) onAttributeReceived?.invoke(attributeKey, attributeValueList) onUserReceived?.invoke(user) } - override fun onRemoveUserAttribute(key: String?, user: FilteredMParticleUser?) { + override fun onRemoveUserAttribute( + key: String?, + user: FilteredMParticleUser?, + ) { onRemoveUserAttribute?.invoke(key, user) onAttributeReceived?.invoke(key, null) onUserReceived?.invoke(user) diff --git a/android-kit-base/src/main/java/com/mparticle/kits/KitManagerImpl.java b/android-kit-base/src/main/java/com/mparticle/kits/KitManagerImpl.java index 9c95e62d4..c1a232808 100644 --- a/android-kit-base/src/main/java/com/mparticle/kits/KitManagerImpl.java +++ b/android-kit-base/src/main/java/com/mparticle/kits/KitManagerImpl.java @@ -1543,8 +1543,8 @@ private void confirmEmail( // If there's an existing email but it doesn't match the passed-in email, log a warning if (emailMismatch && existingEmail != null) { Logger.warning(String.format( - "The existing email on the user (%s) does not match the email passed to selectPlacements (%s). " + - "Please make sure to sync the email identity to mParticle as soon as it's available. " + + "The existing email on the user (%s) does not match the email passed to selectPlacements (%s). " + "Please make sure to sync the email identity to mParticle as soon as it's available. " "Identifying user with the provided email before continuing to selectPlacements.", existingEmail, email )); @@ -1552,8 +1552,8 @@ private void confirmEmail( // If there's an existing other but it doesn't match the passed-in hashed email, log a warning else if (hashedEmailMismatch && existingHashedEmail != null) { Logger.warning(String.format( - "The existing hashed email on the user (%s) does not match the hashed email passed to selectPlacements (%s). " + - "Please make sure to sync the hashed email identity to mParticle as soon as it's available. " + + "The existing hashed email on the user (%s) does not match the hashed email passed to selectPlacements (%s). " + "Please make sure to sync the hashed email identity to mParticle as soon as it's available. " "Identifying user with the provided hashed email before continuing to selectPlacements.", existingHashedEmail, hashedEmail )); @@ -1576,7 +1576,7 @@ else if (hashedEmailMismatch && existingHashedEmail != null) { }); task.addSuccessListener(result -> { - Logger.debug("Updated email identity based on selectPlacement's attributes: " + + Logger.debug("Updated email identity based on selectPlacement's attributes: " result.getUser().getUserIdentities().get(MParticle.IdentityType.Email)); runnable.run(); }); diff --git a/android-kit-base/src/main/java/com/mparticle/kits/MPSideloadedFilters.kt b/android-kit-base/src/main/java/com/mparticle/kits/MPSideloadedFilters.kt index 7665d9567..3593f383a 100644 --- a/android-kit-base/src/main/java/com/mparticle/kits/MPSideloadedFilters.kt +++ b/android-kit-base/src/main/java/com/mparticle/kits/MPSideloadedFilters.kt @@ -3,7 +3,6 @@ package com.mparticle.kits import org.json.JSONObject class MPSideloadedFilters { - var filters: MutableMap = mutableMapOf() private set } diff --git a/android-kit-base/src/main/java/com/mparticle/kits/MPSideloadedKit.kt b/android-kit-base/src/main/java/com/mparticle/kits/MPSideloadedKit.kt index 7a74ca0ab..8747ce4df 100644 --- a/android-kit-base/src/main/java/com/mparticle/kits/MPSideloadedKit.kt +++ b/android-kit-base/src/main/java/com/mparticle/kits/MPSideloadedKit.kt @@ -4,28 +4,35 @@ import android.content.Context import com.mparticle.internal.SideloadedKit import org.json.JSONObject -abstract class MPSideloadedKit(val kitId: Int) : KitIntegration(), SideloadedKit { - +abstract class MPSideloadedKit( + val kitId: Int, +) : KitIntegration(), + SideloadedKit { companion object { const val MIN_SIDELOADED_KIT = 1000000 } init { - configuration = KitConfiguration.createKitConfiguration( - JSONObject().put( - KitConfiguration.KEY_ID, - kitId + configuration = + KitConfiguration.createKitConfiguration( + JSONObject().put( + KitConfiguration.KEY_ID, + kitId, + ), ) - ) } override fun kitId(): Int = kitId - override fun getName(): String = this::class.java.name.split(".").last().orEmpty() + override fun getName(): String = + this::class.java.name + .split(".") + .last() + .orEmpty() override fun onKitCreate( settings: MutableMap?, - context: Context? + context: Context?, ): MutableList = mutableListOf() override fun setOptOut(optedOut: Boolean): MutableList = mutableListOf() @@ -37,7 +44,5 @@ abstract class MPSideloadedKit(val kitId: Int) : KitIntegration(), SideloadedKit override fun getJsonConfig(): JSONObject? = super.getJsonConfig() - private fun KitConfiguration.applyFilters(filters: MPSideloadedFilters): KitConfiguration? { - return configuration?.applySideloadedKits(filters) - } + private fun KitConfiguration.applyFilters(filters: MPSideloadedFilters): KitConfiguration? = configuration?.applySideloadedKits(filters) } diff --git a/android-kit-base/src/main/kotlin/com/mparticle/kits/DataplanFilter.kt b/android-kit-base/src/main/kotlin/com/mparticle/kits/DataplanFilter.kt index 7a4525e71..319b3caa7 100644 --- a/android-kit-base/src/main/kotlin/com/mparticle/kits/DataplanFilter.kt +++ b/android-kit-base/src/main/kotlin/com/mparticle/kits/DataplanFilter.kt @@ -12,9 +12,13 @@ import org.json.JSONObject internal interface DataplanFilter { fun transformEventForEvent(event: T?): T? + fun transformIdentities(identities: Map?): Map? + fun transformUserAttributes(attributes: Map?): Map? + fun isUserAttributeBlocked(key: String?): Boolean + fun isUserIdentityBlocked(key: MParticle.IdentityType?): Boolean } @@ -23,16 +27,15 @@ internal class DataplanFilterImpl constructor( private val blockEvents: Boolean, private val blockEventAttributes: Boolean, private val blockUserAttributes: Boolean, - private val blockUserIdentities: Boolean + private val blockUserIdentities: Boolean, ) : DataplanFilter { - constructor(dataplanOptions: MParticleOptions.DataplanOptions) : this( extractDataPoints(dataplanOptions.dataplan), dataplanOptions.isBlockEvents, dataplanOptions.isBlockEventAttributes, dataplanOptions.isBlockUserAttributes, - dataplanOptions.isBlockUserIdentities + dataplanOptions.isBlockUserIdentities, ) init { @@ -45,11 +48,11 @@ Data Plan parsed for Kit Filtering: blockUserAttributes=$blockUserAttributes blockUserIdentities=$blockUserIdentities ${ - dataPoints.entries.joinToString("\n") { (key, value) -> - "$key\n\t${value?.joinToString("\n\t") { it }}" - } + dataPoints.entries.joinToString("\n") { (key, value) -> + "$key\n\t${value?.joinToString("\n\t") { it }}" + } } - """ + """, ) } @@ -65,31 +68,35 @@ Data Plan parsed for Kit Filtering: return null } if (blockEvents || blockEventAttributes) { - val dataPointKey = when { - event is MPEvent -> - when { - event.isScreenEvent -> DataPoint(SCREEN_EVENT_KEY, event.eventName) - else -> DataPoint( - CUSTOM_EVENT_KEY, - event.eventName, - event.eventType.getEventsApiName() - ) - } - event is CommerceEvent -> - when { - !event.productAction.isNullOrBlank() -> DataPoint( - PRODUCT_ACTION_KEY, - event.productAction - ) - !event.promotionAction.isNullOrBlank() -> DataPoint( - PROMOTION_ACTION_KEY, - event.promotionAction - ) - !event.impressions.isNullOrEmpty() -> DataPoint(PRODUCT_IMPRESSION_KEY) - else -> null - } - else -> null - } + val dataPointKey = + when { + event is MPEvent -> + when { + event.isScreenEvent -> DataPoint(SCREEN_EVENT_KEY, event.eventName) + else -> + DataPoint( + CUSTOM_EVENT_KEY, + event.eventName, + event.eventType.getEventsApiName(), + ) + } + event is CommerceEvent -> + when { + !event.productAction.isNullOrBlank() -> + DataPoint( + PRODUCT_ACTION_KEY, + event.productAction, + ) + !event.promotionAction.isNullOrBlank() -> + DataPoint( + PROMOTION_ACTION_KEY, + event.promotionAction, + ) + !event.impressions.isNullOrEmpty() -> DataPoint(PRODUCT_IMPRESSION_KEY) + else -> null + } + else -> null + } // shouldn't happen but we have to handle it dataPointKey ?: return event // if there is no valid datapoint then it is an unplanned event @@ -99,23 +106,25 @@ Data Plan parsed for Kit Filtering: } val dataPoint = dataPoints[dataPointKey.toString()] if (blockEventAttributes) { - event.customAttributes = event.customAttributeStrings?.filterKeys { - // null dataPoint means there are no constraints for custom attributes - if (dataPoint == null || dataPoint.contains(it)) { - true - } else { - Logger.verbose("Blocking unplanned attribute: $it") - false + event.customAttributes = + event.customAttributeStrings?.filterKeys { + // null dataPoint means there are no constraints for custom attributes + if (dataPoint == null || dataPoint.contains(it)) { + true + } else { + Logger.verbose("Blocking unplanned attribute: $it") + false + } } - } if (event is CommerceEvent) { val productActionDatapoint = dataPoints["$dataPointKey.$PRODUCT_ACTION_PRODUCTS"] event.products?.iterator()?.forEach { product -> product?.customAttributes?.toMutableMap()?.apply { - val filteredAttributes = filterKeys { - productActionDatapoint?.contains(it) ?: true - } + val filteredAttributes = + filterKeys { + productActionDatapoint?.contains(it) ?: true + } clear() putAll(filteredAttributes) } @@ -126,9 +135,10 @@ Data Plan parsed for Kit Filtering: event.impressions?.iterator()?.forEach { it.products.forEach { product -> product?.customAttributes?.toMutableMap()?.apply { - val filteredAttributes = filterKeys { - productImpressionDatapoint?.contains(it) ?: true - } + val filteredAttributes = + filterKeys { + productImpressionDatapoint?.contains(it) ?: true + } clear() putAll(filteredAttributes) } @@ -286,14 +296,20 @@ Data Plan parsed for Kit Filtering: } // returns a set of "allowed" keys, or `null` if all keys are allowed - private fun getAllowedKeys(datapoint: DataPoint, jsonObject: JSONObject): HashSet? { - val definition = jsonObject.optJSONObject("validator") - ?.optJSONObject("definition") + private fun getAllowedKeys( + datapoint: DataPoint, + jsonObject: JSONObject, + ): HashSet? { + val definition = + jsonObject + .optJSONObject("validator") + ?.optJSONObject("definition") when (datapoint.type) { CUSTOM_EVENT_KEY, SCREEN_EVENT_KEY, PRODUCT_IMPRESSION_KEY, PROMOTION_ACTION_KEY, PRODUCT_ACTION_KEY -> { - val data = definition - ?.optJSONObject("properties") - ?.optJSONObject("data") ?: return null + val data = + definition + ?.optJSONObject("properties") + ?.optJSONObject("data") ?: return null if (datapoint.productAttributeType == null) { data.let { val customAttributes = @@ -307,34 +323,39 @@ Data Plan parsed for Kit Filtering: } } else { data.let { - val products = when (datapoint.productAttributeType) { - PRODUCT_ACTION_PRODUCTS -> { - val productBlock = - it.getConstrainedPropertiesJSONObject("product_action") - ?.getConstrainedPropertiesJSONObject("products") - if (productBlock == emptyJSONObject) { - return hashSetOf() + val products = + when (datapoint.productAttributeType) { + PRODUCT_ACTION_PRODUCTS -> { + val productBlock = + it + .getConstrainedPropertiesJSONObject("product_action") + ?.getConstrainedPropertiesJSONObject("products") + if (productBlock == emptyJSONObject) { + return hashSetOf() + } + productBlock } - productBlock - } - PRODUCT_IMPRESSION_PRODUCTS -> { - var productBlock = - it.getConstrainedPropertiesJSONObject("product_impressions") - if (productBlock == emptyJSONObject) { - return hashSetOf() + PRODUCT_IMPRESSION_PRODUCTS -> { + var productBlock = + it.getConstrainedPropertiesJSONObject("product_impressions") + if (productBlock == emptyJSONObject) { + return hashSetOf() + } + productBlock = + productBlock + ?.optJSONObject("items") + ?.getConstrainedPropertiesJSONObject("products") + if (productBlock == emptyJSONObject) { + return hashSetOf() + } + productBlock } - productBlock = productBlock?.optJSONObject("items") - ?.getConstrainedPropertiesJSONObject("products") - if (productBlock == emptyJSONObject) { - return hashSetOf() + else -> { + return null } - productBlock } - else -> { - return null - } - } - return products?.optJSONObject("items") + return products + ?.optJSONObject("items") ?.getConstrainedPropertiesJSONObject("custom_attributes") ?.getConstrainedPropertiesKeySet() } @@ -404,12 +425,10 @@ Data Plan parsed for Kit Filtering: } } - fun MParticle.IdentityType.getEventsApiName(): String { - return MParticleIdentityClientImpl.getStringValue(this) - } + fun MParticle.IdentityType.getEventsApiName(): String = MParticleIdentityClientImpl.getStringValue(this) - fun MParticle.EventType.getEventsApiName(): String { - return when (this) { + fun MParticle.EventType.getEventsApiName(): String = + when (this) { MParticle.EventType.Location -> "location" MParticle.EventType.Media -> "media" MParticle.EventType.Navigation -> "navigation" @@ -421,7 +440,6 @@ Data Plan parsed for Kit Filtering: MParticle.EventType.UserPreference -> "user_preference" else -> "unknown" } - } fun Iterator.toHashSet(): HashSet { val set = HashSet() @@ -430,11 +448,15 @@ Data Plan parsed for Kit Filtering: } } - class DataPoint(val type: String, val name: String? = null, val eventType: String? = null) { + class DataPoint( + val type: String, + val name: String? = null, + val eventType: String? = null, + ) { constructor(datapoint: DataPoint) : this( datapoint.type, datapoint.name, - datapoint.eventType + datapoint.eventType, ) var productAttributeType: String? = null @@ -442,24 +464,29 @@ Data Plan parsed for Kit Filtering: fun getProductDataPoints() = when (type) { - PRODUCT_ACTION_KEY, PRODUCT_IMPRESSION_KEY -> listOf( - DataPoint(this).apply { productAttributeType = PRODUCT_ACTION_PRODUCTS }, - DataPoint(this).apply { productAttributeType = PRODUCT_IMPRESSION_PRODUCTS } - ) + PRODUCT_ACTION_KEY, PRODUCT_IMPRESSION_KEY -> + listOf( + DataPoint(this).apply { productAttributeType = PRODUCT_ACTION_PRODUCTS }, + DataPoint(this).apply { productAttributeType = PRODUCT_IMPRESSION_PRODUCTS }, + ) else -> null } override fun toString() = - "$type${if (name != null) ".$name" else ""}${if (eventType != null) ".$eventType" else ""}${productAttributeType?.let { ".$it" } ?: ""}" + "$type${if (name != null) ".$name" else ""}${if (eventType != null) ".$eventType" else ""}${productAttributeType?.let { + ".$it" + } ?: ""}" } class EmptyDataplanFilter : DataplanFilter { override fun transformEventForEvent(event: T?) = event - override fun transformIdentities(identities: Map?) = - identities + + override fun transformIdentities(identities: Map?) = identities override fun transformUserAttributes(attributes: Map?) = attributes + override fun isUserAttributeBlocked(key: String?) = false + override fun isUserIdentityBlocked(key: MParticle.IdentityType?) = false } } diff --git a/android-kit-base/src/main/kotlin/com/mparticle/kits/KitOptions.kt b/android-kit-base/src/main/kotlin/com/mparticle/kits/KitOptions.kt index 3690e189b..ec7f9b158 100644 --- a/android-kit-base/src/main/kotlin/com/mparticle/kits/KitOptions.kt +++ b/android-kit-base/src/main/kotlin/com/mparticle/kits/KitOptions.kt @@ -2,21 +2,24 @@ package com.mparticle.kits import com.mparticle.Configuration -open class KitOptions(initializer: KitOptions.() -> Unit = {}) : Configuration { +open class KitOptions( + initializer: KitOptions.() -> Unit = {}, +) : Configuration { val kits: MutableMap> = mutableMapOf() init { this.initializer() } - open fun addKit(kitId: Int, type: Class): KitOptions { + open fun addKit( + kitId: Int, + type: Class, + ): KitOptions { kits[kitId] = type return this } - override fun configures(): Class { - return KitManagerImpl::class.java - } + override fun configures(): Class = KitManagerImpl::class.java override fun apply(kitManager: KitManagerImpl) { kitManager.setKitOptions(this) diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/DataplanFilterImplTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/DataplanFilterImplTest.kt index a74886571..45e84b874 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/DataplanFilterImplTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/DataplanFilterImplTest.kt @@ -33,12 +33,15 @@ class DataplanFilterImplTest { @Test fun testParseDataplan() { - val dataplan = File("src/test/kotlin/com/mparticle/kits/sample_dataplan.json") - .readText() - .toJSON() - val dataplanOptions = MParticleOptions.DataplanOptions.builder() - .dataplanVersion(dataplan) - .build() + val dataplan = + File("src/test/kotlin/com/mparticle/kits/sample_dataplan.json") + .readText() + .toJSON() + val dataplanOptions = + MParticleOptions.DataplanOptions + .builder() + .dataplanVersion(dataplan) + .build() val dataplanFilter = DataplanFilterImpl(dataplanOptions!!) assertEquals(15, dataplanFilter.dataPoints.size) dataplanFilter.apply { @@ -56,11 +59,12 @@ class DataplanFilterImplTest { "attributeEmail", "attributeStringAlpha", "attributeBoolean", - "attributeNumMinMax" - ) + "attributeNumMinMax", + ), ) } - dataPoints.getValue("$PRODUCT_ACTION_KEY.add_to_cart.$PRODUCT_IMPRESSION_PRODUCTS") + dataPoints + .getValue("$PRODUCT_ACTION_KEY.add_to_cart.$PRODUCT_IMPRESSION_PRODUCTS") .also { assertNull(it) } @@ -79,7 +83,7 @@ class DataplanFilterImplTest { dataPoints.getValue(USER_ATTRIBUTES_KEY).also { assertEquals( it, - hashSetOf("a third attribute", "my attribute", "my other attribute") + hashSetOf("a third attribute", "my attribute", "my other attribute"), ) } dataPoints.getValue(USER_IDENTITIES_KEY).also { @@ -99,12 +103,15 @@ class DataplanFilterImplTest { @Test fun testParseDataplan2() { - val dataplan = File("src/test/kotlin/com/mparticle/kits/sample_dataplan2.json") - .readText() - .toJSON() - val dataplanOptions = MParticleOptions.DataplanOptions.builder() - .dataplanVersion(dataplan) - .build() + val dataplan = + File("src/test/kotlin/com/mparticle/kits/sample_dataplan2.json") + .readText() + .toJSON() + val dataplanOptions = + MParticleOptions.DataplanOptions + .builder() + .dataplanVersion(dataplan) + .build() val dataplanFilter = DataplanFilterImpl(dataplanOptions!!) assertEquals(20, dataplanFilter.dataPoints.size) dataplanFilter.apply { @@ -121,15 +128,16 @@ class DataplanFilterImplTest { "attributeEmail", "attributeNumEnum", "attributeStringAlpha", - "attributeBoolean" + "attributeBoolean", ), - it + it, ) } dataPoints.getValue("$PRODUCT_ACTION_KEY.add_to_cart.$PRODUCT_ACTION_PRODUCTS").also { assertNull(it) } - dataPoints.getValue("$PRODUCT_ACTION_KEY.add_to_cart.$PRODUCT_IMPRESSION_PRODUCTS") + dataPoints + .getValue("$PRODUCT_ACTION_KEY.add_to_cart.$PRODUCT_IMPRESSION_PRODUCTS") .also { assertNull(it) } @@ -151,7 +159,7 @@ class DataplanFilterImplTest { dataPoints.getValue(USER_ATTRIBUTES_KEY).also { assertEquals( hashSetOf("my attribute", "my other attribute", "a third attribute"), - it + it, ) } dataPoints.getValue(USER_IDENTITIES_KEY).also { assertNull(it) } @@ -194,9 +202,10 @@ class DataplanFilterImplTest { dataplanPoints = getRandomDataplanPoints() val datapoint = getRandomDataplanEventKey() dataplanPoints.remove(datapoint.toString()) - val event = getRandomEvent(datapoint).apply { - customAttributes = randomAttributes() - } + val event = + getRandomEvent(datapoint).apply { + customAttributes = randomAttributes() + } val dataplanFilter = DataplanFilterImpl(dataplanPoints, true, Random.nextBoolean(), false, false) @@ -211,9 +220,10 @@ class DataplanFilterImplTest { while (diversity.size != 0) { dataplanPoints = getRandomDataplanPoints() val datapoint = getRandomDataplanEventKey() - val event = getRandomEvent(datapoint).apply { - customAttributes = randomAttributes() - } + val event = + getRandomEvent(datapoint).apply { + customAttributes = randomAttributes() + } dataplanPoints[datapoint.toString()] = null @@ -231,9 +241,10 @@ class DataplanFilterImplTest { dataplanPoints = getRandomDataplanPoints() val datapoint = getRandomDataplanEventKey() dataplanPoints.remove(datapoint.toString()) - val event = getRandomEvent(datapoint).apply { - customAttributes = randomAttributes() - } + val event = + getRandomEvent(datapoint).apply { + customAttributes = randomAttributes() + } val dataplanFilter = DataplanFilterImpl(dataplanPoints, false, Random.nextBoolean(), false, false) @@ -249,16 +260,17 @@ class DataplanFilterImplTest { dataplanPoints = getRandomDataplanPoints() val datapoint = getRandomDataplanEventKey() val allowedAttributes = randomAttributes() - val event = getRandomEvent(datapoint).apply { - customAttributes = allowedAttributes - } + val event = + getRandomEvent(datapoint).apply { + customAttributes = allowedAttributes + } dataplanPoints[datapoint.toString()] = allowedAttributes.keys.toHashSet() val dataplanFilter = DataplanFilterImpl(dataplanPoints, true, Random.nextBoolean(), false, false) assertEquals( allowedAttributes, - dataplanFilter.transformEventForEvent(event)?.customAttributeStrings + dataplanFilter.transformEventForEvent(event)?.customAttributeStrings, ) diversity.remove(datapoint.type) } @@ -271,9 +283,10 @@ class DataplanFilterImplTest { dataplanPoints = getRandomDataplanPoints() val datapoint = getRandomDataplanEventKey() val allowedAttributes = randomAttributes() - val event = getRandomEvent(datapoint).apply { - customAttributes = allowedAttributes - } + val event = + getRandomEvent(datapoint).apply { + customAttributes = allowedAttributes + } val dataplanFilter = DataplanFilterImpl(dataplanPoints, false, Random.nextBoolean(), false, false) @@ -291,16 +304,17 @@ class DataplanFilterImplTest { dataplanPoints.remove(datapoint.toString()) val allowedAttributes = randomAttributes() val blockedAttributes = randomAttributes() - val event = getRandomEvent(datapoint).apply { - customAttributes = allowedAttributes + blockedAttributes - } + val event = + getRandomEvent(datapoint).apply { + customAttributes = allowedAttributes + blockedAttributes + } dataplanPoints[datapoint.toString()] = allowedAttributes.keys.toHashSet() val dataplanFilter = DataplanFilterImpl(dataplanPoints, Random.Default.nextBoolean(), true, false, false) assertEquals( allowedAttributes, - dataplanFilter.transformEventForEvent(event)?.customAttributeStrings + dataplanFilter.transformEventForEvent(event)?.customAttributeStrings, ) diversity.remove(datapoint.type) } @@ -321,118 +335,122 @@ class DataplanFilterImplTest { } } - private val types = setOf( - CUSTOM_EVENT_KEY, - PRODUCT_ACTION_KEY, - PROMOTION_ACTION_KEY, - PRODUCT_IMPRESSION_KEY, - SCREEN_EVENT_KEY - ) - - fun getRandomEvent(datapoint: DataplanPoint): BaseEvent { - return when (datapoint.type) { - CUSTOM_EVENT_KEY -> MPEvent.Builder( - datapoint.name!!, - MParticle.EventType.values().first { it.getEventsApiName() == datapoint.eventType } - ) - .build() - SCREEN_EVENT_KEY -> ScreenEventBuilder(datapoint.name!!).build() - .also { assertTrue(it.isScreenEvent) } - PRODUCT_ACTION_KEY -> CommerceEvent.Builder( - datapoint.name!!, - Product.Builder("a", "b", 1.0).build() - ).build() + private val types = + setOf( + CUSTOM_EVENT_KEY, + PRODUCT_ACTION_KEY, + PROMOTION_ACTION_KEY, + PRODUCT_IMPRESSION_KEY, + SCREEN_EVENT_KEY, + ) + + fun getRandomEvent(datapoint: DataplanPoint): BaseEvent = + when (datapoint.type) { + CUSTOM_EVENT_KEY -> + MPEvent + .Builder( + datapoint.name!!, + MParticle.EventType.values().first { it.getEventsApiName() == datapoint.eventType }, + ).build() + SCREEN_EVENT_KEY -> + ScreenEventBuilder(datapoint.name!!) + .build() + .also { assertTrue(it.isScreenEvent) } + PRODUCT_ACTION_KEY -> + CommerceEvent + .Builder( + datapoint.name!!, + Product.Builder("a", "b", 1.0).build(), + ).build() PROMOTION_ACTION_KEY -> CommerceEvent.Builder(datapoint.name!!, Promotion()).build() - PRODUCT_IMPRESSION_KEY -> CommerceEvent.Builder( - Impression( - "impressionname", - Product.Builder("a", "b", 1.0).build() - ) - ).build() + PRODUCT_IMPRESSION_KEY -> + CommerceEvent + .Builder( + Impression( + "impressionname", + Product.Builder("a", "b", 1.0).build(), + ), + ).build() else -> throw IllegalArgumentException(datapoint.type + ": messed this implementation up :/") } - } - fun getRandomDataplanEventKey(): DataplanPoint { - return when (Random.Default.nextInt(0, 5)) { - 0 -> DataplanPoint( - CUSTOM_EVENT_KEY, - randomString(5), - randomEventType().getEventsApiName() - ) + fun getRandomDataplanEventKey(): DataplanPoint = + when (Random.Default.nextInt(0, 5)) { + 0 -> + DataplanPoint( + CUSTOM_EVENT_KEY, + randomString(5), + randomEventType().getEventsApiName(), + ) 1 -> DataplanPoint(SCREEN_EVENT_KEY, randomString(8)) 2 -> DataplanPoint(PRODUCT_ACTION_KEY, randomProductAction()) 3 -> DataplanPoint(PROMOTION_ACTION_KEY, randomPromotionAction()) 4 -> DataplanPoint(PRODUCT_IMPRESSION_KEY) else -> throw IllegalArgumentException("messed this implementation up :/") } - } - fun getRandomDataplanPoints(): MutableMap?> { - return (0..Random.Default.nextInt(0, 10)) + fun getRandomDataplanPoints(): MutableMap?> = + (0..Random.Default.nextInt(0, 10)) .associate { getRandomDataplanEventKey().toString() to randomAttributes().keys.toHashSet() - } - .toMutableMap() - } + }.toMutableMap() val chars: List = ('a'..'z') + ('A'..'Z') - fun randomAttributes(): Map { - return (0..Random.Default.nextInt(0, 5)).map { - randomString(4) to randomString(8) - }.toMap() - } + fun randomAttributes(): Map = + (0..Random.Default.nextInt(0, 5)) + .map { + randomString(4) to randomString(8) + }.toMap() - fun randomString(length: Int): String { - return (0 until length).map { - chars[Random.Default.nextInt(0, chars.size - 1)] - }.joinToString("") - } + fun randomString(length: Int): String = + (0 until length) + .map { + chars[Random.Default.nextInt(0, chars.size - 1)] + }.joinToString("") - fun randomEventType(): MParticle.EventType { - return MParticle.EventType.values()[ + fun randomEventType(): MParticle.EventType = + MParticle.EventType.values()[ Random.Default.nextInt( 0, - MParticle.EventType.values().size - 1 - ) + MParticle.EventType.values().size - 1, + ), ] - } - fun randomProductAction(): String { - return randomConstString(Product::class.java) - } + fun randomProductAction(): String = randomConstString(Product::class.java) - fun randomPromotionAction(): String { - return randomConstString(Promotion::class.java) - } + fun randomPromotionAction(): String = randomConstString(Promotion::class.java) - fun randomConstString(clazz: Class<*>): String { - return clazz.fields + fun randomConstString(clazz: Class<*>): String = + clazz.fields .filter { Modifier.isPublic(it.modifiers) && Modifier.isStatic(it.modifiers) } .filter { it.name.all { it.isUpperCase() } } .filter { it.type == String::class.java } .let { it[Random.Default.nextInt(0, it.size - 1)].get(null) as String } - } private fun String.toJSON() = JSONObject(this) - class ScreenEvent(event: MPEvent) : MPEvent(event) { + class ScreenEvent( + event: MPEvent, + ) : MPEvent(event) { init { isScreenEvent = true } } - class ScreenEventBuilder(name: String) : MPEvent.Builder(name, MParticle.EventType.Other) { - override fun build(): MPEvent { - return ScreenEvent(super.build()) - } + class ScreenEventBuilder( + name: String, + ) : MPEvent.Builder(name, MParticle.EventType.Other) { + override fun build(): MPEvent = ScreenEvent(super.build()) } - class DataplanPoint(val type: String, val name: String? = null, val eventType: String? = null) { - override fun toString() = - "$type${if (name != null) ".$name" else ""}${if (eventType != null) ".$eventType" else ""}" + class DataplanPoint( + val type: String, + val name: String? = null, + val eventType: String? = null, + ) { + override fun toString() = "$type${if (name != null) ".$name" else ""}${if (eventType != null) ".$eventType" else ""}" } } diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/FilteredApiRequestTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/FilteredApiRequestTest.kt index 1475f099c..3256fa2d4 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/FilteredApiRequestTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/FilteredApiRequestTest.kt @@ -10,19 +10,22 @@ class FilteredApiRequestTest { @Test fun testEmptyApiRequest() { val request = IdentityApiRequest.withEmptyUser().build() - val mockIntegration = Mockito.mock( - KitIntegration::class.java - ) - val mockConfiguration = Mockito.mock( - KitConfiguration::class.java - ) - Mockito.`when`( - mockConfiguration.shouldSetIdentity( - Mockito.any( - IdentityType::class.java - ) + val mockIntegration = + Mockito.mock( + KitIntegration::class.java, ) - ).thenReturn(true) + val mockConfiguration = + Mockito.mock( + KitConfiguration::class.java, + ) + Mockito + .`when`( + mockConfiguration.shouldSetIdentity( + Mockito.any( + IdentityType::class.java, + ), + ), + ).thenReturn(true) Mockito.`when`(mockIntegration.configuration).thenReturn(mockConfiguration) val filteredRequest = FilteredIdentityApiRequest(request, mockIntegration) Assert.assertEquals(0, filteredRequest.userIdentities.size.toLong()) @@ -30,21 +33,26 @@ class FilteredApiRequestTest { @Test fun testApiRequestFilter() { - val request = IdentityApiRequest.withEmptyUser() - .email("testEmail") - .customerId("1234") - .userIdentity(IdentityType.Alias, "alias") - .userIdentity(IdentityType.Google, "mparticle@gmail") - .build() - val mockIntegration = Mockito.mock( - KitIntegration::class.java - ) - val mockConfiguration = Mockito.mock( - KitConfiguration::class.java - ) + val request = + IdentityApiRequest + .withEmptyUser() + .email("testEmail") + .customerId("1234") + .userIdentity(IdentityType.Alias, "alias") + .userIdentity(IdentityType.Google, "mparticle@gmail") + .build() + val mockIntegration = + Mockito.mock( + KitIntegration::class.java, + ) + val mockConfiguration = + Mockito.mock( + KitConfiguration::class.java, + ) Mockito.`when`(mockConfiguration.shouldSetIdentity(IdentityType.Email)).thenReturn(true) Mockito.`when`(mockConfiguration.shouldSetIdentity(IdentityType.Alias)).thenReturn(true) - Mockito.`when`(mockConfiguration.shouldSetIdentity(IdentityType.CustomerId)) + Mockito + .`when`(mockConfiguration.shouldSetIdentity(IdentityType.CustomerId)) .thenReturn(false) Mockito.`when`(mockConfiguration.shouldSetIdentity(IdentityType.Google)).thenReturn(false) Mockito.`when`(mockIntegration.configuration).thenReturn(mockConfiguration) diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitConfigurationTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitConfigurationTest.kt index 538648014..0f4b952af 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitConfigurationTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitConfigurationTest.kt @@ -36,8 +36,9 @@ class KitConfigurationTest { val configuration = MockKitConfiguration.createKitConfiguration(ekConfig) if (ekConfig.has("avf")) { val attributeValueFilter = ekConfig.getJSONObject("avf") - if (attributeValueFilter.has("i") && attributeValueFilter.has("a") && attributeValueFilter.has( - "v" + if (attributeValueFilter.has("i") && attributeValueFilter.has("a") && + attributeValueFilter.has( + "v", ) ) { val shouldIncludeMatches = attributeValueFilter["i"] @@ -47,15 +48,15 @@ class KitConfigurationTest { Assert.assertTrue(configuration.isAttributeValueFilteringActive) Assert.assertEquals( attributeValueFilter.getBoolean("i"), - configuration.isAvfShouldIncludeMatches + configuration.isAvfShouldIncludeMatches, ) Assert.assertEquals( attributeValueFilter.getInt("a").toLong(), - configuration.avfHashedAttribute.toLong() + configuration.avfHashedAttribute.toLong(), ) Assert.assertEquals( attributeValueFilter.getInt("v").toLong(), - configuration.avfHashedValue.toLong() + configuration.avfHashedValue.toLong(), ) } else { Assert.assertFalse(configuration.isAttributeValueFilteringActive) @@ -67,62 +68,62 @@ class KitConfigurationTest { if (filters.has("et")) { Assert.assertEquals( filters.getJSONObject("et").length().toLong(), - configuration.eventTypeFilters.size().toLong() + configuration.eventTypeFilters.size().toLong(), ) } if (filters.has("ec")) { Assert.assertEquals( filters.getJSONObject("ec").length().toLong(), - configuration.eventNameFilters.size().toLong() + configuration.eventNameFilters.size().toLong(), ) } if (filters.has("ea")) { Assert.assertEquals( filters.getJSONObject("ea").length().toLong(), - configuration.eventAttributeFilters.size().toLong() + configuration.eventAttributeFilters.size().toLong(), ) } if (filters.has("svec")) { Assert.assertEquals( filters.getJSONObject("svec").length().toLong(), - configuration.screenNameFilters.size().toLong() + configuration.screenNameFilters.size().toLong(), ) } if (filters.has("svea")) { Assert.assertEquals( filters.getJSONObject("svea").length().toLong(), - configuration.screenAttributeFilters.size().toLong() + configuration.screenAttributeFilters.size().toLong(), ) } if (filters.has("uid")) { Assert.assertEquals( filters.getJSONObject("uid").length().toLong(), - configuration.userIdentityFilters.size().toLong() + configuration.userIdentityFilters.size().toLong(), ) } if (filters.has("ua")) { Assert.assertEquals( filters.getJSONObject("ua").length().toLong(), - configuration.userAttributeFilters.size().toLong() + configuration.userAttributeFilters.size().toLong(), ) } if (filters.has("cea")) { Assert.assertEquals( filters.getJSONObject("cea").length().toLong(), - configuration.commerceAttributeFilters.size().toLong() + configuration.commerceAttributeFilters.size().toLong(), ) } if (filters.has("ent")) { Assert.assertEquals( filters.getJSONObject("ent").length().toLong(), - configuration.commerceEntityFilters.size().toLong() + configuration.commerceEntityFilters.size().toLong(), ) } if (filters.has("afa")) { val entityAttFilters = filters.getJSONObject("afa") Assert.assertEquals( entityAttFilters.length().toLong(), - configuration.commerceEntityAttributeFilters.size.toLong() + configuration.commerceEntityAttributeFilters.size.toLong(), ) val keys: MutableIterator = entityAttFilters.keys() while (keys.hasNext()) { @@ -130,7 +131,8 @@ class KitConfigurationTest { Assert.assertEquals( entityAttFilters.getJSONObject(key).length().toLong(), configuration.commerceEntityAttributeFilters[key.toInt()] - ?.size()?.toLong() + ?.size() + ?.toLong(), ) } } @@ -139,11 +141,11 @@ class KitConfigurationTest { val bracketing = ekConfig.getJSONObject("bk") Assert.assertEquals( bracketing.optInt("lo").toLong(), - configuration.lowBracket.toLong() + configuration.lowBracket.toLong(), ) Assert.assertEquals( bracketing.optInt("hi").toLong(), - configuration.highBracket.toLong() + configuration.highBracket.toLong(), ) } else { Assert.assertEquals(0, configuration.lowBracket.toLong()) @@ -155,7 +157,7 @@ class KitConfigurationTest { Assert.assertNotNull(configuration.defaultEventProjection) Assert.assertEquals( projections.length().toLong(), - (configuration.customMappingList.size + 1).toLong() + (configuration.customMappingList.size + 1).toLong(), ) } } @@ -176,41 +178,52 @@ class KitConfigurationTest { val attributes: MutableMap = HashMap() attributes["my custom attribute"] = "whatever" var event = - CommerceEvent.Builder(Product.ADD_TO_CART, Product.Builder("name", "sku", 2.0).build()) - .customAttributes(attributes).build() + CommerceEvent + .Builder(Product.ADD_TO_CART, Product.Builder("name", "sku", 2.0).build()) + .customAttributes(attributes) + .build() Assert.assertEquals("whatever", event.customAttributeStrings?.get("my custom attribute")) val filteredEvent = configuration.filterCommerceEvent(event) Assert.assertNull(filteredEvent.customAttributeStrings?.get("my custom attribute")) // make sure we're only doing it for ADD_TO_CART var event2 = - CommerceEvent.Builder(Product.PURCHASE, Product.Builder("name", "sku", 2.0).build()) + CommerceEvent + .Builder(Product.PURCHASE, Product.Builder("name", "sku", 2.0).build()) .customAttributes(attributes) - .transactionAttributes(TransactionAttributes().setId("some id")).build() + .transactionAttributes(TransactionAttributes().setId("some id")) + .build() Assert.assertEquals( "whatever", - event2.customAttributeStrings?.get("my custom attribute") + event2.customAttributeStrings?.get("my custom attribute"), ) var filteredEvent2 = configuration.filterCommerceEvent(event2) Assert.assertEquals( "whatever", - filteredEvent2.customAttributeStrings?.get("my custom attribute") + filteredEvent2.customAttributeStrings?.get("my custom attribute"), ) - event = CommerceEvent.Builder(Product.CHECKOUT, Product.Builder("name", "sku", 2.0).build()) - .checkoutOptions("cool options").build() + event = + CommerceEvent + .Builder(Product.CHECKOUT, Product.Builder("name", "sku", 2.0).build()) + .checkoutOptions("cool options") + .build() Assert.assertEquals("cool options", event.checkoutOptions) filteredEvent2 = configuration.filterCommerceEvent(event) Assert.assertNull(filteredEvent2.checkoutOptions) event = - CommerceEvent.Builder(Product.ADD_TO_CART, Product.Builder("name", "sku", 2.0).build()) - .checkoutOptions("cool options").build() + CommerceEvent + .Builder(Product.ADD_TO_CART, Product.Builder("name", "sku", 2.0).build()) + .checkoutOptions("cool options") + .build() Assert.assertEquals("cool options", event.checkoutOptions) filteredEvent2 = configuration.filterCommerceEvent(event) Assert.assertEquals("cool options", filteredEvent2.checkoutOptions) event2 = - CommerceEvent.Builder(Product.PURCHASE, Product.Builder("name", "sku", 2.0).build()) - .customAttributes(attributes).transactionAttributes( - TransactionAttributes().setId("some id").setAffiliation("cool affiliation") + CommerceEvent + .Builder(Product.PURCHASE, Product.Builder("name", "sku", 2.0).build()) + .customAttributes(attributes) + .transactionAttributes( + TransactionAttributes().setId("some id").setAffiliation("cool affiliation"), ).build() Assert.assertEquals("cool affiliation", event2.transactionAttributes?.affiliation) filteredEvent2 = configuration.filterCommerceEvent(event2) @@ -220,15 +233,18 @@ class KitConfigurationTest { @Test @Throws(Exception::class) fun testFilterCommerceEntity() { - var configuration = MockKitConfiguration.createKitConfiguration( - JSONObject( - COMMERCE_FILTERS + var configuration = + MockKitConfiguration.createKitConfiguration( + JSONObject( + COMMERCE_FILTERS, + ), ) - ) val impression = Impression("Cool list name", Product.Builder("name2", "sku", 2.0).build()) var event = - CommerceEvent.Builder(Product.ADD_TO_CART, Product.Builder("name", "sku", 2.0).build()) - .addImpression(impression).build() + CommerceEvent + .Builder(Product.ADD_TO_CART, Product.Builder("name", "sku", 2.0).build()) + .addImpression(impression) + .build() var impressionList = event.impressions if (impressionList != null) { for (imp in impressionList) { @@ -250,8 +266,10 @@ class KitConfigurationTest { config.getJSONObject("hs").getJSONObject("ent").put("1", 1) configuration = MockKitConfiguration.createKitConfiguration(config) event = - CommerceEvent.Builder(Product.ADD_TO_CART, Product.Builder("name", "sku", 2.0).build()) - .addImpression(impression).build() + CommerceEvent + .Builder(Product.ADD_TO_CART, Product.Builder("name", "sku", 2.0).build()) + .addImpression(impression) + .build() impressionList = event.impressions if (impressionList != null) { for (imp in impressionList) { @@ -273,36 +291,50 @@ class KitConfigurationTest { @Test @Throws(Exception::class) fun testFilterCommerceEntityAttribute() { - var event = CommerceEvent.Builder( - Promotion.VIEW, - Promotion().setId("promo id").setCreative("the creative").setName("promotion name") - ).build() - var configuration = MockKitConfiguration.createKitConfiguration( - JSONObject( - COMMERCE_FILTERS + var event = + CommerceEvent + .Builder( + Promotion.VIEW, + Promotion().setId("promo id").setCreative("the creative").setName("promotion name"), + ).build() + var configuration = + MockKitConfiguration.createKitConfiguration( + JSONObject( + COMMERCE_FILTERS, + ), ) - ) Assert.assertEquals("the creative", event.promotions?.get(0)?.creative) var filteredEvent = configuration.filterCommerceEvent(event) Assert.assertNull(filteredEvent.promotions?.get(0)?.creative) Assert.assertEquals("promotion name", filteredEvent.promotions?.get(0)?.name) val attributes: MutableMap = HashMap() attributes["my custom product attribute"] = "whatever" - event = CommerceEvent.Builder( - Product.CHECKOUT, - Product.Builder("name", "sku", 5.0) - .customAttributes(attributes) - .brand("cool brand").build() - ) - .build() + event = + CommerceEvent + .Builder( + Product.CHECKOUT, + Product + .Builder("name", "sku", 5.0) + .customAttributes(attributes) + .brand("cool brand") + .build(), + ).build() Assert.assertEquals( "whatever", - event.products?.get(0)?.customAttributes?.get("my custom product attribute") + event.products + ?.get(0) + ?.customAttributes + ?.get("my custom product attribute"), ) Assert.assertEquals("cool brand", event.products?.get(0)?.brand) configuration = MockKitConfiguration.createKitConfiguration(JSONObject(COMMERCE_FILTERS_2)) filteredEvent = configuration.filterCommerceEvent(event) - Assert.assertNull(filteredEvent.products?.get(0)?.customAttributes?.get("my custom product attribute")) + Assert.assertNull( + filteredEvent.products + ?.get(0) + ?.customAttributes + ?.get("my custom product attribute"), + ) Assert.assertNull(filteredEvent.products?.get(0)?.brand) } @@ -313,13 +345,16 @@ class KitConfigurationTest { val configuration = MockKitConfiguration.createKitConfiguration(JSONObject(COMMERCE_FILTERS)) val event = - CommerceEvent.Builder(Product.ADD_TO_CART, Product.Builder("name", "sku", 2.0).build()) + CommerceEvent + .Builder(Product.ADD_TO_CART, Product.Builder("name", "sku", 2.0).build()) .build() Assert.assertNotNull(configuration.filterCommerceEvent(event)) - val event2 = CommerceEvent.Builder( - Product.REMOVE_FROM_CART, - Product.Builder("name", "sku", 2.0).build() - ).build() + val event2 = + CommerceEvent + .Builder( + Product.REMOVE_FROM_CART, + Product.Builder("name", "sku", 2.0).build(), + ).build() Assert.assertNull(configuration.filterCommerceEvent(event2)) } @@ -337,16 +372,18 @@ class KitConfigurationTest { halfMatchingAttributes["key1"] = "valWrong" nonMatchingAttributes.put("keyWrong", "valWrong") } - val includeTrueConfiguration = MockKitConfiguration.createKitConfiguration( - JSONObject( - ATTRIBUTE_VALUE_FILTERING_INCLUDE_TRUE + val includeTrueConfiguration = + MockKitConfiguration.createKitConfiguration( + JSONObject( + ATTRIBUTE_VALUE_FILTERING_INCLUDE_TRUE, + ), ) - ) - val includeFalseConfiguration = MockKitConfiguration.createKitConfiguration( - JSONObject( - ATTRIBUTE_VALUE_FILTERING_INCLUDE_FALSE + val includeFalseConfiguration = + MockKitConfiguration.createKitConfiguration( + JSONObject( + ATTRIBUTE_VALUE_FILTERING_INCLUDE_FALSE, + ), ) - ) var result: Boolean = includeTrueConfiguration.shouldIncludeFromAttributeValueFiltering(matchingAttributes) Assert.assertTrue(result) @@ -359,9 +396,10 @@ class KitConfigurationTest { result = includeFalseConfiguration.shouldIncludeFromAttributeValueFiltering(matchingAttributes) Assert.assertFalse(result) - result = includeFalseConfiguration.shouldIncludeFromAttributeValueFiltering( - halfMatchingAttributes - ) + result = + includeFalseConfiguration.shouldIncludeFromAttributeValueFiltering( + halfMatchingAttributes, + ) Assert.assertTrue(result) result = includeFalseConfiguration.shouldIncludeFromAttributeValueFiltering(nonMatchingAttributes) @@ -372,24 +410,28 @@ class KitConfigurationTest { @Throws(Exception::class) fun testUserAttributeFiltering() { val configuration = - MockKitConfiguration.createKitConfiguration(JSONObject(" {\"id\":56, \"as\":{\"secretKey\":\"testappkey\", \"eventList\":\"[\\\"test1\\\",\\\"test2\\\",\\\"test3\\\"]\", \"sendTransactionData\":\"True\", \"eventAttributeList\":null }, \"hs\":{\"ua\":{\"-430909305\":0, \"1510554026\":1, \"341203229\":0, \"96511\":0, \"3373707\":0, \"1193085\":0, \"635848677\":0, \"-564885382\":0, \"1168987\":0, \"102865796\":0, \"3552215\":0, \"3648196\":0, \"-892481550\":0, \"405645589\":0, \"405645588\":0, \"405645591\":0, \"405645590\":0, \"405645592\":0, \"3492908\":0 } }, }")) + MockKitConfiguration.createKitConfiguration( + JSONObject( + " {\"id\":56, \"as\":{\"secretKey\":\"testappkey\", \"eventList\":\"[\\\"test1\\\",\\\"test2\\\",\\\"test3\\\"]\", \"sendTransactionData\":\"True\", \"eventAttributeList\":null }, \"hs\":{\"ua\":{\"-430909305\":0, \"1510554026\":1, \"341203229\":0, \"96511\":0, \"3373707\":0, \"1193085\":0, \"635848677\":0, \"-564885382\":0, \"1168987\":0, \"102865796\":0, \"3552215\":0, \"3648196\":0, \"-892481550\":0, \"405645589\":0, \"405645588\":0, \"405645591\":0, \"405645590\":0, \"405645592\":0, \"3492908\":0 } }, }", + ), + ) Assert.assertFalse( KitConfiguration.shouldForwardAttribute( configuration.userAttributeFilters, - "test key in config as false" - ) + "test key in config as false", + ), ) Assert.assertTrue( KitConfiguration.shouldForwardAttribute( configuration.userAttributeFilters, - "test key in config as true" - ) + "test key in config as true", + ), ) Assert.assertTrue( KitConfiguration.shouldForwardAttribute( configuration.userAttributeFilters, - "test key not in config" - ) + "test key not in config", + ), ) } @@ -397,42 +439,50 @@ class KitConfigurationTest { @Throws(Exception::class) fun testScreenAttributeFiltering() { val configuration = - MockKitConfiguration.createKitConfiguration(JSONObject(" {\"id\":56, \"as\":{\"secretKey\":\"testappkey\", \"eventList\":\"[\\\"test1\\\",\\\"test2\\\",\\\"test3\\\"]\", \"sendTransactionData\":\"True\", \"eventAttributeList\":null }, \"hs\":{\"svea\":{\"1689004688\":0, \"1198002448\":1 } }, }")) - val testAttributes = mapOf( - "screen attribute should not forward" to "testVal", - "screen attribute should forward" to "testVal", - "screen attribute should also forward" to "testVal" - ) - val filterdScreenAttributes = KitConfiguration.filterEventAttributes( - null, - "testScreenView", - configuration.screenAttributeFilters, - testAttributes - ) + MockKitConfiguration.createKitConfiguration( + JSONObject( + " {\"id\":56, \"as\":{\"secretKey\":\"testappkey\", \"eventList\":\"[\\\"test1\\\",\\\"test2\\\",\\\"test3\\\"]\", \"sendTransactionData\":\"True\", \"eventAttributeList\":null }, \"hs\":{\"svea\":{\"1689004688\":0, \"1198002448\":1 } }, }", + ), + ) + val testAttributes = + mapOf( + "screen attribute should not forward" to "testVal", + "screen attribute should forward" to "testVal", + "screen attribute should also forward" to "testVal", + ) + val filterdScreenAttributes = + KitConfiguration.filterEventAttributes( + null, + "testScreenView", + configuration.screenAttributeFilters, + testAttributes, + ) Assert.assertFalse( - filterdScreenAttributes.containsKey("screen attribute should not forward") + filterdScreenAttributes.containsKey("screen attribute should not forward"), ) Assert.assertTrue( - filterdScreenAttributes.containsKey("screen attribute should forward") + filterdScreenAttributes.containsKey("screen attribute should forward"), ) Assert.assertTrue( - filterdScreenAttributes.containsKey("screen attribute should also forward") + filterdScreenAttributes.containsKey("screen attribute should also forward"), ) } @Test @Throws(Exception::class) fun testConsentForwardingRules() { - var configuration = MockKitConfiguration.createKitConfiguration( - JSONObject("{\"id\":56,\"crvf\":{\"i\": true, \"v\":[{\"c\":true, \"h\":123}, {\"c\":false, \"h\":456}]}}") - ) + var configuration = + MockKitConfiguration.createKitConfiguration( + JSONObject("{\"id\":56,\"crvf\":{\"i\": true, \"v\":[{\"c\":true, \"h\":123}, {\"c\":false, \"h\":456}]}}"), + ) Assert.assertEquals(2, configuration.mConsentForwardingRules.size.toLong()) Assert.assertEquals(true, configuration.consentForwardingIncludeMatches) Assert.assertEquals(true, configuration.mConsentForwardingRules[123]) Assert.assertEquals(false, configuration.mConsentForwardingRules[456]) - configuration = configuration.parseConfiguration( - JSONObject("{\"id\":56,\"crvf\":{\"i\": false, \"v\":[{\"c\":false, \"h\":123}, {\"c\":true, \"h\":456}]}}") - ) + configuration = + configuration.parseConfiguration( + JSONObject("{\"id\":56,\"crvf\":{\"i\": false, \"v\":[{\"c\":false, \"h\":123}, {\"c\":true, \"h\":456}]}}"), + ) Assert.assertEquals(2, configuration.mConsentForwardingRules.size.toLong()) Assert.assertEquals(false, configuration.consentForwardingIncludeMatches) Assert.assertEquals(false, configuration.mConsentForwardingRules[123]) @@ -454,9 +504,10 @@ class KitConfigurationTest { ruleArray.put(rule1) rule1.put("h", KitUtils.hashForFiltering("1" + "foo purpose")) rule1.put("c", false) - val configuration = MockKitConfiguration.createKitConfiguration( - JSONObject("{\"id\":56,\"crvf\":{\"i\": true, \"v\":[{\"c\":true, \"h\":123}, {\"c\":false, \"h\":456}]}}") - ) + val configuration = + MockKitConfiguration.createKitConfiguration( + JSONObject("{\"id\":56,\"crvf\":{\"i\": true, \"v\":[{\"c\":true, \"h\":123}, {\"c\":false, \"h\":456}]}}"), + ) Assert.assertFalse(configuration.isConsentStateFilterMatch(ConsentState.builder().build())) } @@ -484,81 +535,71 @@ class KitConfigurationTest { val configuration = MockKitConfiguration.createKitConfiguration(jsonConfiguration) Assert.assertTrue( configuration.isConsentStateFilterMatch( - ConsentState.builder() + ConsentState + .builder() .addGDPRConsentState( "foo purpose 1", - GDPRConsent.builder(false).build() - ) - .addGDPRConsentState( + GDPRConsent.builder(false).build(), + ).addGDPRConsentState( "foo purpose 2", - GDPRConsent.builder(true).build() - ) - .addGDPRConsentState( + GDPRConsent.builder(true).build(), + ).addGDPRConsentState( "foo purpose 3", - GDPRConsent.builder(true).build() - ) - .build() - ) + GDPRConsent.builder(true).build(), + ).build(), + ), ) Assert.assertTrue( configuration.isConsentStateFilterMatch( - ConsentState.builder() + ConsentState + .builder() .addGDPRConsentState( "foo purpose 1", - GDPRConsent.builder(true).build() - ) - .addGDPRConsentState( + GDPRConsent.builder(true).build(), + ).addGDPRConsentState( "foo purpose 2", - GDPRConsent.builder(false).build() - ) - .addGDPRConsentState( + GDPRConsent.builder(false).build(), + ).addGDPRConsentState( "foo purpose 3", - GDPRConsent.builder(true).build() - ) - .build() - ) + GDPRConsent.builder(true).build(), + ).build(), + ), ) Assert.assertTrue( configuration.isConsentStateFilterMatch( - ConsentState.builder() + ConsentState + .builder() .addGDPRConsentState( "foo purpose 1", - GDPRConsent.builder(true).build() - ) - .addGDPRConsentState( + GDPRConsent.builder(true).build(), + ).addGDPRConsentState( "foo purpose 2", - GDPRConsent.builder(true).build() - ) - .addGDPRConsentState( + GDPRConsent.builder(true).build(), + ).addGDPRConsentState( "foo purpose 3", - GDPRConsent.builder(false).build() - ) - .setCCPAConsentState( - CCPAConsent.builder(false).build() - ) - .build() - ) + GDPRConsent.builder(false).build(), + ).setCCPAConsentState( + CCPAConsent.builder(false).build(), + ).build(), + ), ) Assert.assertTrue( configuration.isConsentStateFilterMatch( - ConsentState.builder() + ConsentState + .builder() .addGDPRConsentState( "foo purpose 1", - GDPRConsent.builder(false).build() - ) - .addGDPRConsentState( + GDPRConsent.builder(false).build(), + ).addGDPRConsentState( "foo purpose 2", - GDPRConsent.builder(false).build() - ) - .addGDPRConsentState( + GDPRConsent.builder(false).build(), + ).addGDPRConsentState( "foo purpose 3", - GDPRConsent.builder(false).build() - ) - .setCCPAConsentState( - CCPAConsent.builder(true).build() - ) - .build() - ) + GDPRConsent.builder(false).build(), + ).setCCPAConsentState( + CCPAConsent.builder(true).build(), + ).build(), + ), ) } @@ -578,45 +619,45 @@ class KitConfigurationTest { val configuration = MockKitConfiguration.createKitConfiguration(jsonConfiguration) Assert.assertTrue( configuration.isConsentStateFilterMatch( - ConsentState.builder() + ConsentState + .builder() .addGDPRConsentState( "foo purpose", - GDPRConsent.builder(false).build() - ) - .build() - ) + GDPRConsent.builder(false).build(), + ).build(), + ), ) Assert.assertFalse( configuration.isConsentStateFilterMatch( - ConsentState.builder() + ConsentState + .builder() .addGDPRConsentState( "foo purpose", - GDPRConsent.builder(true).build() - ) - .build() - ) + GDPRConsent.builder(true).build(), + ).build(), + ), ) ruleArray.getJSONObject(0).put("c", true) configuration.parseConfiguration(jsonConfiguration) Assert.assertTrue( configuration.isConsentStateFilterMatch( - ConsentState.builder() + ConsentState + .builder() .addGDPRConsentState( "foo purpose", - GDPRConsent.builder(true).build() - ) - .build() - ) + GDPRConsent.builder(true).build(), + ).build(), + ), ) Assert.assertFalse( configuration.isConsentStateFilterMatch( - ConsentState.builder() + ConsentState + .builder() .addGDPRConsentState( "foo purpose", - GDPRConsent.builder(false).build() - ) - .build() - ) + GDPRConsent.builder(false).build(), + ).build(), + ), ) } @@ -636,67 +677,72 @@ class KitConfigurationTest { val configuration = MockKitConfiguration.createKitConfiguration(jsonConfiguration) Assert.assertTrue( configuration.isConsentStateFilterMatch( - ConsentState.builder() + ConsentState + .builder() .setCCPAConsentState( - CCPAConsent.builder(false) - .build() - ) - .build() - ) + CCPAConsent + .builder(false) + .build(), + ).build(), + ), ) Assert.assertFalse( configuration.isConsentStateFilterMatch( - ConsentState.builder() + ConsentState + .builder() .setCCPAConsentState( - CCPAConsent.builder(true) - .build() - ) - .build() - ) + CCPAConsent + .builder(true) + .build(), + ).build(), + ), ) ruleArray.getJSONObject(0).put("c", true) configuration.parseConfiguration(jsonConfiguration) Assert.assertTrue( configuration.isConsentStateFilterMatch( - ConsentState.builder() + ConsentState + .builder() .setCCPAConsentState( - CCPAConsent.builder(true) - .build() - ) - .build() - ) + CCPAConsent + .builder(true) + .build(), + ).build(), + ), ) Assert.assertFalse( configuration.isConsentStateFilterMatch( - ConsentState.builder() + ConsentState + .builder() .setCCPAConsentState( - CCPAConsent.builder(false) - .build() - ) - .build() - ) + CCPAConsent + .builder(false) + .build(), + ).build(), + ), ) } @Test fun testConvertToSparseArray() { val kitConfiguration = MockKitConfiguration() - val jsonData = """ - { - "7456529": 0, - "10887805": 0, - "13992010": 0, - "15360852": 0, - "17455322": 0, - "18683141": 0, - "23029959": 0, - "41851400": 0, - "47355425": 0, - "54925556": 0, - "56409892": 0, - "66701264": 0 - } - """.trimIndent() + val jsonData = + """ + { + "7456529": 0, + "10887805": 0, + "13992010": 0, + "15360852": 0, + "17455322": 0, + "18683141": 0, + "23029959": 0, + "41851400": 0, + "47355425": 0, + "54925556": 0, + "56409892": 0, + "66701264": 0 + } + """.trimIndent() val jsonConfiguration = JSONObject(jsonData) val method: Method = MockKitConfiguration::class.java.getDeclaredMethod("convertToSparseArray", JSONObject::class.java) method.isAccessible = true @@ -733,22 +779,23 @@ class KitConfigurationTest { @Test fun testConvertToSparseArray_When_JSON_Data_IS_INVALID() { val kitConfiguration = MockKitConfiguration() - val jsn = """ - { - "7456529": 0, - "10887805": 0, - "-36!037962": 0, - "15360852": 0, - "17455322": 0, - "18683141": 0, - "23029959": 0, - "41851400": 0, - "47355425": 0, - "54925556": 0, - "56409892": 0, - "66701264": 0 - } - """.trimIndent() + val jsn = + """ + { + "7456529": 0, + "10887805": 0, + "-36!037962": 0, + "15360852": 0, + "17455322": 0, + "18683141": 0, + "23029959": 0, + "41851400": 0, + "47355425": 0, + "54925556": 0, + "56409892": 0, + "66701264": 0 + } + """.trimIndent() val jsonConfiguration = JSONObject(jsn) val method: Method = MockKitConfiguration::class.java.getDeclaredMethod("convertToSparseArray", JSONObject::class.java) method.isAccessible = true @@ -760,18 +807,20 @@ class KitConfigurationTest { @Test fun testConvertToSparseArray_When_JSON_OBJECT_IS_INVALID() { val kitConfiguration = MockKitConfiguration() - val jsn = """ - { - "name": "John", - "age": "30", - "18683141": 0 - } - """.trimIndent() + val jsn = + """ + { + "name": "John", + "age": "30", + "18683141": 0 + } + """.trimIndent() val jsonConfiguration = JSONObject(jsn) - val method: Method = MockKitConfiguration::class.java.getDeclaredMethod( - "convertToSparseArray", - JSONObject::class.java - ) + val method: Method = + MockKitConfiguration::class.java.getDeclaredMethod( + "convertToSparseArray", + JSONObject::class.java, + ) method.isAccessible = true val result = method.invoke(kitConfiguration, jsonConfiguration) as SparseBooleanArray @@ -800,27 +849,26 @@ class KitConfigurationTest { @Test @Throws(JSONException::class) fun testAttributeToUser() { - var kitConfig = JSONObject() - .put("id", 10) - .put( - "hs", - JSONObject() - .put( - "eaa", - JSONObject() - .put("-1107245616", "add-item") - ) - .put( - "ear", - JSONObject() - .put("238178128", "remove-item") - ) - .put( - "eas", - JSONObject() - .put("1784066270", "single-item") - ) - ) + var kitConfig = + JSONObject() + .put("id", 10) + .put( + "hs", + JSONObject() + .put( + "eaa", + JSONObject() + .put("-1107245616", "add-item"), + ).put( + "ear", + JSONObject() + .put("238178128", "remove-item"), + ).put( + "eas", + JSONObject() + .put("1784066270", "single-item"), + ), + ) var kitConfiguration = MockKitConfiguration.createKitConfiguration(kitConfig) val addMap = kitConfiguration.eventAttributesAddToUser Assert.assertEquals(1, addMap.size.toLong()) @@ -834,9 +882,10 @@ class KitConfigurationTest { Assert.assertEquals(1, singleMap.size.toLong()) Assert.assertTrue(singleMap.containsKey(1784066270)) Assert.assertEquals("single-item", singleMap[1784066270]) - kitConfig = JSONObject() - .put("id", 10) - .put("hs", JSONObject()) + kitConfig = + JSONObject() + .put("id", 10) + .put("hs", JSONObject()) kitConfiguration = MockKitConfiguration.createKitConfiguration(kitConfig) Assert.assertEquals(0, kitConfiguration.eventAttributesAddToUser.size.toLong()) Assert.assertEquals(0, kitConfiguration.eventAttributesRemoveFromUser.size.toLong()) diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitIntegrationTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitIntegrationTest.kt index 6e80af26c..ba8ee52d3 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitIntegrationTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitIntegrationTest.kt @@ -17,22 +17,17 @@ class KitIntegrationTest { @Throws(Exception::class) fun testGetAllUserAttributesWithoutLists() { MParticle.setInstance(MockMParticle()) - val integration: KitIntegration = object : KitIntegration() { - override fun getName(): String? { - return null - } + val integration: KitIntegration = + object : KitIntegration() { + override fun getName(): String? = null - override fun onKitCreate( - settings: Map, - context: Context - ): List? { - return null - } + override fun onKitCreate( + settings: Map, + context: Context, + ): List? = null - override fun setOptOut(optedOut: Boolean): List? { - return null + override fun setOptOut(optedOut: Boolean): List? = null } - } integration.configuration = Mockito.mock(KitConfiguration::class.java) val attributes: MutableMap = HashMap() attributes["key 1"] = "value 1" @@ -40,20 +35,26 @@ class KitIntegrationTest { list.add("value 2") list.add("value 3") attributes["key 2"] = list - Mockito.`when`( - MParticle.getInstance()!!.Identity().currentUser!!.userAttributes - ).thenReturn(attributes) + Mockito + .`when`( + MParticle + .getInstance()!! + .Identity() + .currentUser!! + .userAttributes, + ).thenReturn(attributes) val filteredAttributes = integration.allUserAttributes Assert.assertEquals("value 1", filteredAttributes["key 1"]) Assert.assertEquals("value 2,value 3", filteredAttributes["key 2"]) } internal inner class MockSparseBooleanArray : SparseBooleanArray() { - override fun get(key: Int): Boolean { - return get(key, false) - } + override fun get(key: Int): Boolean = get(key, false) - override fun get(key: Int, valueIfKeyNotFound: Boolean): Boolean { + override fun get( + key: Int, + valueIfKeyNotFound: Boolean, + ): Boolean { print("SparseArray getting: $key") return if (map.containsKey(key)) { map[key]!! @@ -63,7 +64,11 @@ class KitIntegrationTest { } var map: MutableMap = HashMap() - override fun put(key: Int, value: Boolean) { + + override fun put( + key: Int, + value: Boolean, + ) { map[key] = value } @@ -71,38 +76,30 @@ class KitIntegrationTest { map.clear() } - override fun size(): Int { - return map.size - } + override fun size(): Int = map.size - override fun toString(): String { - return map.toString() - } + override fun toString(): String = map.toString() } @Test @Throws(Exception::class) fun testGetAllUserAttributesWithoutListsWithFilters() { MParticle.setInstance(MockMParticle()) - val integration: KitIntegration = object : KitIntegration() { - override fun getName(): String? { - return null - } + val integration: KitIntegration = + object : KitIntegration() { + override fun getName(): String? = null - override fun onKitCreate( - settings: Map, - context: Context - ): List? { - return null - } + override fun onKitCreate( + settings: Map, + context: Context, + ): List? = null - override fun setOptOut(optedOut: Boolean): List? { - return null + override fun setOptOut(optedOut: Boolean): List? = null } - } - val configuration = Mockito.mock( - KitConfiguration::class.java - ) + val configuration = + Mockito.mock( + KitConfiguration::class.java, + ) val mockArray = MockSparseBooleanArray() mockArray.put(MPUtility.mpHash("key 4"), false) mockArray.put(MPUtility.mpHash("key 3"), false) @@ -116,9 +113,14 @@ class KitIntegrationTest { list.add("value 3") attributes["key 2"] = list attributes["key 3"] = list - Mockito.`when`( - MParticle.getInstance()!!.Identity().currentUser!!.userAttributes - ).thenReturn(attributes) + Mockito + .`when`( + MParticle + .getInstance()!! + .Identity() + .currentUser!! + .userAttributes, + ).thenReturn(attributes) val filteredAttributes = integration.allUserAttributes Assert.assertEquals("value 1", filteredAttributes["key 1"]) Assert.assertEquals("value 2,value 3", filteredAttributes["key 2"]) @@ -138,9 +140,14 @@ class KitIntegrationTest { list.add("value 2") list.add("value 3") attributes["key 2"] = list - Mockito.`when`( - MParticle.getInstance()!!.Identity().currentUser!!.userAttributes - ).thenReturn(attributes) + Mockito + .`when`( + MParticle + .getInstance()!! + .Identity() + .currentUser!! + .userAttributes, + ).thenReturn(attributes) val filteredAttributes = integration.allUserAttributes Assert.assertEquals("value 1", filteredAttributes["key 1"]) Assert.assertEquals(list, filteredAttributes["key 2"]) @@ -151,9 +158,10 @@ class KitIntegrationTest { fun testGetAllUserAttributesWithListsAndFilters() { MParticle.setInstance(MockMParticle()) val integration: KitIntegration = AttributeListenerIntegration() - val configuration = Mockito.mock( - KitConfiguration::class.java - ) + val configuration = + Mockito.mock( + KitConfiguration::class.java, + ) val mockArray = MockSparseBooleanArray() mockArray.put(MPUtility.mpHash("key 4"), false) mockArray.put(MPUtility.mpHash("key 3"), false) @@ -167,9 +175,14 @@ class KitIntegrationTest { list.add("value 3") attributes["key 2"] = list attributes["key 3"] = list - Mockito.`when`( - MParticle.getInstance()!!.Identity().currentUser!!.userAttributes - ).thenReturn(attributes) + Mockito + .`when`( + MParticle + .getInstance()!! + .Identity() + .currentUser!! + .userAttributes, + ).thenReturn(attributes) val filteredAttributes = integration.allUserAttributes Assert.assertEquals("value 1", filteredAttributes["key 1"]) Assert.assertEquals(list, filteredAttributes["key 2"]) @@ -177,39 +190,45 @@ class KitIntegrationTest { Assert.assertNull(filteredAttributes["key 4"]) } - private inner class AttributeListenerIntegration : KitIntegration(), AttributeListener { - override fun setUserAttribute(attributeKey: String, attributeValue: String) {} - override fun setUserAttributeList(attributeKey: String, attributeValueList: List) {} - override fun supportsAttributeLists(): Boolean { - return true - } + private inner class AttributeListenerIntegration : + KitIntegration(), + AttributeListener { + override fun setUserAttribute( + attributeKey: String, + attributeValue: String, + ) {} + + override fun setUserAttributeList( + attributeKey: String, + attributeValueList: List, + ) {} + + override fun supportsAttributeLists(): Boolean = true override fun setAllUserAttributes( userAttributes: Map, - userAttributeLists: Map> + userAttributeLists: Map>, ) { } override fun removeUserAttribute(key: String) {} - override fun setUserIdentity(identityType: IdentityType, identity: String) {} + + override fun setUserIdentity( + identityType: IdentityType, + identity: String, + ) {} + override fun removeUserIdentity(identityType: IdentityType) {} - override fun logout(): List? { - return null - } - override fun getName(): String? { - return null - } + override fun logout(): List? = null + + override fun getName(): String? = null override fun onKitCreate( settings: Map, - context: Context - ): List? { - return null - } + context: Context, + ): List? = null - override fun setOptOut(optedOut: Boolean): List? { - return null - } + override fun setOptOut(optedOut: Boolean): List? = null } } diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerImplTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerImplTest.kt index 8718607f4..413a09a98 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerImplTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerImplTest.kt @@ -82,16 +82,17 @@ class KitManagerImplTest { fun testSetKitFactory() { val manager: KitManagerImpl = MockKitManagerImpl() Assert.assertNotNull(manager.mKitIntegrationFactory) - val factory = mock( - KitIntegrationFactory::class.java - ) + val factory = + mock( + KitIntegrationFactory::class.java, + ) manager.setKitFactory(factory) Assert.assertEquals(factory, manager.mKitIntegrationFactory) } private fun createKitsMap( ids: List, - type: Class<*> = KitIntegration::class.java + type: Class<*> = KitIntegration::class.java, ): HashMap> { val map = hashMapOf>() ids.forEach { map.put(it, type) } @@ -109,9 +110,10 @@ class KitManagerImplTest { val kitConfiguration = JSONArray() kitConfiguration.put(JSONObject("{\"id\":1}")) kitConfiguration.put(JSONObject("{\"id\":2}")) - val factory = mock( - KitIntegrationFactory::class.java - ) + val factory = + mock( + KitIntegrationFactory::class.java, + ) manager.setKitFactory(factory) `when`(factory.getSupportedKits()).thenReturn(createKitsMap(listOf(1, 2)).keys) @@ -119,20 +121,25 @@ class KitManagerImplTest { val mockKit = mock(KitIntegration::class.java) `when`(mockKit.configuration).thenReturn( mock( - KitConfiguration::class.java - ) + KitConfiguration::class.java, + ), ) `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(mockKit) manager.updateKits(kitConfiguration) assertEquals(2, manager.providers.size) - assertEquals(mockKit, manager.providers.values.iterator().next()) + assertEquals( + mockKit, + manager.providers.values + .iterator() + .next(), + ) } @Test @@ -141,33 +148,44 @@ class KitManagerImplTest { val mockUser = mock(MParticleUser::class.java) `when`(mockIdentity!!.currentUser).thenReturn(mockUser) val manager: KitManagerImpl = MockKitManagerImpl() - val state = ConsentState.builder() - .addGDPRConsentState("Blah", GDPRConsent.builder(true).build()) - .build() + val state = + ConsentState + .builder() + .addGDPRConsentState("Blah", GDPRConsent.builder(true).build()) + .build() `when`(mockUser.consentState).thenReturn(state) val kitConfiguration = JSONArray() - kitConfiguration.put(JSONObject("{ \"id\":1, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":false, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }")) - kitConfiguration.put(JSONObject("{ \"id\":2, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":false, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }")) - kitConfiguration.put(JSONObject("{ \"id\":3, \"as\":{ \"foo\":\"bar\" } }")) - val factory = mock( - KitIntegrationFactory::class.java + kitConfiguration.put( + JSONObject( + "{ \"id\":1, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":false, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }", + ), + ) + kitConfiguration.put( + JSONObject( + "{ \"id\":2, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":false, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }", + ), ) + kitConfiguration.put(JSONObject("{ \"id\":3, \"as\":{ \"foo\":\"bar\" } }")) + val factory = + mock( + KitIntegrationFactory::class.java, + ) manager.setKitFactory(factory) `when`(factory.getSupportedKits()).thenReturn(createKitsMap(listOf(1, 2, 3)).keys) `when`(factory.isSupported(Mockito.anyInt())).thenReturn(true) val mockKit = mock(KitIntegration::class.java) `when`(mockKit.configuration).thenReturn( mock( - KitConfiguration::class.java - ) + KitConfiguration::class.java, + ), ) `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(mockKit) manager.updateKits(kitConfiguration) Assert.assertEquals(1, manager.providers.size) @@ -179,32 +197,39 @@ class KitManagerImplTest { val mockUser = mock(MParticleUser::class.java) `when`(mockIdentity!!.currentUser).thenReturn(mockUser) val manager: KitManagerImpl = MockKitManagerImpl() - val state = ConsentState.builder() - .addGDPRConsentState("Blah", GDPRConsent.builder(true).build()) - .build() + val state = + ConsentState + .builder() + .addGDPRConsentState("Blah", GDPRConsent.builder(true).build()) + .build() `when`(mockUser.consentState).thenReturn(state) val kitConfiguration = JSONArray() - kitConfiguration.put(JSONObject("{ \"id\":1, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":true, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }")) - kitConfiguration.put(JSONObject("{ \"id\":2, \"as\":{ \"foo\":\"bar\" } }")) - val factory = mock( - KitIntegrationFactory::class.java + kitConfiguration.put( + JSONObject( + "{ \"id\":1, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":true, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }", + ), ) + kitConfiguration.put(JSONObject("{ \"id\":2, \"as\":{ \"foo\":\"bar\" } }")) + val factory = + mock( + KitIntegrationFactory::class.java, + ) manager.setKitFactory(factory) `when`(factory.getSupportedKits()).thenReturn(createKitsMap(listOf(1, 2)).keys) `when`(factory.isSupported(Mockito.anyInt())).thenReturn(true) val mockKit = mock(KitIntegration::class.java) `when`(mockKit.configuration).thenReturn( mock( - KitConfiguration::class.java - ) + KitConfiguration::class.java, + ), ) `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(mockKit) manager.updateKits(kitConfiguration) assertEquals(2, manager.providers.size) @@ -216,32 +241,39 @@ class KitManagerImplTest { val mockUser = mock(MParticleUser::class.java) `when`(mockIdentity!!.currentUser).thenReturn(mockUser) val manager: KitManagerImpl = MockKitManagerImpl() - val state = ConsentState.builder() - .addGDPRConsentState("Blah", GDPRConsent.builder(true).build()) - .build() + val state = + ConsentState + .builder() + .addGDPRConsentState("Blah", GDPRConsent.builder(true).build()) + .build() `when`(mockUser.consentState).thenReturn(state) val kitConfiguration = JSONArray() - kitConfiguration.put(JSONObject("{ \"id\":1, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":true, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }")) - kitConfiguration.put(JSONObject("{ \"id\":2, \"as\":{ \"foo\":\"bar\" } }")) - val factory = mock( - KitIntegrationFactory::class.java + kitConfiguration.put( + JSONObject( + "{ \"id\":1, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":true, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }", + ), ) + kitConfiguration.put(JSONObject("{ \"id\":2, \"as\":{ \"foo\":\"bar\" } }")) + val factory = + mock( + KitIntegrationFactory::class.java, + ) manager.setKitFactory(factory) `when`(factory.getSupportedKits()).thenReturn(createKitsMap(listOf(1, 2)).keys) `when`(factory.isSupported(Mockito.anyInt())).thenReturn(true) val mockKit = mock(KitIntegration::class.java) `when`(mockKit.configuration).thenReturn( mock( - KitConfiguration::class.java - ) + KitConfiguration::class.java, + ), ) `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(mockKit) manager.updateKits(kitConfiguration) assertEquals(2, manager.providers.size) @@ -257,33 +289,40 @@ class KitManagerImplTest { `when`(mockIdentity!!.currentUser).thenReturn(mockUser) `when`(mockUser.isLoggedIn).thenReturn(true) val manager: KitManagerImpl = MockKitManagerImpl() - val state = ConsentState.builder() - .addGDPRConsentState("Blah", GDPRConsent.builder(true).build()) - .build() + val state = + ConsentState + .builder() + .addGDPRConsentState("Blah", GDPRConsent.builder(true).build()) + .build() `when`(mockUser.consentState).thenReturn(state) val kitConfiguration = JSONArray() - kitConfiguration.put(JSONObject("{ \"id\":1, \"eau\": true, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":true, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }")) + kitConfiguration.put( + JSONObject( + "{ \"id\":1, \"eau\": true, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":true, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }", + ), + ) kitConfiguration.put(JSONObject("{ \"id\":2, \"eau\": true, \"as\":{ \"foo\":\"bar\" } }")) kitConfiguration.put(JSONObject("{ \"id\":3, \"eau\": false, \"as\":{ \"foo\":\"bar\" } }")) - val factory = mock( - KitIntegrationFactory::class.java - ) + val factory = + mock( + KitIntegrationFactory::class.java, + ) manager.setKitFactory(factory) `when`(factory.getSupportedKits()).thenReturn(createKitsMap(listOf(1, 2, 3)).keys) `when`(factory.isSupported(Mockito.anyInt())).thenReturn(true) val mockKit = mock(KitIntegration::class.java) `when`(mockKit.configuration).thenReturn( mock( - KitConfiguration::class.java - ) + KitConfiguration::class.java, + ), ) `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(mockKit) manager.updateKits(kitConfiguration) assertEquals(3, manager.providers.size) @@ -296,33 +335,40 @@ class KitManagerImplTest { `when`(mockIdentity!!.currentUser).thenReturn(mockUser) `when`(mockUser.isLoggedIn).thenReturn(false) val manager: KitManagerImpl = MockKitManagerImpl() - val state = ConsentState.builder() - .addGDPRConsentState("Blah", GDPRConsent.builder(true).build()) - .build() + val state = + ConsentState + .builder() + .addGDPRConsentState("Blah", GDPRConsent.builder(true).build()) + .build() `when`(mockUser.consentState).thenReturn(state) val kitConfiguration = JSONArray() - kitConfiguration.put(JSONObject("{ \"id\":1, \"eau\": true, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":true, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }")) + kitConfiguration.put( + JSONObject( + "{ \"id\":1, \"eau\": true, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":true, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }", + ), + ) kitConfiguration.put(JSONObject("{ \"id\":2, \"eau\": false, \"as\":{ \"foo\":\"bar\" } }")) kitConfiguration.put(JSONObject("{ \"id\":3, \"eau\": true, \"as\":{ \"foo\":\"bar\" } }")) - val factory = mock( - KitIntegrationFactory::class.java - ) + val factory = + mock( + KitIntegrationFactory::class.java, + ) manager.setKitFactory(factory) `when`(factory.getSupportedKits()).thenReturn(createKitsMap(listOf(1, 2, 3)).keys) `when`(factory.isSupported(Mockito.anyInt())).thenReturn(true) val mockKit = mock(KitIntegration::class.java) `when`(mockKit.configuration).thenReturn( mock( - KitConfiguration::class.java - ) + KitConfiguration::class.java, + ), ) `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(mockKit) manager.updateKits(kitConfiguration) assertEquals(1, manager.providers.size) @@ -338,33 +384,40 @@ class KitManagerImplTest { `when`(mockIdentity!!.currentUser).thenReturn(mockUser) `when`(mockUser.isLoggedIn).thenReturn(false) val manager: KitManagerImpl = MockKitManagerImpl() - val state = ConsentState.builder() - .addGDPRConsentState("Blah", GDPRConsent.builder(true).build()) - .build() + val state = + ConsentState + .builder() + .addGDPRConsentState("Blah", GDPRConsent.builder(true).build()) + .build() `when`(mockUser.consentState).thenReturn(state) val kitConfiguration = JSONArray() - kitConfiguration.put(JSONObject("{ \"id\":1, \"eau\": true, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":true, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }")) + kitConfiguration.put( + JSONObject( + "{ \"id\":1, \"eau\": true, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":true, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }", + ), + ) kitConfiguration.put(JSONObject("{ \"id\":2, \"eau\": true, \"as\":{ \"foo\":\"bar\" } }")) kitConfiguration.put(JSONObject("{ \"id\":3, \"eau\": true, \"as\":{ \"foo\":\"bar\" } }")) - val factory = mock( - KitIntegrationFactory::class.java - ) + val factory = + mock( + KitIntegrationFactory::class.java, + ) manager.setKitFactory(factory) `when`(factory.getSupportedKits()).thenReturn(createKitsMap(listOf(1, 2, 3)).keys) `when`(factory.isSupported(Mockito.anyInt())).thenReturn(true) val mockKit = mock(KitIntegration::class.java) `when`(mockKit.configuration).thenReturn( mock( - KitConfiguration::class.java - ) + KitConfiguration::class.java, + ), ) `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(mockKit) manager.updateKits(kitConfiguration) Assert.assertEquals(0, manager.providers.size) @@ -380,37 +433,45 @@ class KitManagerImplTest { val mockUser = mock(MParticleUser::class.java) `when`(mockIdentity!!.currentUser).thenReturn(mockUser) `when`(mockUser.isLoggedIn).thenReturn(true) - val mockCoreCallbacks = mock( - CoreCallbacks::class.java - ) + val mockCoreCallbacks = + mock( + CoreCallbacks::class.java, + ) val manager: KitManagerImpl = MockKitManagerImpl() - val state = ConsentState.builder() - .addGDPRConsentState("Blah", GDPRConsent.builder(true).build()) - .build() + val state = + ConsentState + .builder() + .addGDPRConsentState("Blah", GDPRConsent.builder(true).build()) + .build() `when`(mockUser.consentState).thenReturn(state) val kitConfiguration = JSONArray() - kitConfiguration.put(JSONObject("{ \"id\":1, \"eau\": true, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":true, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }")) + kitConfiguration.put( + JSONObject( + "{ \"id\":1, \"eau\": true, \"as\":{ \"foo\":\"bar\" }, \"crvf\":{ \"i\":true, \"v\":[ { \"c\":true, \"h\":48278946 }, { \"c\":true, \"h\":1556641 } ] } }", + ), + ) kitConfiguration.put(JSONObject("{ \"id\":2, \"eau\": true, \"as\":{ \"foo\":\"bar\" } }")) kitConfiguration.put(JSONObject("{ \"id\":3, \"eau\": true, \"as\":{ \"foo\":\"bar\" } }")) - val factory = mock( - KitIntegrationFactory::class.java - ) + val factory = + mock( + KitIntegrationFactory::class.java, + ) manager.setKitFactory(factory) `when`(factory.getSupportedKits()).thenReturn(createKitsMap(listOf(1, 2, 3)).keys) `when`(factory.isSupported(Mockito.anyInt())).thenReturn(true) val mockKit = mock(KitIntegration::class.java) `when`(mockKit.configuration).thenReturn( mock( - KitConfiguration::class.java - ) + KitConfiguration::class.java, + ), ) `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(mockKit) manager.updateKits(kitConfiguration) Assert.assertEquals(3, manager.providers.size) @@ -425,14 +486,16 @@ class KitManagerImplTest { fun testOnUserAttributesReceived() { MParticle.setInstance(MockMParticle()) val manager: KitManagerImpl = MockKitManagerImpl() - val integration = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(AttributeListener::class.java) - ) - val integration2 = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(AttributeListener::class.java) - ) + val integration = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(AttributeListener::class.java), + ) + val integration2 = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(AttributeListener::class.java), + ) `when`((integration as AttributeListener).supportsAttributeLists()).thenReturn(true) `when`((integration2 as AttributeListener).supportsAttributeLists()) .thenReturn(false) @@ -467,14 +530,16 @@ class KitManagerImplTest { @Throws(Exception::class) fun testSetUserAttributeList() { val manager: KitManagerImpl = MockKitManagerImpl() - val integration = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(AttributeListener::class.java) - ) - val integration2 = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(AttributeListener::class.java) - ) + val integration = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(AttributeListener::class.java), + ) + val integration2 = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(AttributeListener::class.java), + ) `when`((integration as AttributeListener).supportsAttributeLists()).thenReturn(true) `when`((integration2 as AttributeListener).supportsAttributeLists()) .thenReturn(false) @@ -499,14 +564,16 @@ class KitManagerImplTest { @Throws(JSONException::class) fun testLogEventCalledOne() { val manager = KitManagerEventCounter() - val integration = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(AttributeListener::class.java) - ) - val integration2 = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(AttributeListener::class.java) - ) + val integration = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(AttributeListener::class.java), + ) + val integration2 = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(AttributeListener::class.java), + ) `when`((integration as AttributeListener).supportsAttributeLists()).thenReturn(true) `when`((integration2 as AttributeListener).supportsAttributeLists()) .thenReturn(false) @@ -524,7 +591,8 @@ class KitManagerImplTest { manager.logBaseEventCalled = 0 manager.logMPEventCalled = 0 val commerceEvent = - CommerceEvent.Builder(Product.CHECKOUT, Product.Builder("name", "sku", 100.0).build()) + CommerceEvent + .Builder(Product.CHECKOUT, Product.Builder("name", "sku", 100.0).build()) .build() manager.logEvent(commerceEvent) assertEquals(1, manager.logBaseEventCalled) @@ -540,8 +608,11 @@ class KitManagerImplTest { val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) val factory = mock(KitIntegrationFactory::class.java) manager.setKitFactory(factory) @@ -553,10 +624,10 @@ class KitManagerImplTest { `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(sideloadedKit) manager.configureKits(mutableListOf(mockedKitConfig)) Assert.assertEquals(1, manager.providers.size) @@ -571,8 +642,11 @@ class KitManagerImplTest { val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) val factory = mock(KitIntegrationFactory::class.java) `when`(factory.getSupportedKits()) @@ -586,10 +660,10 @@ class KitManagerImplTest { `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(sideloadedKit) manager.configureKits(mutableListOf(mockedKitConfig)) Assert.assertEquals(1, manager.providers.size) @@ -605,16 +679,18 @@ class KitManagerImplTest { val manager: KitManagerImpl = MockKitManagerImpl() val idOne = 6000000 val idTwo = 6000001 - val kitConfiguration = JSONArray() - .apply { - put(JSONObject().apply { put("id", 1) }) - put(JSONObject().apply { put("id", idOne) }) - put(JSONObject().apply { put("id", idTwo) }) - } + val kitConfiguration = + JSONArray() + .apply { + put(JSONObject().apply { put("id", 1) }) + put(JSONObject().apply { put("id", idOne) }) + put(JSONObject().apply { put("id", idTwo) }) + } `when`(manager.mCoreCallbacks.getLatestKitConfiguration()).thenReturn(kitConfiguration) - val factory = mock( - KitIntegrationFactory::class.java - ) + val factory = + mock( + KitIntegrationFactory::class.java, + ) manager.setKitFactory(factory) `when`(factory.getSupportedKits()) .thenReturn(createKitsMap(listOf(1, idOne, idTwo), MPSideloadedKit::class.java).keys) @@ -622,15 +698,15 @@ class KitManagerImplTest { val sideloadedKit = mock(KitIntegration::class.java) `when`(sideloadedKit.isDisabled).thenReturn(false) `when`(sideloadedKit.configuration).thenReturn( - mock(KitConfiguration::class.java) + mock(KitConfiguration::class.java), ) `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(sideloadedKit) manager.updateKits(kitConfiguration) Assert.assertEquals(3, manager.providers.size) @@ -641,15 +717,16 @@ class KitManagerImplTest { @Test fun shouldFilterKitsFromKnownIntegrations() { val options = MParticleOptions.builder(MockContext()).build() - val filteredKitOptions = MParticleOptions.builder(MockContext()) - .disabledKits( - Arrays.asList( - MParticle.ServiceProviders.ADJUST, - MParticle.ServiceProviders.APPBOY, - MParticle.ServiceProviders.CLEVERTAP - ) - ) - .build() + val filteredKitOptions = + MParticleOptions + .builder(MockContext()) + .disabledKits( + Arrays.asList( + MParticle.ServiceProviders.ADJUST, + MParticle.ServiceProviders.APPBOY, + MParticle.ServiceProviders.CLEVERTAP, + ), + ).build() val filteredKitIntegrationFactory = KitIntegrationFactory(filteredKitOptions) val kitIntegrationFactory = KitIntegrationFactory(options) @@ -676,9 +753,11 @@ class KitManagerImplTest { @Test fun shouldNotFilterKitsFromKnownIntegrationsWhenFilterIsEmpty() { val options = MParticleOptions.builder(MockContext()).build() - val filteredKitOptions = MParticleOptions.builder(MockContext()) - .disabledKits(emptyList()) - .build() + val filteredKitOptions = + MParticleOptions + .builder(MockContext()) + .disabledKits(emptyList()) + .build() val filteredKitIntegrationFactory = KitIntegrationFactory(filteredKitOptions) val kitIntegrationFactory = KitIntegrationFactory(options) @@ -696,9 +775,11 @@ class KitManagerImplTest { @Test fun shouldIgnoreUnknownKitInFilter() { val options = MParticleOptions.builder(MockContext()).build() - val filteredKitOptions = MParticleOptions.builder(MockContext()) - .disabledKits(listOf(1231, 132132)) - .build() + val filteredKitOptions = + MParticleOptions + .builder(MockContext()) + .disabledKits(listOf(1231, 132132)) + .build() val filteredKitIntegrationFactory = KitIntegrationFactory(filteredKitOptions) val kitIntegrationFactory = KitIntegrationFactory(options) @@ -716,9 +797,11 @@ class KitManagerImplTest { @Test fun shouldRetainUnfilteredKits() { val filteredKitId = MParticle.ServiceProviders.ADJUST - val options = MParticleOptions.builder(MockContext()) - .disabledKits(listOf(filteredKitId)) - .build() + val options = + MParticleOptions + .builder(MockContext()) + .disabledKits(listOf(filteredKitId)) + .build() val factory = KitIntegrationFactory(options) @@ -775,9 +858,10 @@ class KitManagerImplTest { kitConfiguration.put(JSONObject("{\"id\":1}")) kitConfiguration.put(JSONObject("{\"id\":2}")) `when`(manager.mCoreCallbacks.getLatestKitConfiguration()).thenReturn(kitConfiguration) - val factory = mock( - KitIntegrationFactory::class.java - ) + val factory = + mock( + KitIntegrationFactory::class.java, + ) manager.setKitFactory(factory) `when`(factory.getSupportedKits()).thenReturn(createKitsMap(listOf(1, 2)).keys) `when`(factory.isSupported(Mockito.anyInt())).thenReturn(true) @@ -785,16 +869,16 @@ class KitManagerImplTest { `when`(mockKit.isDisabled).thenReturn(true) `when`(mockKit.configuration).thenReturn( mock( - KitConfiguration::class.java - ) + KitConfiguration::class.java, + ), ) `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(mockKit) manager.setOptOut(true) manager.updateKits(kitConfiguration) @@ -809,28 +893,34 @@ class KitManagerImplTest { val sideloadedKit = mock(MPSideloadedKit::class.java) val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) - val settingsMap = hashMapOf( - "placementAttributesMapping" to """ - [ - {"map": "number", "value": "no"}, - {"map": "customerId", "value": "minorcatid"} - ] - """.trimIndent() - ) + val settingsMap = + hashMapOf( + "placementAttributesMapping" to + """ + [ + {"map": "number", "value": "no"}, + {"map": "customerId", "value": "minorcatid"} + ] + """.trimIndent(), + ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true field.set(mockedKitConfig, settingsMap) val mockedProvider = mockProvider(mockedKitConfig) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) val factory = mock(KitIntegrationFactory::class.java) manager.setKitFactory(factory) @@ -842,22 +932,24 @@ class KitManagerImplTest { `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(sideloadedKit) - manager.providers = ConcurrentHashMap().apply { - put(42, mockedProvider) - } + manager.providers = + ConcurrentHashMap().apply { + put(42, mockedProvider) + } - val attributes = hashMapOf( - Pair("test", "Test"), - Pair("lastname", "Test1"), - Pair("number", "(123) 456-9898"), - Pair("customerId", "55555"), - Pair("country", "US") - ) + val attributes = + hashMapOf( + Pair("test", "Test"), + Pair("lastname", "Test1"), + Pair("number", "(123) 456-9898"), + Pair("customerId", "55555"), + Pair("country", "US"), + ) manager.execute("Test", attributes, null, null, null, null) Assert.assertEquals(6, attributes.size) @@ -874,28 +966,34 @@ class KitManagerImplTest { val sideloadedKit = mock(MPSideloadedKit::class.java) val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) - val settingsMap = hashMapOf( - "placementAttributesMapping" to """ - [ - {"map": "number", "value": "no"}, - {"map": "customerId", "value": "minorcatid"} - ] - """.trimIndent() - ) + val settingsMap = + hashMapOf( + "placementAttributesMapping" to + """ + [ + {"map": "number", "value": "no"}, + {"map": "customerId", "value": "minorcatid"} + ] + """.trimIndent(), + ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true field.set(mockedKitConfig, settingsMap) val mockedProvider = mockProvider(mockedKitConfig) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) val factory = mock(KitIntegrationFactory::class.java) manager.setKitFactory(factory) @@ -907,22 +1005,24 @@ class KitManagerImplTest { `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(sideloadedKit) - manager.providers = ConcurrentHashMap().apply { - put(42, mockedProvider) - } + manager.providers = + ConcurrentHashMap().apply { + put(42, mockedProvider) + } - val attributes = hashMapOf( - Pair("test", "Test"), - Pair("lastname", "Test1"), - Pair("call", "(123) 456-9898"), - Pair("postal", "5-45555"), - Pair("country", "US") - ) + val attributes = + hashMapOf( + Pair("test", "Test"), + Pair("lastname", "Test1"), + Pair("call", "(123) 456-9898"), + Pair("postal", "5-45555"), + Pair("country", "US"), + ) manager.execute("Test", attributes, null, null, null, null) Assert.assertEquals(6, attributes.size) @@ -940,28 +1040,34 @@ class KitManagerImplTest { val sideloadedKit = mock(MPSideloadedKit::class.java) val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) - val settingsMap = hashMapOf( - "placementAttributesMapping" to """ - [ - {"map": "number", "value": "no"}, - {"map": "customerId", "value": "minorcatid"} - ] - """.trimIndent() - ) + val settingsMap = + hashMapOf( + "placementAttributesMapping" to + """ + [ + {"map": "number", "value": "no"}, + {"map": "customerId", "value": "minorcatid"} + ] + """.trimIndent(), + ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true field.set(mockedKitConfig, settingsMap) val mockedProvider = mockProvider(mockedKitConfig) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) val factory = mock(KitIntegrationFactory::class.java) manager.setKitFactory(factory) @@ -973,22 +1079,24 @@ class KitManagerImplTest { `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(sideloadedKit) - manager.providers = ConcurrentHashMap().apply { - put(42, mockedProvider) - } + manager.providers = + ConcurrentHashMap().apply { + put(42, mockedProvider) + } - val attributes = hashMapOf( - Pair("test", "Test"), - Pair("lastname", "Test1"), - Pair("no", "(123) 456-9898"), - Pair("minorcatid", "5-45555"), - Pair("country", "US") - ) + val attributes = + hashMapOf( + Pair("test", "Test"), + Pair("lastname", "Test1"), + Pair("no", "(123) 456-9898"), + Pair("minorcatid", "5-45555"), + Pair("country", "US"), + ) manager.execute("Test", attributes, null, null, null, null) Assert.assertEquals(6, attributes.size) @@ -1005,27 +1113,32 @@ class KitManagerImplTest { val sideloadedKit = mock(MPSideloadedKit::class.java) val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) - val settingsMap = hashMapOf( - "placementAttributesMapping" to """ - [ - - ] - """.trimIndent() - ) + val settingsMap = + hashMapOf( + "placementAttributesMapping" to + """ + [ + ] + """.trimIndent(), + ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true field.set(mockedKitConfig, settingsMap) val mockedProvider = mockProvider(mockedKitConfig) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) val factory = mock(KitIntegrationFactory::class.java) manager.setKitFactory(factory) @@ -1037,22 +1150,24 @@ class KitManagerImplTest { `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(sideloadedKit) - manager.providers = ConcurrentHashMap().apply { - put(42, mockedProvider) - } + manager.providers = + ConcurrentHashMap().apply { + put(42, mockedProvider) + } - val attributes = hashMapOf( - Pair("test", "Test"), - Pair("lastname", "Test1"), - Pair("number", "(123) 456-9898"), - Pair("customerId", "55555"), - Pair("country", "US") - ) + val attributes = + hashMapOf( + Pair("test", "Test"), + Pair("lastname", "Test1"), + Pair("number", "(123) 456-9898"), + Pair("customerId", "55555"), + Pair("country", "US"), + ) manager.execute("Test", attributes, null, null, null, null) Assert.assertEquals(6, attributes.size) @@ -1072,9 +1187,10 @@ class KitManagerImplTest { val sideloadedKit = mock(MPSideloadedKit::class.java) val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) val identityApi = mock(IdentityApi::class.java) @@ -1085,29 +1201,34 @@ class KitManagerImplTest { identities.put(MParticle.IdentityType.Email, oldEmail) `when`(user.userIdentities).thenReturn(identities) instance.setIdentityApi(identityApi) - val settingsMap = hashMapOf( - "placementAttributesMapping" to """ - [ - - ] - """.trimIndent() - ) + val settingsMap = + hashMapOf( + "placementAttributesMapping" to + """ + [ + ] + """.trimIndent(), + ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true field.set(mockedKitConfig, settingsMap) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) - val method: Method = KitManagerImpl::class.java.getDeclaredMethod( - "confirmEmail", - String::class.java, - String::class.java, - MParticleUser::class.java, - IdentityApi::class.java, - KitConfiguration::class.java, - Runnable::class.java - ) + val method: Method = + KitManagerImpl::class.java.getDeclaredMethod( + "confirmEmail", + String::class.java, + String::class.java, + MParticleUser::class.java, + IdentityApi::class.java, + KitConfiguration::class.java, + Runnable::class.java, + ) method.isAccessible = true val result = method.invoke(manager, "Test@gmail.com", "", user, identityApi, mockedKitConfig, runnable) verify(mockTask).addSuccessListener(any()) @@ -1121,9 +1242,10 @@ class KitManagerImplTest { val sideloadedKit = mock(MPSideloadedKit::class.java) val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) val identityApi = mock(IdentityApi::class.java) @@ -1134,19 +1256,23 @@ class KitManagerImplTest { identities.put(MParticle.IdentityType.Email, oldEmail) `when`(user.userIdentities).thenReturn(identities) instance.setIdentityApi(identityApi) - val settingsMap = hashMapOf( - "placementAttributesMapping" to """ - [ - - ] - """.trimIndent() - ) + val settingsMap = + hashMapOf( + "placementAttributesMapping" to + """ + [ + ] + """.trimIndent(), + ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true field.set(mockedKitConfig, settingsMap) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) val method: Method = KitManagerImpl::class.java.getDeclaredMethod( "confirmEmail", @@ -1170,9 +1296,10 @@ class KitManagerImplTest { val sideloadedKit = mock(MPSideloadedKit::class.java) val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) val identityApi = mock(IdentityApi::class.java) @@ -1183,19 +1310,23 @@ class KitManagerImplTest { identities.put(MParticle.IdentityType.Email, oldEmail) `when`(user.userIdentities).thenReturn(identities) instance.setIdentityApi(identityApi) - val settingsMap = hashMapOf( - "placementAttributesMapping" to """ - [ - - ] - """.trimIndent() - ) + val settingsMap = + hashMapOf( + "placementAttributesMapping" to + """ + [ + ] + """.trimIndent(), + ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true field.set(mockedKitConfig, settingsMap) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) val method: Method = KitManagerImpl::class.java.getDeclaredMethod( "confirmEmail", @@ -1219,9 +1350,10 @@ class KitManagerImplTest { val sideloadedKit = mock(MPSideloadedKit::class.java) val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) val identityApi = mock(IdentityApi::class.java) @@ -1232,19 +1364,23 @@ class KitManagerImplTest { identities.put(MParticle.IdentityType.Email, oldEmail) `when`(user.userIdentities).thenReturn(identities) instance.setIdentityApi(identityApi) - val settingsMap = hashMapOf( - "placementAttributesMapping" to """ - [ - - ] - """.trimIndent() - ) + val settingsMap = + hashMapOf( + "placementAttributesMapping" to + """ + [ + ] + """.trimIndent(), + ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true field.set(mockedKitConfig, settingsMap) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) val method: Method = KitManagerImpl::class.java.getDeclaredMethod( "confirmEmail", @@ -1268,9 +1404,10 @@ class KitManagerImplTest { val sideloadedKit = mock(MPSideloadedKit::class.java) val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) val identityApi = mock(IdentityApi::class.java) @@ -1281,19 +1418,23 @@ class KitManagerImplTest { identities.put(MParticle.IdentityType.Other, oldHashedEmail) `when`(user.userIdentities).thenReturn(identities) instance.setIdentityApi(identityApi) - val settingsMap = hashMapOf( - "placementAttributesMapping" to """ - [ - - ] - """.trimIndent() - ) + val settingsMap = + hashMapOf( + "placementAttributesMapping" to + """ + [ + ] + """.trimIndent(), + ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true field.set(mockedKitConfig, settingsMap) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) val method: Method = KitManagerImpl::class.java.getDeclaredMethod( "confirmEmail", @@ -1317,9 +1458,10 @@ class KitManagerImplTest { val sideloadedKit = mock(MPSideloadedKit::class.java) val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) val identityApi = mock(IdentityApi::class.java) @@ -1330,19 +1472,23 @@ class KitManagerImplTest { identities.put(MParticle.IdentityType.Other, oldHashedEmail) `when`(user.userIdentities).thenReturn(identities) instance.setIdentityApi(identityApi) - val settingsMap = hashMapOf( - "placementAttributesMapping" to """ - [ - - ] - """.trimIndent() - ) + val settingsMap = + hashMapOf( + "placementAttributesMapping" to + """ + [ + ] + """.trimIndent(), + ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true field.set(mockedKitConfig, settingsMap) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) val method: Method = KitManagerImpl::class.java.getDeclaredMethod( "confirmEmail", @@ -1366,9 +1512,10 @@ class KitManagerImplTest { val sideloadedKit = mock(MPSideloadedKit::class.java) val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) val identityApi = mock(IdentityApi::class.java) @@ -1379,19 +1526,23 @@ class KitManagerImplTest { identities.put(MParticle.IdentityType.Other, oldHashedEmail) `when`(user.userIdentities).thenReturn(identities) instance.setIdentityApi(identityApi) - val settingsMap = hashMapOf( - "placementAttributesMapping" to """ - [ - - ] - """.trimIndent() - ) + val settingsMap = + hashMapOf( + "placementAttributesMapping" to + """ + [ + ] + """.trimIndent(), + ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true field.set(mockedKitConfig, settingsMap) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) val method: Method = KitManagerImpl::class.java.getDeclaredMethod( "confirmEmail", @@ -1514,21 +1665,26 @@ class KitManagerImplTest { @Test fun testGetValueIgnoreCase_keyExistsDifferentCase() { val sideloadedKit = mock(MPSideloadedKit::class.java) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) val manager: KitManagerImpl = MockKitManagerImpl(options) - val method: Method = KitManagerImpl::class.java.getDeclaredMethod( - "getValueIgnoreCase", - Map::class.java, - String::class.java - ) + val method: Method = + KitManagerImpl::class.java.getDeclaredMethod( + "getValueIgnoreCase", + Map::class.java, + String::class.java, + ) method.isAccessible = true val map = hashMapOf("Email" to "test@example.com") val result = method.invoke(manager, map, "email") @@ -1538,21 +1694,26 @@ class KitManagerImplTest { @Test fun testGetValueIgnoreCase_when__no_match() { val sideloadedKit = mock(MPSideloadedKit::class.java) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) val manager: KitManagerImpl = MockKitManagerImpl(options) - val method: Method = KitManagerImpl::class.java.getDeclaredMethod( - "getValueIgnoreCase", - Map::class.java, - String::class.java - ) + val method: Method = + KitManagerImpl::class.java.getDeclaredMethod( + "getValueIgnoreCase", + Map::class.java, + String::class.java, + ) method.isAccessible = true val map = mapOf("Name" to "Test") val result = method.invoke(manager, map, "email") @@ -1562,21 +1723,26 @@ class KitManagerImplTest { @Test fun testGetValueIgnoreCase_when_empty_map_returns_null() { val sideloadedKit = mock(MPSideloadedKit::class.java) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) val manager: KitManagerImpl = MockKitManagerImpl(options) - val method: Method = KitManagerImpl::class.java.getDeclaredMethod( - "getValueIgnoreCase", - Map::class.java, - String::class.java - ) + val method: Method = + KitManagerImpl::class.java.getDeclaredMethod( + "getValueIgnoreCase", + Map::class.java, + String::class.java, + ) method.isAccessible = true val map = emptyMap() val result = method.invoke(manager, map, "email") @@ -1586,21 +1752,26 @@ class KitManagerImplTest { @Test fun testGetValueIgnoreCase_when_empty_key_returns_null1() { val sideloadedKit = mock(MPSideloadedKit::class.java) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) val manager: KitManagerImpl = MockKitManagerImpl(options) - val method: Method = KitManagerImpl::class.java.getDeclaredMethod( - "getValueIgnoreCase", - Map::class.java, - String::class.java - ) + val method: Method = + KitManagerImpl::class.java.getDeclaredMethod( + "getValueIgnoreCase", + Map::class.java, + String::class.java, + ) method.isAccessible = true val map = mapOf("Name" to "Test") val result = method.invoke(manager, map, null) @@ -1612,25 +1783,31 @@ class KitManagerImplTest { val sideloadedKit = mock(MPSideloadedKit::class.java) val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) `when`(sideloadedKit.configuration).thenReturn(mockedKitConfig) - val settingsMap = hashMapOf( - "placementAttributesMapping" to """ - [] - """.trimIndent() - ) + val settingsMap = + hashMapOf( + "placementAttributesMapping" to + """ + [] + """.trimIndent(), + ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true field.set(mockedKitConfig, settingsMap) val mockedProvider = mockProvider(mockedKitConfig) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) val factory = mock(KitIntegrationFactory::class.java) manager.setKitFactory(factory) @@ -1642,22 +1819,24 @@ class KitManagerImplTest { `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(sideloadedKit) - manager.providers = ConcurrentHashMap().apply { - put(42, mockedProvider) - } + manager.providers = + ConcurrentHashMap().apply { + put(42, mockedProvider) + } - val attributes = hashMapOf( - Pair("test", "Test"), - Pair("lastname", "Test1"), - Pair("number", "(123) 456-9898"), - Pair("customerId", "55555"), - Pair("country", "US") - ) + val attributes = + hashMapOf( + Pair("test", "Test"), + Pair("lastname", "Test1"), + Pair("number", "(123) 456-9898"), + Pair("customerId", "55555"), + Pair("country", "US"), + ) manager.execute("Test", attributes, null, null, null, null) Assert.assertEquals(6, attributes.size) Assert.assertEquals("(123) 456-9898", attributes["number"]) @@ -1673,24 +1852,30 @@ class KitManagerImplTest { val sideloadedKit = mock(MPSideloadedKit::class.java) val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) - val settingsMap = hashMapOf( - "placementAttributesMapping" to """ - [] - """.trimIndent() - ) + val settingsMap = + hashMapOf( + "placementAttributesMapping" to + """ + [] + """.trimIndent(), + ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true field.set(mockedKitConfig, settingsMap) val mockedProvider = mockProvider(mockedKitConfig) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) val factory = mock(KitIntegrationFactory::class.java) manager.setKitFactory(factory) @@ -1704,22 +1889,24 @@ class KitManagerImplTest { `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(sideloadedKit) - manager.providers = ConcurrentHashMap().apply { - put(42, mockedProvider) - } + manager.providers = + ConcurrentHashMap().apply { + put(42, mockedProvider) + } - val attributes = hashMapOf( - Pair("test", "Test"), - Pair("lastname", "Test1"), - Pair("number", "(123) 456-9898"), - Pair("customerId", "55555"), - Pair("country", "US") - ) + val attributes = + hashMapOf( + Pair("test", "Test"), + Pair("lastname", "Test1"), + Pair("number", "(123) 456-9898"), + Pair("customerId", "55555"), + Pair("country", "US"), + ) manager.execute("Test", attributes, null, null, null, null) Assert.assertEquals(6, attributes.size) Assert.assertEquals("(123) 456-9898", attributes["number"]) @@ -1735,24 +1922,30 @@ class KitManagerImplTest { val sideloadedKit = mock(MPSideloadedKit::class.java) val kitId = 6000000 - val configJSONObj = JSONObject().apply { - put("id", kitId) - } + val configJSONObj = + JSONObject().apply { + put("id", kitId) + } val mockedKitConfig = KitConfiguration.createKitConfiguration(configJSONObj) - val settingsMap = hashMapOf( - "placementAttributesMapping" to """ - [] - """.trimIndent() - ) + val settingsMap = + hashMapOf( + "placementAttributesMapping" to + """ + [] + """.trimIndent(), + ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true field.set(mockedKitConfig, settingsMap) val mockedProvider = mockProvider(mockedKitConfig) - val options = MParticleOptions.builder(MockContext()) - .sideloadedKits(mutableListOf(sideloadedKit) as List).build() + val options = + MParticleOptions + .builder(MockContext()) + .sideloadedKits(mutableListOf(sideloadedKit) as List) + .build() val manager: KitManagerImpl = MockKitManagerImpl(options) val factory = mock(KitIntegrationFactory::class.java) manager.setKitFactory(factory) @@ -1766,23 +1959,25 @@ class KitManagerImplTest { `when`( factory.createInstance( any( - KitManagerImpl::class.java + KitManagerImpl::class.java, ), - any(KitConfiguration::class.java) - ) + any(KitConfiguration::class.java), + ), ).thenReturn(sideloadedKit) - manager.providers = ConcurrentHashMap().apply { - put(42, mockedProvider) - } + manager.providers = + ConcurrentHashMap().apply { + put(42, mockedProvider) + } - val attributes = hashMapOf( - Pair("test", "Test"), - Pair("lastname", "Test1"), - Pair("number", "(123) 456-9898"), - Pair("customerId", "55555"), - Pair("country", "US"), - Pair("sandbox", "false") - ) + val attributes = + hashMapOf( + Pair("test", "Test"), + Pair("lastname", "Test1"), + Pair("number", "(123) 456-9898"), + Pair("customerId", "55555"), + Pair("country", "US"), + Pair("sandbox", "false"), + ) manager.execute("Test", attributes, null, null, null, null) Assert.assertEquals(6, attributes.size) Assert.assertEquals("(123) 456-9898", attributes["number"]) @@ -1797,26 +1992,29 @@ class KitManagerImplTest { fun testSetWrapperSdkVersion() { val manager: KitManagerImpl = MockKitManagerImpl() - val enabledRoktListener = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(KitIntegration.RoktListener::class.java) - ) + val enabledRoktListener = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(KitIntegration.RoktListener::class.java), + ) `when`(enabledRoktListener.isDisabled).thenReturn(false) - val disabledRoktListener = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(KitIntegration.RoktListener::class.java) - ) + val disabledRoktListener = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(KitIntegration.RoktListener::class.java), + ) `when`(disabledRoktListener.isDisabled).thenReturn(true) val nonRoktListener = mock(KitIntegration::class.java) `when`(nonRoktListener.isDisabled).thenReturn(false) - manager.providers = ConcurrentHashMap().apply { - put(1, enabledRoktListener) - put(2, disabledRoktListener) - put(3, nonRoktListener) - } + manager.providers = + ConcurrentHashMap().apply { + put(1, enabledRoktListener) + put(2, disabledRoktListener) + put(3, nonRoktListener) + } val wrapperSdkVersion = WrapperSdkVersion(WrapperSdk.WrapperFlutter, "1.2.3") manager.setWrapperSdkVersion(wrapperSdkVersion) @@ -1847,9 +2045,10 @@ class KitManagerImplTest { `when`(nonRoktProvider.isDisabled).thenReturn(false) `when`(nonRoktProvider.getName()).thenReturn("NonRoktProvider") - manager.providers = ConcurrentHashMap().apply { - put(1, nonRoktProvider) - } + manager.providers = + ConcurrentHashMap().apply { + put(1, nonRoktProvider) + } val result = manager.events("test-identifier") @@ -1863,16 +2062,18 @@ class KitManagerImplTest { fun testEvents_roktListenerDisabled_returnsEmptyFlow() { val manager: KitManagerImpl = MockKitManagerImpl() - val disabledRoktProvider = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(KitIntegration.RoktListener::class.java) - ) + val disabledRoktProvider = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(KitIntegration.RoktListener::class.java), + ) `when`(disabledRoktProvider.isDisabled).thenReturn(true) `when`(disabledRoktProvider.getName()).thenReturn("DisabledRoktProvider") - manager.providers = ConcurrentHashMap().apply { - put(1, disabledRoktProvider) - } + manager.providers = + ConcurrentHashMap().apply { + put(1, disabledRoktProvider) + } val result = manager.events("test-identifier") @@ -1886,10 +2087,11 @@ class KitManagerImplTest { fun testEvents_roktListenerEnabled_delegatesToProvider() { val manager: KitManagerImpl = MockKitManagerImpl() - val enabledRoktProvider = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(KitIntegration.RoktListener::class.java) - ) + val enabledRoktProvider = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(KitIntegration.RoktListener::class.java), + ) `when`(enabledRoktProvider.isDisabled).thenReturn(false) `when`(enabledRoktProvider.getName()).thenReturn("EnabledRoktProvider") @@ -1898,9 +2100,10 @@ class KitManagerImplTest { `when`((enabledRoktProvider as KitIntegration.RoktListener).events(testIdentifier)) .thenReturn(expectedFlow) - manager.providers = ConcurrentHashMap().apply { - put(1, enabledRoktProvider) - } + manager.providers = + ConcurrentHashMap().apply { + put(1, enabledRoktProvider) + } val result = manager.events(testIdentifier) @@ -1916,24 +2119,27 @@ class KitManagerImplTest { `when`(nonRoktProvider.isDisabled).thenReturn(false) `when`(nonRoktProvider.getName()).thenReturn("NonRoktProvider") - val disabledRoktProvider = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(KitIntegration.RoktListener::class.java) - ) + val disabledRoktProvider = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(KitIntegration.RoktListener::class.java), + ) `when`(disabledRoktProvider.isDisabled).thenReturn(true) `when`(disabledRoktProvider.getName()).thenReturn("DisabledRoktProvider") - val enabledRoktProvider = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(KitIntegration.RoktListener::class.java) - ) + val enabledRoktProvider = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(KitIntegration.RoktListener::class.java), + ) `when`(enabledRoktProvider.isDisabled).thenReturn(false) `when`(enabledRoktProvider.getName()).thenReturn("EnabledRoktProvider") - val secondEnabledRoktProvider = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(KitIntegration.RoktListener::class.java) - ) + val secondEnabledRoktProvider = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(KitIntegration.RoktListener::class.java), + ) `when`(secondEnabledRoktProvider.isDisabled).thenReturn(false) `when`(secondEnabledRoktProvider.getName()).thenReturn("SecondEnabledRoktProvider") @@ -1944,12 +2150,13 @@ class KitManagerImplTest { `when`((secondEnabledRoktProvider as KitIntegration.RoktListener).events(testIdentifier)) .thenReturn(flowOf()) - manager.providers = ConcurrentHashMap().apply { - put(1, nonRoktProvider) - put(2, disabledRoktProvider) - put(3, enabledRoktProvider) - put(4, secondEnabledRoktProvider) - } + manager.providers = + ConcurrentHashMap().apply { + put(1, nonRoktProvider) + put(2, disabledRoktProvider) + put(3, enabledRoktProvider) + put(4, secondEnabledRoktProvider) + } val result = manager.events(testIdentifier) @@ -1962,18 +2169,20 @@ class KitManagerImplTest { fun testEvents_providerThrowsException_returnsEmptyFlow() { val manager: KitManagerImpl = MockKitManagerImpl() - val exceptionRoktProvider = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(KitIntegration.RoktListener::class.java) - ) + val exceptionRoktProvider = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(KitIntegration.RoktListener::class.java), + ) `when`(exceptionRoktProvider.isDisabled).thenReturn(false) `when`(exceptionRoktProvider.getName()).thenReturn("ExceptionRoktProvider") `when`((exceptionRoktProvider as KitIntegration.RoktListener).events(any())) .thenThrow(RuntimeException("Test exception")) - manager.providers = ConcurrentHashMap().apply { - put(1, exceptionRoktProvider) - } + manager.providers = + ConcurrentHashMap().apply { + put(1, exceptionRoktProvider) + } val result = manager.events("test-identifier") @@ -1987,19 +2196,21 @@ class KitManagerImplTest { fun testEvents_providerThrowsException_continuesToNextProvider() { val manager: KitManagerImpl = MockKitManagerImpl() - val exceptionRoktProvider = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(KitIntegration.RoktListener::class.java) - ) + val exceptionRoktProvider = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(KitIntegration.RoktListener::class.java), + ) `when`(exceptionRoktProvider.isDisabled).thenReturn(false) `when`(exceptionRoktProvider.getName()).thenReturn("ExceptionRoktProvider") `when`((exceptionRoktProvider as KitIntegration.RoktListener).events(any())) .thenThrow(RuntimeException("Test exception")) - val workingRoktProvider = mock( - KitIntegration::class.java, - withSettings().extraInterfaces(KitIntegration.RoktListener::class.java) - ) + val workingRoktProvider = + mock( + KitIntegration::class.java, + withSettings().extraInterfaces(KitIntegration.RoktListener::class.java), + ) `when`(workingRoktProvider.isDisabled).thenReturn(false) `when`(workingRoktProvider.getName()).thenReturn("WorkingRoktProvider") @@ -2008,10 +2219,11 @@ class KitManagerImplTest { `when`((workingRoktProvider as KitIntegration.RoktListener).events(testIdentifier)) .thenReturn(expectedFlow) - manager.providers = ConcurrentHashMap().apply { - put(1, exceptionRoktProvider) - put(2, workingRoktProvider) - } + manager.providers = + ConcurrentHashMap().apply { + put(1, exceptionRoktProvider) + put(2, workingRoktProvider) + } val result = manager.events(testIdentifier) @@ -2019,10 +2231,18 @@ class KitManagerImplTest { assertEquals(expectedFlow, result) } - internal inner class mockProvider(val config: KitConfiguration) : KitIntegration(), KitIntegration.RoktListener { + internal inner class mockProvider( + val config: KitConfiguration, + ) : KitIntegration(), + KitIntegration.RoktListener { override fun isDisabled(): Boolean = false + override fun getName(): String = "FakeProvider" - override fun onKitCreate(settings: MutableMap?, context: Context?): MutableList { + + override fun onKitCreate( + settings: MutableMap?, + context: Context?, + ): MutableList { TODO("Not yet implemented") } @@ -2030,9 +2250,7 @@ class KitManagerImplTest { TODO("Not yet implemented") } - override fun getConfiguration(): KitConfiguration { - return config - } + override fun getConfiguration(): KitConfiguration = config override fun execute( viewName: String, @@ -2041,7 +2259,7 @@ class KitManagerImplTest { placeHolders: MutableMap>?, fontTypefaces: MutableMap>?, user: FilteredMParticleUser?, - config: RoktConfig? + config: RoktConfig?, ) { println("Executed with $attributes") } @@ -2051,7 +2269,10 @@ class KitManagerImplTest { return flowOf() } - override fun enrichAttributes(attributes: MutableMap, user: FilteredMParticleUser?) { + override fun enrichAttributes( + attributes: MutableMap, + user: FilteredMParticleUser?, + ) { println("callRoktComposable with $attributes") } @@ -2059,7 +2280,11 @@ class KitManagerImplTest { println("setWrapperSdkVersion with $wrapperSdkVersion") } - override fun purchaseFinalized(placementId: String, catalogItemId: String, status: Boolean) { + override fun purchaseFinalized( + placementId: String, + catalogItemId: String, + status: Boolean, + ) { println("purchaseFinalized with placementId: $placementId catalogItemId : $catalogItemId status : $status ") } @@ -2072,6 +2297,7 @@ class KitManagerImplTest { var logBaseEventCalled = 0 var logCommerceEventCalled = 0 var logMPEventCalled = 0 + override fun logEvent(event: BaseEvent) { super.logEvent(event) logBaseEventCalled++ diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerTest.kt index 8087b7ec0..0301ec78b 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerTest.kt @@ -61,8 +61,8 @@ class KitManagerTest { Pair(37, KitIntegration::class.java), Pair(56, KitIntegration::class.java), Pair(64, KitIntegration::class.java), - Pair(68, KitIntegration::class.java) - ) + Pair(68, KitIntegration::class.java), + ), ) Assert.assertNotNull(array) manager.updateKits(array) @@ -151,8 +151,8 @@ class KitManagerTest { Pair(37, KitIntegration::class.java), Pair(56, KitIntegration::class.java), Pair(64, KitIntegration::class.java), - Pair(68, KitIntegration::class.java) - ) + Pair(68, KitIntegration::class.java), + ), ) manager.updateKits(array) val kitStatus = manager.kitStatus @@ -184,24 +184,25 @@ class KitManagerTest { val mockConfig = MockKitConfiguration().parseConfiguration(config) Mockito.`when`(mockForesee.configuration).thenReturn(mockConfig) val uri = Mockito.mock(Uri::class.java) - Mockito.`when`( - mockForesee.getSurveyUrl( - Mockito.any( - MutableMap::class.java - ) as MutableMap?, - Mockito.any( - MutableMap::class.java - ) as MutableMap>? - ) - ).thenReturn(uri) + Mockito + .`when`( + mockForesee.getSurveyUrl( + Mockito.any( + MutableMap::class.java, + ) as MutableMap?, + Mockito.any( + MutableMap::class.java, + ) as MutableMap>?, + ), + ).thenReturn(uri) manager.providers[MParticle.ServiceProviders.FORESEE_ID] = (mockForesee as KitIntegration) Assert.assertNull(manager.getSurveyUrl(56, HashMap(), HashMap())) Assert.assertTrue( manager.getSurveyUrl( MParticle.ServiceProviders.FORESEE_ID, HashMap(), - HashMap() - ) === uri + HashMap(), + ) === uri, ) } diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt index 6ca81dba0..0cf12761c 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt @@ -41,40 +41,42 @@ class CustomMappingTest { val matches = pJson.getJSONArray("matches") Assert.assertEquals( matches.getJSONObject(0).getInt("message_type").toLong(), - customMapping.messageType.toLong() + customMapping.messageType.toLong(), ) Assert.assertEquals( matches.getJSONObject(0).getString("event_match_type"), - customMapping.matchList[0].mMatchType + customMapping.matchList[0].mMatchType, ) if (customMapping.matchList[0].mMatchType.startsWith(CustomMapping.MATCH_TYPE_HASH)) { Assert.assertEquals( matches.getJSONObject(0).getInt("event").toLong(), - customMapping.matchList[0].mEventHash.toLong() + customMapping.matchList[0].mEventHash.toLong(), ) } else { Assert.assertEquals( matches.getJSONObject(0).getString("event"), - customMapping.matchList[0].mEventName + customMapping.matchList[0].mEventName, ) } if (matches.getJSONObject(0).has("attribute_key")) { Assert.assertEquals( matches.getJSONObject(0).getString("attribute_key"), - customMapping.matchList[0].mAttributeKey + customMapping.matchList[0].mAttributeKey, ) if (matches.getJSONObject(0)["attribute_values"] is JSONArray) { val attributeValues = matches.getJSONObject(0).getJSONArray("attribute_values") Assert.assertEquals( attributeValues.length().toLong(), - customMapping.matchList[0].attributeValues.size.toLong() + customMapping.matchList[0] + .attributeValues.size + .toLong(), ) } else { Assert.assertTrue( customMapping.matchList[0].attributeValues.contains( - matches.getJSONObject(0).getString("attribute_values").lowercase() - ) + matches.getJSONObject(0).getString("attribute_values").lowercase(), + ), ) } } @@ -83,29 +85,30 @@ class CustomMappingTest { Assert.assertEquals(behaviors.optBoolean("is_default"), customMapping.isDefault) Assert.assertEquals( behaviors.optBoolean("append_unmapped_as_is"), - customMapping.mAppendUnmappedAsIs + customMapping.mAppendUnmappedAsIs, ) Assert.assertEquals( behaviors.optInt("max_custom_params", Int.MAX_VALUE).toLong(), - customMapping.mMaxCustomParams.toLong() + customMapping.mMaxCustomParams.toLong(), ) } val action = pJson.getJSONObject("action") Assert.assertEquals( customMapping.mProjectedEventName, - action.getString("projected_event_name") + action.getString("projected_event_name"), ) val attributes = action.getJSONArray("attribute_maps") val sum = - (if (customMapping.mRequiredAttributeMapList == null) 0 else customMapping.mRequiredAttributeMapList.size) + - if (customMapping.mStaticAttributeMapList == null) 0 else customMapping.mStaticAttributeMapList.size + (if (customMapping.mRequiredAttributeMapList == null) 0 else customMapping.mRequiredAttributeMapList.size) + if (customMapping.mStaticAttributeMapList == null) 0 else customMapping.mStaticAttributeMapList.size Assert.assertEquals(attributes.length().toLong(), sum.toLong()) for (k in 0 until attributes.length()) { val attribute = attributes.getJSONObject(k) val attProj = CustomMapping.AttributeMap(attribute) Assert.assertEquals(attribute.optBoolean("is_required"), attProj.mIsRequired) - if (attribute.getString("match_type") - .startsWith(CustomMapping.MATCH_TYPE_STATIC) + if (attribute + .getString("match_type") + .startsWith(CustomMapping.MATCH_TYPE_STATIC) ) { Assert.assertFalse(customMapping.mRequiredAttributeMapList.contains(attProj)) Assert.assertTrue(customMapping.mStaticAttributeMapList.contains(attProj)) @@ -130,12 +133,20 @@ class CustomMappingTest { @Throws(Exception::class) fun testDefault() { val defaultCustomMapping = - CustomMapping(JSONObject("{ \"id\":89, \"matches\":[{ \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" }], \"behavior\":{ \"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ ] } }")) + CustomMapping( + JSONObject( + "{ \"id\":89, \"matches\":[{ \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" }], \"behavior\":{ \"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ ] } }", + ), + ) val info = HashMap() info["some key"] = "some value" info["another key"] = "another value" - val event = MPEvent.Builder("whatever", MParticle.EventType.Other).category("whatever!!") - .customAttributes(info).build() + val event = + MPEvent + .Builder("whatever", MParticle.EventType.Other) + .category("whatever!!") + .customAttributes(info) + .build() Assert.assertTrue(defaultCustomMapping.isMatch(MPEventWrapper(event))) val newEvent = defaultCustomMapping.project(MPEventWrapper(event))[0].mpEvent Assert.assertEquals(event, newEvent) @@ -151,21 +162,23 @@ class CustomMappingTest { @Test @Throws(Exception::class) fun testDefaultProjection2() { - val kitConfiguration = MockKitConfiguration.createKitConfiguration( - JSONObject( - "{\"id\":56, \"as\":{}, \"hs\":{}, \"pr\":[{\"id\":93, \"pmmid\":23, \"matches\":[{\"message_type\":4, \"event_match_type\":\"String\", \"event\":\"Product View\", \"attribute_key\":\"\$MethodName\", \"attribute_values\":\"\$ProductView\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"cool_product_view\"} }, {\"id\":89, \"matches\":[{\"message_type\":4, \"event_match_type\":\"\", \"event\":\"\"}], \"behavior\":{\"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{\"projected_event_name\":\"\", \"attribute_maps\":[] } }, {\"id\":100, \"pmid\":179, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"account - check order status\", \"attribute_maps\":[] } }, {\"id\":92, \"pmid\":182, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"1111995177\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"account - feedback\", \"attribute_maps\":[{\"projected_attribute_name\":\"Feedback Type\", \"match_type\":\"Hash\", \"value\":\"-768380952\", \"data_type\":\"String\"} ] } }, {\"id\":96, \"pmid\":183, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - add to tote\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Add to Tote Name\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Print\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Category\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Total Amount\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote SKU\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Size\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Quantity\", \"match_type\":\"Static\", \"value\":\"10\", \"data_type\":\"Int\"}, {\"projected_attribute_name\":\"Last Add to Tote Unit Price\", \"match_type\":\"Static\", \"value\":\"1321\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":184, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":185, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"987878094\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"689388774\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":186, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"-754932241\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"992037090\", \"data_type\":\"String\"} ] } } ] }" + val kitConfiguration = + MockKitConfiguration.createKitConfiguration( + JSONObject( + "{\"id\":56, \"as\":{}, \"hs\":{}, \"pr\":[{\"id\":93, \"pmmid\":23, \"matches\":[{\"message_type\":4, \"event_match_type\":\"String\", \"event\":\"Product View\", \"attribute_key\":\"\$MethodName\", \"attribute_values\":\"\$ProductView\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"cool_product_view\"} }, {\"id\":89, \"matches\":[{\"message_type\":4, \"event_match_type\":\"\", \"event\":\"\"}], \"behavior\":{\"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{\"projected_event_name\":\"\", \"attribute_maps\":[] } }, {\"id\":100, \"pmid\":179, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"account - check order status\", \"attribute_maps\":[] } }, {\"id\":92, \"pmid\":182, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"1111995177\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"account - feedback\", \"attribute_maps\":[{\"projected_attribute_name\":\"Feedback Type\", \"match_type\":\"Hash\", \"value\":\"-768380952\", \"data_type\":\"String\"} ] } }, {\"id\":96, \"pmid\":183, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - add to tote\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Add to Tote Name\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Print\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Category\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Total Amount\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote SKU\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Size\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Quantity\", \"match_type\":\"Static\", \"value\":\"10\", \"data_type\":\"Int\"}, {\"projected_attribute_name\":\"Last Add to Tote Unit Price\", \"match_type\":\"Static\", \"value\":\"1321\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":184, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":185, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"987878094\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"689388774\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":186, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"-754932241\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"992037090\", \"data_type\":\"String\"} ] } } ] }", + ), ) - ) val info = HashMap() info["some key"] = "some value" info["another key"] = "another value" val event = MPEvent.Builder("whatever", MParticle.EventType.Other).customAttributes(info).build() - val list = CustomMapping.projectEvents( - event, - kitConfiguration.customMappingList, - kitConfiguration.defaultEventProjection - ) + val list = + CustomMapping.projectEvents( + event, + kitConfiguration.customMappingList, + kitConfiguration.defaultEventProjection, + ) Assert.assertEquals(1, list.size.toLong()) Assert.assertEquals(list[0].mpEvent, event) } @@ -177,30 +190,33 @@ class CustomMappingTest { @Test @Throws(Exception::class) fun testNoDefaultEventAndDefaultScreen() { - val kitConfiguration = MockKitConfiguration.createKitConfiguration( - JSONObject( - "{\"id\":56, \"as\":{}, \"hs\":{}, \"pr\":[{\"id\":93, \"pmmid\":23, \"matches\":[{\"message_type\":4, \"event_match_type\":\"String\", \"event\":\"Product View\", \"attribute_key\":\"\$MethodName\", \"attribute_values\":\"\$ProductView\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"cool_product_view\"} }, {\"id\":89, \"matches\":[{\"message_type\":3, \"event_match_type\":\"\", \"event\":\"\"}], \"behavior\":{\"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{\"projected_event_name\":\"\", \"attribute_maps\":[] } }, {\"id\":100, \"pmid\":179, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"account - check order status\", \"attribute_maps\":[] } }, {\"id\":92, \"pmid\":182, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"1111995177\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"account - feedback\", \"attribute_maps\":[{\"projected_attribute_name\":\"Feedback Type\", \"match_type\":\"Hash\", \"value\":\"-768380952\", \"data_type\":\"String\"} ] } }, {\"id\":96, \"pmid\":183, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - add to tote\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Add to Tote Name\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Print\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Category\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Total Amount\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote SKU\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Size\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Quantity\", \"match_type\":\"Static\", \"value\":\"10\", \"data_type\":\"Int\"}, {\"projected_attribute_name\":\"Last Add to Tote Unit Price\", \"match_type\":\"Static\", \"value\":\"1321\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":184, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":185, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"987878094\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"689388774\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":186, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"-754932241\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"992037090\", \"data_type\":\"String\"} ] } } ] }" + val kitConfiguration = + MockKitConfiguration.createKitConfiguration( + JSONObject( + "{\"id\":56, \"as\":{}, \"hs\":{}, \"pr\":[{\"id\":93, \"pmmid\":23, \"matches\":[{\"message_type\":4, \"event_match_type\":\"String\", \"event\":\"Product View\", \"attribute_key\":\"\$MethodName\", \"attribute_values\":\"\$ProductView\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"cool_product_view\"} }, {\"id\":89, \"matches\":[{\"message_type\":3, \"event_match_type\":\"\", \"event\":\"\"}], \"behavior\":{\"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{\"projected_event_name\":\"\", \"attribute_maps\":[] } }, {\"id\":100, \"pmid\":179, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"account - check order status\", \"attribute_maps\":[] } }, {\"id\":92, \"pmid\":182, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"1111995177\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"account - feedback\", \"attribute_maps\":[{\"projected_attribute_name\":\"Feedback Type\", \"match_type\":\"Hash\", \"value\":\"-768380952\", \"data_type\":\"String\"} ] } }, {\"id\":96, \"pmid\":183, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - add to tote\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Add to Tote Name\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Print\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Category\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Total Amount\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote SKU\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Size\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Quantity\", \"match_type\":\"Static\", \"value\":\"10\", \"data_type\":\"Int\"}, {\"projected_attribute_name\":\"Last Add to Tote Unit Price\", \"match_type\":\"Static\", \"value\":\"1321\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":184, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":185, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"987878094\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"689388774\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":186, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"-754932241\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"992037090\", \"data_type\":\"String\"} ] } } ] }", + ), ) - ) val info = HashMap() info["some key"] = "some value" info["another key"] = "another value" val event = MPEvent.Builder("whatever", MParticle.EventType.Other).customAttributes(info).build() - var list = CustomMapping.projectEvents( - event, - kitConfiguration.customMappingList, - kitConfiguration.defaultEventProjection - ) + var list = + CustomMapping.projectEvents( + event, + kitConfiguration.customMappingList, + kitConfiguration.defaultEventProjection, + ) Assert.assertNull(list) // but if we say this is a screen event, the default projection should be detected - list = CustomMapping.projectEvents( - event, - true, - kitConfiguration.customMappingList, - kitConfiguration.defaultEventProjection, - kitConfiguration.defaultScreenCustomMapping - ) + list = + CustomMapping.projectEvents( + event, + true, + kitConfiguration.customMappingList, + kitConfiguration.defaultEventProjection, + kitConfiguration.defaultScreenCustomMapping, + ) Assert.assertEquals(1, list.size.toLong()) } @@ -213,7 +229,11 @@ class CustomMappingTest { @Throws(Exception::class) fun testDontAppendAsIs() { var customMapping = - CustomMapping(JSONObject("{ \"id\":89, \"matches\":[{ \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" }], \"behavior\":{ \"append_unmapped_as_is\":false, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ ] } }")) + CustomMapping( + JSONObject( + "{ \"id\":89, \"matches\":[{ \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" }], \"behavior\":{ \"append_unmapped_as_is\":false, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ ] } }", + ), + ) val info = HashMap() info["some key"] = "some value" info["another key"] = "another value" @@ -222,7 +242,11 @@ class CustomMappingTest { var newEvent = customMapping.project(MPEventWrapper(event))[0] Assert.assertTrue(newEvent.mpEvent.customAttributeStrings!!.isEmpty()) customMapping = - CustomMapping(JSONObject("{ \"id\":89, \"matches\":[{ \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" }], \"behavior\":{ \"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ ] } }")) + CustomMapping( + JSONObject( + "{ \"id\":89, \"matches\":[{ \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" }], \"behavior\":{ \"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ ] } }", + ), + ) newEvent = customMapping.project(MPEventWrapper(event))[0] Assert.assertTrue(newEvent.mpEvent.customAttributeStrings!!.size == 2) } @@ -240,7 +264,11 @@ class CustomMappingTest { @Throws(Exception::class) fun testMaxParams() { var customMapping = - CustomMapping(JSONObject("{ \"id\":89, \"matches\":[{ \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" }], \"behavior\":{ \"append_unmapped_as_is\":true, \"max_custom_params\":5, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ ] } }")) + CustomMapping( + JSONObject( + "{ \"id\":89, \"matches\":[{ \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" }], \"behavior\":{ \"append_unmapped_as_is\":true, \"max_custom_params\":5, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ ] } }", + ), + ) val info = HashMap() // add them out of order, why not? info["key 3"] = "123af4" @@ -259,7 +287,11 @@ class CustomMappingTest { Assert.assertFalse(newEvent.customAttributeStrings!!.containsKey("key 6")) // now create the SAME projection, except specify an optional attribute key 6 - it should boot key 5 from the resulting event customMapping = - CustomMapping(JSONObject("{ \"id\":89, \"matches\":[{ \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" }], \"behavior\":{ \"append_unmapped_as_is\":true, \"max_custom_params\":5, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ { \"projected_attribute_name\":\"\", \"match_type\":\"String\", \"value\":\"key 6\", \"data_type\":\"String\" }] } }")) + CustomMapping( + JSONObject( + "{ \"id\":89, \"matches\":[{ \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" }], \"behavior\":{ \"append_unmapped_as_is\":true, \"max_custom_params\":5, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ { \"projected_attribute_name\":\"\", \"match_type\":\"String\", \"value\":\"key 6\", \"data_type\":\"String\" }] } }", + ), + ) result = customMapping.project(MPEventWrapper(event))[0] newEvent = result.mpEvent Assert.assertFalse(newEvent.customAttributeStrings!!.containsKey("key 5")) @@ -268,7 +300,11 @@ class CustomMappingTest { // test what happens if max isn't even set (everything should be there) customMapping = - CustomMapping(JSONObject("{ \"id\":89, \"matches\":[{ \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" }], \"behavior\":{ \"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ { \"projected_attribute_name\":\"\", \"match_type\":\"String\", \"value\":\"key 6\", \"data_type\":\"String\" }] } }")) + CustomMapping( + JSONObject( + "{ \"id\":89, \"matches\":[{ \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" }], \"behavior\":{ \"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ { \"projected_attribute_name\":\"\", \"match_type\":\"String\", \"value\":\"key 6\", \"data_type\":\"String\" }] } }", + ), + ) result = customMapping.project(MPEventWrapper(event))[0] newEvent = result.mpEvent Assert.assertTrue(newEvent.customAttributeStrings!!.containsKey("key 5")) @@ -285,12 +321,16 @@ class CustomMappingTest { @Throws(Exception::class) fun testFieldName() { val customMapping = - CustomMapping(JSONObject("{ \"id\":89, \"matches\":[{ \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" }], \"behavior\":{ \"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ { \"projected_attribute_name\":\"\", \"match_type\":\"String\", \"value\":\"key 6\", \"data_type\":\"String\" },{ \"projected_attribute_name\": \"screen_name_key\", \"match_type\": \"Field\", \"value\": \"ScreenName\", \"data_type\": 1, \"is_required\": true }] } }")) + CustomMapping( + JSONObject( + "{ \"id\":89, \"matches\":[{ \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" }], \"behavior\":{ \"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ { \"projected_attribute_name\":\"\", \"match_type\":\"String\", \"value\":\"key 6\", \"data_type\":\"String\" },{ \"projected_attribute_name\": \"screen_name_key\", \"match_type\": \"Field\", \"value\": \"ScreenName\", \"data_type\": 1, \"is_required\": true }] } }", + ), + ) val event = MPEvent.Builder("screenname", MParticle.EventType.Other).build() val projectedEvent = customMapping.project(MPEventWrapper(event))[0] Assert.assertEquals( "screenname", - projectedEvent.mpEvent.customAttributeStrings!!["screen_name_key"] + projectedEvent.mpEvent.customAttributeStrings!!["screen_name_key"], ) } @@ -305,7 +345,9 @@ class CustomMappingTest { val info: MutableMap = HashMap() info["key 1"] = "value 1" val event = - MPEvent.Builder("some event name", MParticle.EventType.Other).customAttributes(info) + MPEvent + .Builder("some event name", MParticle.EventType.Other) + .customAttributes(info) .build() val wrapper = MPEventWrapper(event) @@ -317,9 +359,10 @@ class CustomMappingTest { // make sure event hash is generated correctly Assert.assertEquals( - KitUtils.hashForFiltering(event.eventType.ordinal.toString() + event.eventName) + KitUtils + .hashForFiltering(event.eventType.ordinal.toString() + event.eventName) .toLong(), - wrapper.eventHash.toLong() + wrapper.eventHash.toLong(), ) Assert.assertEquals(4, wrapper.messageType.toLong()) Assert.assertEquals(event.eventType.ordinal.toLong(), wrapper.eventTypeOrdinal.toLong()) @@ -333,7 +376,9 @@ class CustomMappingTest { val info: MutableMap = HashMap() info["key 1"] = "value 1" val event = - MPEvent.Builder("some event name", MParticle.EventType.Other).customAttributes(info) + MPEvent + .Builder("some event name", MParticle.EventType.Other) + .customAttributes(info) .build() val wrapper = MPEventWrapper(event, true) @@ -346,7 +391,7 @@ class CustomMappingTest { // make sure event hash is generated correctly Assert.assertEquals( KitUtils.hashForFiltering(0.toString() + event.eventName).toLong(), - wrapper.eventHash.toLong() + wrapper.eventHash.toLong(), ) Assert.assertEquals(3, wrapper.messageType.toLong()) Assert.assertEquals(0, wrapper.eventTypeOrdinal.toLong()) @@ -360,11 +405,12 @@ class CustomMappingTest { @Test @Throws(Exception::class) fun testMultiHashProjections1() { - val kitConfiguration = MockKitConfiguration.createKitConfiguration( - JSONObject( - "{\"id\":56, \"as\":{}, \"hs\":{}, \"pr\":[{\"id\":93, \"pmmid\":23, \"matches\":[{\"message_type\":4, \"event_match_type\":\"String\", \"event\":\"Product View\", \"attribute_key\":\"\$MethodName\", \"attribute_values\":\"\$ProductView\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"cool_product_view\"} }, {\"id\":89, \"matches\":[{\"message_type\":4, \"event_match_type\":\"\", \"event\":\"\"}], \"behavior\":{\"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{\"projected_event_name\":\"\", \"attribute_maps\":[] } }, {\"id\":100, \"pmid\":179, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":10, \"append_unmapped_as_is\":true }, \"action\":{\"projected_event_name\":\"account - check order status\", \"attribute_maps\":[] } }, {\"id\":92, \"pmid\":182, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"1111995177\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"account - feedback\", \"attribute_maps\":[{\"projected_attribute_name\":\"Feedback Type\", \"match_type\":\"Hash\", \"value\":\"-768380952\", \"data_type\":\"String\"} ] } }, {\"id\":96, \"pmid\":183, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - add to tote\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Add to Tote Name\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Print\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Category\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\", \"is_required\":true }, {\"projected_attribute_name\":\"Last Add to Tote Total Amount\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote SKU\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Size\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Quantity\", \"match_type\":\"Static\", \"value\":\"10\", \"data_type\":\"Int\"}, {\"projected_attribute_name\":\"Last Add to Tote Unit Price\", \"match_type\":\"Static\", \"value\":\"1321\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":184, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Complete the Look Product Name 2\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\", \"is_required\":true } ] } }, {\"id\":104, \"pmid\":185, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"987878094\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"689388774\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":186, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"-754932241\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"992037090\", \"data_type\":\"String\"} ] } } ] }" + val kitConfiguration = + MockKitConfiguration.createKitConfiguration( + JSONObject( + "{\"id\":56, \"as\":{}, \"hs\":{}, \"pr\":[{\"id\":93, \"pmmid\":23, \"matches\":[{\"message_type\":4, \"event_match_type\":\"String\", \"event\":\"Product View\", \"attribute_key\":\"\$MethodName\", \"attribute_values\":\"\$ProductView\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"cool_product_view\"} }, {\"id\":89, \"matches\":[{\"message_type\":4, \"event_match_type\":\"\", \"event\":\"\"}], \"behavior\":{\"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{\"projected_event_name\":\"\", \"attribute_maps\":[] } }, {\"id\":100, \"pmid\":179, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":10, \"append_unmapped_as_is\":true }, \"action\":{\"projected_event_name\":\"account - check order status\", \"attribute_maps\":[] } }, {\"id\":92, \"pmid\":182, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"1111995177\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"account - feedback\", \"attribute_maps\":[{\"projected_attribute_name\":\"Feedback Type\", \"match_type\":\"Hash\", \"value\":\"-768380952\", \"data_type\":\"String\"} ] } }, {\"id\":96, \"pmid\":183, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - add to tote\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Add to Tote Name\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Print\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Category\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\", \"is_required\":true }, {\"projected_attribute_name\":\"Last Add to Tote Total Amount\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote SKU\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Size\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Quantity\", \"match_type\":\"Static\", \"value\":\"10\", \"data_type\":\"Int\"}, {\"projected_attribute_name\":\"Last Add to Tote Unit Price\", \"match_type\":\"Static\", \"value\":\"1321\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":184, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Complete the Look Product Name 2\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\", \"is_required\":true } ] } }, {\"id\":104, \"pmid\":185, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"987878094\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"689388774\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":186, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"-754932241\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"992037090\", \"data_type\":\"String\"} ] } } ] }", + ), ) - ) /** * Test 1 @@ -375,17 +421,18 @@ class CustomMappingTest { val attributes: MutableMap = HashMap() attributes["attribute we don't care about"] = "some value" builder.customAttributes(attributes) - val eventList = CustomMapping.projectEvents( - builder.build(), - kitConfiguration.customMappingList, - kitConfiguration.defaultEventProjection - ) + val eventList = + CustomMapping.projectEvents( + builder.build(), + kitConfiguration.customMappingList, + kitConfiguration.defaultEventProjection, + ) Assert.assertEquals(1, eventList.size.toLong()) val projEvent1 = eventList[0].mpEvent Assert.assertEquals("account - check order status", projEvent1.eventName) Assert.assertEquals( "some value", - projEvent1.customAttributeStrings!!["attribute we don't care about"] + projEvent1.customAttributeStrings!!["attribute we don't care about"], ) } @@ -398,11 +445,12 @@ class CustomMappingTest { @Test @Throws(Exception::class) fun testMultiHashProjections2() { - val kitConfiguration = MockKitConfiguration.createKitConfiguration( - JSONObject( - "{\"id\":56, \"as\":{}, \"hs\":{}, \"pr\":[{\"id\":93, \"pmmid\":23, \"matches\":[{\"message_type\":4, \"event_match_type\":\"String\", \"event\":\"Product View\", \"attribute_key\":\"\$MethodName\", \"attribute_values\":\"\$ProductView\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"cool_product_view\"} }, {\"id\":89, \"matches\":[{\"message_type\":4, \"event_match_type\":\"\", \"event\":\"\"}], \"behavior\":{\"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{\"projected_event_name\":\"\", \"attribute_maps\":[] } }, {\"id\":100, \"pmid\":179, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":10, \"append_unmapped_as_is\":true }, \"action\":{\"projected_event_name\":\"account - check order status\", \"attribute_maps\":[] } }, {\"id\":92, \"pmid\":182, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"1111995177\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"account - feedback\", \"attribute_maps\":[{\"projected_attribute_name\":\"Feedback Type\", \"match_type\":\"Hash\", \"value\":\"-768380952\", \"data_type\":\"String\"} ] } }, {\"id\":96, \"pmid\":183, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - add to tote\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Add to Tote Name\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Print\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Category\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\", \"is_required\":true }, {\"projected_attribute_name\":\"Last Add to Tote Total Amount\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote SKU\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Size\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Quantity\", \"match_type\":\"Static\", \"value\":\"10\", \"data_type\":\"Int\"}, {\"projected_attribute_name\":\"Last Add to Tote Unit Price\", \"match_type\":\"Static\", \"value\":\"1321\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":184, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Complete the Look Product Name 2\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\", \"is_required\":true } ] } }, {\"id\":104, \"pmid\":185, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"987878094\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"689388774\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":186, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"-754932241\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"992037090\", \"data_type\":\"String\"} ] } } ] }" + val kitConfiguration = + MockKitConfiguration.createKitConfiguration( + JSONObject( + "{\"id\":56, \"as\":{}, \"hs\":{}, \"pr\":[{\"id\":93, \"pmmid\":23, \"matches\":[{\"message_type\":4, \"event_match_type\":\"String\", \"event\":\"Product View\", \"attribute_key\":\"\$MethodName\", \"attribute_values\":\"\$ProductView\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"cool_product_view\"} }, {\"id\":89, \"matches\":[{\"message_type\":4, \"event_match_type\":\"\", \"event\":\"\"}], \"behavior\":{\"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{\"projected_event_name\":\"\", \"attribute_maps\":[] } }, {\"id\":100, \"pmid\":179, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":10, \"append_unmapped_as_is\":true }, \"action\":{\"projected_event_name\":\"account - check order status\", \"attribute_maps\":[] } }, {\"id\":92, \"pmid\":182, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"1111995177\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"account - feedback\", \"attribute_maps\":[{\"projected_attribute_name\":\"Feedback Type\", \"match_type\":\"Hash\", \"value\":\"-768380952\", \"data_type\":\"String\"} ] } }, {\"id\":96, \"pmid\":183, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - add to tote\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Add to Tote Name\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Print\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Category\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\", \"is_required\":true }, {\"projected_attribute_name\":\"Last Add to Tote Total Amount\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote SKU\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Size\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Quantity\", \"match_type\":\"Static\", \"value\":\"10\", \"data_type\":\"Int\"}, {\"projected_attribute_name\":\"Last Add to Tote Unit Price\", \"match_type\":\"Static\", \"value\":\"1321\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":184, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Complete the Look Product Name 2\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\", \"is_required\":true } ] } }, {\"id\":104, \"pmid\":185, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"987878094\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"689388774\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":186, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"-754932241\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"992037090\", \"data_type\":\"String\"} ] } } ] }", + ), ) - ) val builder = MPEvent.Builder("sproj 1", MParticle.EventType.UserContent) val attributes: MutableMap = HashMap() attributes["attribute we don't care about"] = "some value" @@ -410,18 +458,19 @@ class CustomMappingTest { // add an attribute that's required by 1 of them, we should end up with 2 triggered projections attributes["Value"] = "product name" - val eventList = CustomMapping.projectEvents( - builder.build(), - kitConfiguration.customMappingList, - kitConfiguration.defaultEventProjection - ) + val eventList = + CustomMapping.projectEvents( + builder.build(), + kitConfiguration.customMappingList, + kitConfiguration.defaultEventProjection, + ) Assert.assertEquals(2, eventList.size.toLong()) var projEvent1 = eventList[0].mpEvent // same as test 1, but verify for the fun of it. Assert.assertEquals("account - check order status", projEvent1.eventName) Assert.assertEquals( "some value", - projEvent1.customAttributeStrings!!["attribute we don't care about"] + projEvent1.customAttributeStrings!!["attribute we don't care about"], ) // this is the new projection which requires the Value attribute @@ -430,23 +479,23 @@ class CustomMappingTest { // required attribute Assert.assertEquals( "product name", - projEvent1.customAttributeStrings!!["Last Add to Tote Category"] + projEvent1.customAttributeStrings!!["Last Add to Tote Category"], ) // the required attribute has been renamed // non-required attributes which define the same hash as the required one. Assert.assertEquals( "product name", - projEvent1.customAttributeStrings!!["Last Add to Tote Total Amount"] + projEvent1.customAttributeStrings!!["Last Add to Tote Total Amount"], ) Assert.assertEquals( "product name", - projEvent1.customAttributeStrings!!["Last Add to Tote SKU"] + projEvent1.customAttributeStrings!!["Last Add to Tote SKU"], ) // static attributes are in this projection as well. Assert.assertEquals("10", projEvent1.customAttributeStrings!!["Last Add to Tote Quantity"]) Assert.assertEquals( "1321", - projEvent1.customAttributeStrings!!["Last Add to Tote Unit Price"] + projEvent1.customAttributeStrings!!["Last Add to Tote Unit Price"], ) } @@ -460,11 +509,12 @@ class CustomMappingTest { @Test @Throws(Exception::class) fun testMultiHashProjections3() { - val kitConfiguration = MockKitConfiguration.createKitConfiguration( - JSONObject( - "{\"id\":56, \"as\":{}, \"hs\":{}, \"pr\":[{\"id\":93, \"pmmid\":23, \"matches\":[{\"message_type\":4, \"event_match_type\":\"String\", \"event\":\"Product View\", \"attribute_key\":\"\$MethodName\", \"attribute_values\":\"\$ProductView\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"cool_product_view\"} }, {\"id\":89, \"matches\":[{\"message_type\":4, \"event_match_type\":\"\", \"event\":\"\"}], \"behavior\":{\"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{\"projected_event_name\":\"\", \"attribute_maps\":[] } }, {\"id\":100, \"pmid\":179, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":10, \"append_unmapped_as_is\":true }, \"action\":{\"projected_event_name\":\"account - check order status\", \"attribute_maps\":[] } }, {\"id\":92, \"pmid\":182, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"1111995177\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"account - feedback\", \"attribute_maps\":[{\"projected_attribute_name\":\"Feedback Type\", \"match_type\":\"Hash\", \"value\":\"-768380952\", \"data_type\":\"String\"} ] } }, {\"id\":96, \"pmid\":183, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - add to tote\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Add to Tote Name\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Print\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Category\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\", \"is_required\":true }, {\"projected_attribute_name\":\"Last Add to Tote Total Amount\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote SKU\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Size\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Quantity\", \"match_type\":\"Static\", \"value\":\"10\", \"data_type\":\"Int\"}, {\"projected_attribute_name\":\"Last Add to Tote Unit Price\", \"match_type\":\"Static\", \"value\":\"1321\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":184, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Complete the Look Product Name 2\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\", \"is_required\":true } ] } }, {\"id\":104, \"pmid\":185, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"987878094\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"689388774\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":186, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"-754932241\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"992037090\", \"data_type\":\"String\"} ] } } ] }" + val kitConfiguration = + MockKitConfiguration.createKitConfiguration( + JSONObject( + "{\"id\":56, \"as\":{}, \"hs\":{}, \"pr\":[{\"id\":93, \"pmmid\":23, \"matches\":[{\"message_type\":4, \"event_match_type\":\"String\", \"event\":\"Product View\", \"attribute_key\":\"\$MethodName\", \"attribute_values\":\"\$ProductView\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"cool_product_view\"} }, {\"id\":89, \"matches\":[{\"message_type\":4, \"event_match_type\":\"\", \"event\":\"\"}], \"behavior\":{\"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{\"projected_event_name\":\"\", \"attribute_maps\":[] } }, {\"id\":100, \"pmid\":179, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":10, \"append_unmapped_as_is\":true }, \"action\":{\"projected_event_name\":\"account - check order status\", \"attribute_maps\":[] } }, {\"id\":92, \"pmid\":182, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"1111995177\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"account - feedback\", \"attribute_maps\":[{\"projected_attribute_name\":\"Feedback Type\", \"match_type\":\"Hash\", \"value\":\"-768380952\", \"data_type\":\"String\"} ] } }, {\"id\":96, \"pmid\":183, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - add to tote\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Add to Tote Name\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Print\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Category\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\", \"is_required\":true }, {\"projected_attribute_name\":\"Last Add to Tote Total Amount\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote SKU\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Size\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Last Add to Tote Quantity\", \"match_type\":\"Static\", \"value\":\"10\", \"data_type\":\"Int\"}, {\"projected_attribute_name\":\"Last Add to Tote Unit Price\", \"match_type\":\"Static\", \"value\":\"1321\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":184, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"178531468\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"111828069\", \"data_type\":\"String\"}, {\"projected_attribute_name\":\"Complete the Look Product Name 2\", \"match_type\":\"Hash\", \"value\":\"102582760\", \"data_type\":\"String\", \"is_required\":true } ] } }, {\"id\":104, \"pmid\":185, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"987878094\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"689388774\", \"data_type\":\"String\"} ] } }, {\"id\":104, \"pmid\":186, \"matches\":[{\"message_type\":4, \"event_match_type\":\"Hash\", \"event\":\"-754932241\"}], \"behavior\":{\"max_custom_params\":0 }, \"action\":{\"projected_event_name\":\"pdp - complete the look\", \"attribute_maps\":[{\"projected_attribute_name\":\"Complete the Look Product Name\", \"match_type\":\"Hash\", \"value\":\"992037090\", \"data_type\":\"String\"} ] } } ] }", + ), ) - ) val builder = MPEvent.Builder("sproj 1", MParticle.EventType.UserContent) val attributes: MutableMap = HashMap() attributes["attribute we don't care about"] = "some value" @@ -478,46 +528,47 @@ class CustomMappingTest { * defines that attribute as non-required. */ attributes["Label"] = "product label" - val eventList = CustomMapping.projectEvents( - builder.build(), - kitConfiguration.customMappingList, - kitConfiguration.defaultEventProjection - ) + val eventList = + CustomMapping.projectEvents( + builder.build(), + kitConfiguration.customMappingList, + kitConfiguration.defaultEventProjection, + ) Assert.assertEquals(3, eventList.size.toLong()) var projEvent1 = eventList[0].mpEvent Assert.assertEquals("account - check order status", projEvent1.eventName) Assert.assertEquals( "some value", - projEvent1.customAttributeStrings!!["attribute we don't care about"] + projEvent1.customAttributeStrings!!["attribute we don't care about"], ) projEvent1 = eventList[1].mpEvent Assert.assertEquals("pdp - add to tote", projEvent1.eventName) Assert.assertEquals( "product name", - projEvent1.customAttributeStrings!!["Last Add to Tote Category"] + projEvent1.customAttributeStrings!!["Last Add to Tote Category"], ) Assert.assertEquals( "product name", - projEvent1.customAttributeStrings!!["Last Add to Tote Total Amount"] + projEvent1.customAttributeStrings!!["Last Add to Tote Total Amount"], ) Assert.assertEquals( "product name", - projEvent1.customAttributeStrings!!["Last Add to Tote SKU"] + projEvent1.customAttributeStrings!!["Last Add to Tote SKU"], ) Assert.assertEquals("10", projEvent1.customAttributeStrings!!["Last Add to Tote Quantity"]) Assert.assertEquals( "1321", - projEvent1.customAttributeStrings!!["Last Add to Tote Unit Price"] + projEvent1.customAttributeStrings!!["Last Add to Tote Unit Price"], ) // these are new for the 2nd projection, as they match the Hash for the new "Label" attribute Assert.assertEquals( "product label", - projEvent1.customAttributeStrings!!["Last Add to Tote Name"] + projEvent1.customAttributeStrings!!["Last Add to Tote Name"], ) Assert.assertEquals( "product label", - projEvent1.customAttributeStrings!!["Last Add to Tote Print"] + projEvent1.customAttributeStrings!!["Last Add to Tote Print"], ) // and here's our 3rd projection, which defines both the original "Value" attribute hash as well as "Label" @@ -525,11 +576,11 @@ class CustomMappingTest { Assert.assertEquals("pdp - complete the look", projEvent1.eventName) Assert.assertEquals( "product name", - projEvent1.customAttributeStrings!!["Complete the Look Product Name"] + projEvent1.customAttributeStrings!!["Complete the Look Product Name"], ) Assert.assertEquals( "product label", - projEvent1.customAttributeStrings!!["Complete the Look Product Name 2"] + projEvent1.customAttributeStrings!!["Complete the Look Product Name 2"], ) } @@ -550,15 +601,22 @@ class CustomMappingTest { "{\"id\":93, \"pmid\":220, \"matches\":[{\"message_type\":16, \"event_match_type\":\"Hash\", \"event\":\"1572\"}], \"behavior\":{\"max_custom_params\":0, \"selector\":\"foreach\"}, \"action\":{\"projected_event_name\":\"pdp - product view\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Product View Category\", \"match_type\":\"Hash\", \"value\":\"2000445218\", \"data_type\":\"String\", \"property\":\"ProductField\"}, {\"projected_attribute_name\":\"Last Product View Currency\", \"match_type\":\"Hash\", \"value\":\"881337592\", \"data_type\":\"String\", \"property\":\"EventField\"}, {\"projected_attribute_name\":\"Last Product View SKU\", \"match_type\":\"Hash\", \"value\":\"1514047\", \"data_type\":\"String\", \"property\":\"ProductField\"}, {\"projected_attribute_name\":\"Last Product View Name\", \"match_type\":\"Hash\", \"value\":\"1455148719\", \"data_type\":\"String\", \"property\":\"ProductField\"}, {\"projected_attribute_name\":\"Last Product View Quantity\", \"match_type\":\"Hash\", \"value\":\"664929967\", \"data_type\":\"Int\", \"property\":\"ProductField\"}, {\"projected_attribute_name\":\"Last Product View Total Amount\", \"match_type\":\"Hash\", \"value\":\"1647761705\", \"data_type\":\"String\", \"property\":\"ProductField\"} ], \"outbound_message_type\":4 } }" val customMapping = CustomMapping(JSONObject(config)) val productBuilder = - Product.Builder("product name 0", "product id 0", 1.0).category("product category 0") + Product + .Builder("product name 0", "product id 0", 1.0) + .category("product category 0") .quantity(1.0) val commerceEventBuilder = CommerceEvent.Builder(Product.DETAIL, productBuilder.build()).currency("dollar bills") for (i in 1..4) { commerceEventBuilder.addProduct( - productBuilder.name("product name $i").sku("product id $i").category( - "product category $i" - ).quantity((i + 1).toDouble()).unitPrice((i + 1).toDouble()).build() + productBuilder + .name("product name $i") + .sku("product id $i") + .category( + "product category $i", + ).quantity((i + 1).toDouble()) + .unitPrice((i + 1).toDouble()) + .build(), ) } val commerceEvent = commerceEventBuilder.build() @@ -576,11 +634,11 @@ class CustomMappingTest { Assert.assertEquals("product name $i", attributes["Last Product View Name"]) Assert.assertEquals( i.plus(1).toString() + ".0", - attributes["Last Product View Quantity"] + attributes["Last Product View Quantity"], ) Assert.assertEquals( ((i + 1) * (i + 1)).toString() + ".0", - attributes["Last Product View Total Amount"] + attributes["Last Product View Total Amount"], ) Assert.assertEquals("pdp - product view", event.eventName) } @@ -591,108 +649,149 @@ class CustomMappingTest { fun testMatchCommerceEventType() { val product = Product.Builder("name", "sku", 0.0).build() val config = - JSONObject("{\"id\":99, \"pmid\":229, \"matches\":[{\"message_type\":16, \"event_match_type\":\"Hash\", \"event\":\"1569\", }], \"behavior\":{\"max_custom_params\":0, \"selector\":\"last\"}, \"action\":{\"projected_event_name\":\"checkout - place order\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Place Order Category\", \"match_type\":\"Hash\", \"value\":\"-1167125985\", \"data_type\":\"String\", \"property\":\"ProductField\"} ], \"outbound_message_type\":16 } }") - var event = CommerceEvent.Builder(Product.DETAIL, product) - .transactionAttributes(TransactionAttributes().setId("id")).build() + JSONObject( + "{\"id\":99, \"pmid\":229, \"matches\":[{\"message_type\":16, \"event_match_type\":\"Hash\", \"event\":\"1569\", }], \"behavior\":{\"max_custom_params\":0, \"selector\":\"last\"}, \"action\":{\"projected_event_name\":\"checkout - place order\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Place Order Category\", \"match_type\":\"Hash\", \"value\":\"-1167125985\", \"data_type\":\"String\", \"property\":\"ProductField\"} ], \"outbound_message_type\":16 } }", + ) + var event = + CommerceEvent + .Builder(Product.DETAIL, product) + .transactionAttributes(TransactionAttributes().setId("id")) + .build() config.getJSONArray("matches").getJSONObject(0).put( "event", - "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)) + "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)), ) var customMapping = CustomMapping(config) Assert.assertTrue(customMapping.isMatch(CommerceEventWrapper(event))) - event = CommerceEvent.Builder(Product.ADD_TO_CART, product) - .transactionAttributes(TransactionAttributes().setId("id")).build() + event = + CommerceEvent + .Builder(Product.ADD_TO_CART, product) + .transactionAttributes(TransactionAttributes().setId("id")) + .build() config.getJSONArray("matches").getJSONObject(0).put( "event", - "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)) + "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)), ) customMapping = CustomMapping(config) Assert.assertTrue(customMapping.isMatch(CommerceEventWrapper(event))) - event = CommerceEvent.Builder(Product.PURCHASE, product) - .transactionAttributes(TransactionAttributes().setId("id")).build() + event = + CommerceEvent + .Builder(Product.PURCHASE, product) + .transactionAttributes(TransactionAttributes().setId("id")) + .build() config.getJSONArray("matches").getJSONObject(0).put( "event", - "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)) + "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)), ) customMapping = CustomMapping(config) Assert.assertTrue(customMapping.isMatch(CommerceEventWrapper(event))) - event = CommerceEvent.Builder(Product.ADD_TO_WISHLIST, product) - .transactionAttributes(TransactionAttributes().setId("id")).build() + event = + CommerceEvent + .Builder(Product.ADD_TO_WISHLIST, product) + .transactionAttributes(TransactionAttributes().setId("id")) + .build() config.getJSONArray("matches").getJSONObject(0).put( "event", - "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)) + "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)), ) customMapping = CustomMapping(config) Assert.assertTrue(customMapping.isMatch(CommerceEventWrapper(event))) - event = CommerceEvent.Builder(Product.CHECKOUT, product) - .transactionAttributes(TransactionAttributes().setId("id")).build() + event = + CommerceEvent + .Builder(Product.CHECKOUT, product) + .transactionAttributes(TransactionAttributes().setId("id")) + .build() config.getJSONArray("matches").getJSONObject(0).put( "event", - "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)) + "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)), ) customMapping = CustomMapping(config) Assert.assertTrue(customMapping.isMatch(CommerceEventWrapper(event))) - event = CommerceEvent.Builder(Product.CHECKOUT_OPTION, product) - .transactionAttributes(TransactionAttributes().setId("id")).build() + event = + CommerceEvent + .Builder(Product.CHECKOUT_OPTION, product) + .transactionAttributes(TransactionAttributes().setId("id")) + .build() config.getJSONArray("matches").getJSONObject(0).put( "event", - "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)) + "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)), ) customMapping = CustomMapping(config) Assert.assertTrue(customMapping.isMatch(CommerceEventWrapper(event))) - event = CommerceEvent.Builder(Product.CLICK, product) - .transactionAttributes(TransactionAttributes().setId("id")).build() + event = + CommerceEvent + .Builder(Product.CLICK, product) + .transactionAttributes(TransactionAttributes().setId("id")) + .build() config.getJSONArray("matches").getJSONObject(0).put( "event", - "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)) + "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)), ) customMapping = CustomMapping(config) Assert.assertTrue(customMapping.isMatch(CommerceEventWrapper(event))) - event = CommerceEvent.Builder(Product.REFUND, product) - .transactionAttributes(TransactionAttributes().setId("id")).build() + event = + CommerceEvent + .Builder(Product.REFUND, product) + .transactionAttributes(TransactionAttributes().setId("id")) + .build() config.getJSONArray("matches").getJSONObject(0).put( "event", - "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)) + "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)), ) customMapping = CustomMapping(config) Assert.assertTrue(customMapping.isMatch(CommerceEventWrapper(event))) - event = CommerceEvent.Builder(Product.REMOVE_FROM_CART, product) - .transactionAttributes(TransactionAttributes().setId("id")).build() + event = + CommerceEvent + .Builder(Product.REMOVE_FROM_CART, product) + .transactionAttributes(TransactionAttributes().setId("id")) + .build() config.getJSONArray("matches").getJSONObject(0).put( "event", - "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)) + "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)), ) customMapping = CustomMapping(config) Assert.assertTrue(customMapping.isMatch(CommerceEventWrapper(event))) - event = CommerceEvent.Builder(Product.REMOVE_FROM_WISHLIST, product) - .transactionAttributes(TransactionAttributes().setId("id")).build() + event = + CommerceEvent + .Builder(Product.REMOVE_FROM_WISHLIST, product) + .transactionAttributes(TransactionAttributes().setId("id")) + .build() config.getJSONArray("matches").getJSONObject(0).put( "event", - "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)) + "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)), ) customMapping = CustomMapping(config) Assert.assertTrue(customMapping.isMatch(CommerceEventWrapper(event))) - event = CommerceEvent.Builder(Impression("list name", product)) - .transactionAttributes(TransactionAttributes().setId("id")).build() + event = + CommerceEvent + .Builder(Impression("list name", product)) + .transactionAttributes(TransactionAttributes().setId("id")) + .build() config.getJSONArray("matches").getJSONObject(0).put( "event", - "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)) + "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)), ) customMapping = CustomMapping(config) Assert.assertTrue(customMapping.isMatch(CommerceEventWrapper(event))) - event = CommerceEvent.Builder(Promotion.VIEW, Promotion().setId("id")) - .transactionAttributes(TransactionAttributes().setId("id")).build() + event = + CommerceEvent + .Builder(Promotion.VIEW, Promotion().setId("id")) + .transactionAttributes(TransactionAttributes().setId("id")) + .build() config.getJSONArray("matches").getJSONObject(0).put( "event", - "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)) + "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)), ) customMapping = CustomMapping(config) Assert.assertTrue(customMapping.isMatch(CommerceEventWrapper(event))) - event = CommerceEvent.Builder(Promotion.CLICK, Promotion().setId("id")) - .transactionAttributes(TransactionAttributes().setId("id")).build() + event = + CommerceEvent + .Builder(Promotion.CLICK, Promotion().setId("id")) + .transactionAttributes(TransactionAttributes().setId("id")) + .build() config.getJSONArray("matches").getJSONObject(0).put( "event", - "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)) + "" + KitUtils.hashForFiltering("" + CommerceEventUtils.getEventType(event)), ) customMapping = CustomMapping(config) Assert.assertTrue(customMapping.isMatch(CommerceEventWrapper(event))) @@ -713,7 +812,9 @@ class CustomMappingTest { @Throws(Exception::class) fun testMatchCommerceEventProperty() { val config = - JSONObject("{\"id\":99, \"pmid\":229, \"matches\":[{\"message_type\":16, \"event_match_type\":\"Hash\", \"event\":\"1569\", \"property\":\"EventField\", \"property_name\":\"-601244443\", \"property_values\":[\"5\"]}], \"behavior\":{\"max_custom_params\":0, \"selector\":\"last\"}, \"action\":{\"projected_event_name\":\"checkout - place order\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Place Order Category\", \"match_type\":\"Hash\", \"value\":\"-1167125985\", \"data_type\":\"String\", \"property\":\"ProductField\"} ], \"outbound_message_type\":16 } }") + JSONObject( + "{\"id\":99, \"pmid\":229, \"matches\":[{\"message_type\":16, \"event_match_type\":\"Hash\", \"event\":\"1569\", \"property\":\"EventField\", \"property_name\":\"-601244443\", \"property_values\":[\"5\"]}], \"behavior\":{\"max_custom_params\":0, \"selector\":\"last\"}, \"action\":{\"projected_event_name\":\"checkout - place order\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Place Order Category\", \"match_type\":\"Hash\", \"value\":\"-1167125985\", \"data_type\":\"String\", \"property\":\"ProductField\"} ], \"outbound_message_type\":16 } }", + ) var customMapping = CustomMapping(config) val product = Product.Builder("name", "sku", 0.0).build() var commerceEvent = CommerceEvent.Builder(Product.CHECKOUT, product).checkoutStep(4).build() @@ -731,48 +832,73 @@ class CustomMappingTest { config.getJSONArray("matches").getJSONObject(0).put("property", "ProductAttribute") customMapping = CustomMapping(config) Assert.assertFalse(customMapping.isMatch(CommerceEventWrapper(commerceEvent))) - commerceEvent = CommerceEvent.Builder(Product.CHECKOUT, product) - .addProduct(Product.Builder("name 2", "sku", 0.0).customAttributes(attributes).build()) - .build() + commerceEvent = + CommerceEvent + .Builder(Product.CHECKOUT, product) + .addProduct(Product.Builder("name 2", "sku", 0.0).customAttributes(attributes).build()) + .build() var wrapper = CommerceEventWrapper(commerceEvent) Assert.assertTrue(customMapping.isMatch(wrapper)) // only 1 product has the required attribute so there should only be 1 product after the matching step - Assert.assertEquals(1, wrapper.event.products!!.size.toLong()) + Assert.assertEquals( + 1, + wrapper.event.products!! + .size + .toLong(), + ) Assert.assertEquals("name 2", wrapper.event.products!![0].name) config.getJSONArray("matches").getJSONObject(0).put("property", "ProductField") - config.getJSONArray("matches").getJSONObject(0) + config + .getJSONArray("matches") + .getJSONObject(0) .put("property_name", "-1167125985") // checkout + category hash var values = JSONArray() values.put("some product cat") config.getJSONArray("matches").getJSONObject(0).put("property_values", values) customMapping = CustomMapping(config) Assert.assertFalse(customMapping.isMatch(CommerceEventWrapper(commerceEvent))) - commerceEvent = CommerceEvent.Builder(Product.CHECKOUT, product) - .addProduct(Product.Builder("name 2", "sku", 0.0).category("some product cat").build()) - .build() + commerceEvent = + CommerceEvent + .Builder(Product.CHECKOUT, product) + .addProduct(Product.Builder("name 2", "sku", 0.0).category("some product cat").build()) + .build() wrapper = CommerceEventWrapper(commerceEvent) Assert.assertTrue(customMapping.isMatch(wrapper)) // only 1 product has the required attribute so there should only be 1 product after the matching step - Assert.assertEquals(1, wrapper.event.products!!.size.toLong()) + Assert.assertEquals( + 1, + wrapper.event.products!! + .size + .toLong(), + ) Assert.assertEquals("some product cat", wrapper.event.products!![0].category) config.getJSONArray("matches").getJSONObject(0).put("property", "PromotionField") - config.getJSONArray("matches").getJSONObject(0) + config + .getJSONArray("matches") + .getJSONObject(0) .put("property_name", "835505623") // click + creative hash values = JSONArray() values.put("some promotion creative") config.getJSONArray("matches").getJSONObject(0).put("property_values", values) customMapping = CustomMapping(config) Assert.assertFalse(customMapping.isMatch(CommerceEventWrapper(commerceEvent))) - commerceEvent = CommerceEvent.Builder( - Promotion.CLICK, - Promotion().setCreative("some promotion creative") - ).addPromotion( - Promotion().setCreative("some other creative") - ).build() + commerceEvent = + CommerceEvent + .Builder( + Promotion.CLICK, + Promotion().setCreative("some promotion creative"), + ).addPromotion( + Promotion().setCreative("some other creative"), + ).build() wrapper = CommerceEventWrapper(commerceEvent) Assert.assertTrue(customMapping.isMatch(wrapper)) // only 1 promotion has the required attribute so there should only be 1 promotion after the matching step - Assert.assertEquals(1, wrapper.event.promotions!!.size.toLong()) + Assert.assertEquals( + 1, + wrapper.event.promotions!! + .size + .toLong(), + ) Assert.assertEquals("some promotion creative", wrapper.event.promotions!![0].creative) } @@ -791,59 +917,81 @@ class CustomMappingTest { @Test @Throws(Exception::class) fun testCommerceEventToCommerceEvent() { - val config = JSONObject( - "{\"id\":99, \"pmid\":229, \"matches\":[{\"message_type\":16, \"event_match_type\":\"Hash\", \"event\":\"1569\", \"property\":\"EventField\", \"property_name\":\"-601244443\", \"property_values\":[\"5\", \"7\"]}], \"behavior\":{\"max_custom_params\":0, \"selector\":\"last\"}, \"action\":{\"projected_event_name\":\"checkout - place order\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Place Order Category\", \"match_type\":\"Hash\", \"value\":\"-1167125985\", \"data_type\":\"String\", \"property\":\"ProductField\"}, {\"projected_attribute_name\":\"Projected sample custom attribute\", \"match_type\":\"Hash\", \"value\":\"153565474\", \"data_type\":\"String\", \"property\":\"ProductAttribute\"}, {\"projected_attribute_name\":\"Projected list source\", \"match_type\":\"Hash\", \"value\":\"-882952085\", \"data_type\":\"String\", \"property\":\"EventField\"}, {\"projected_attribute_name\":\"Projected sample event attribute\", \"match_type\":\"Hash\", \"value\":\"1957440897\", \"data_type\":\"String\", \"property\":\"EventAttribute\"} ], \"outbound_message_type\":16 } }" - ) + val config = + JSONObject( + "{\"id\":99, \"pmid\":229, \"matches\":[{\"message_type\":16, \"event_match_type\":\"Hash\", \"event\":\"1569\", \"property\":\"EventField\", \"property_name\":\"-601244443\", \"property_values\":[\"5\", \"7\"]}], \"behavior\":{\"max_custom_params\":0, \"selector\":\"last\"}, \"action\":{\"projected_event_name\":\"checkout - place order\", \"attribute_maps\":[{\"projected_attribute_name\":\"Last Place Order Category\", \"match_type\":\"Hash\", \"value\":\"-1167125985\", \"data_type\":\"String\", \"property\":\"ProductField\"}, {\"projected_attribute_name\":\"Projected sample custom attribute\", \"match_type\":\"Hash\", \"value\":\"153565474\", \"data_type\":\"String\", \"property\":\"ProductAttribute\"}, {\"projected_attribute_name\":\"Projected list source\", \"match_type\":\"Hash\", \"value\":\"-882952085\", \"data_type\":\"String\", \"property\":\"EventField\"}, {\"projected_attribute_name\":\"Projected sample event attribute\", \"match_type\":\"Hash\", \"value\":\"1957440897\", \"data_type\":\"String\", \"property\":\"EventAttribute\"} ], \"outbound_message_type\":16 } }", + ) val customMapping = CustomMapping(config) val product = Product.Builder("name", "sku", 0.0).category("category 0").build() val productAttributes: MutableMap = HashMap() productAttributes["sample custom attribute"] = "sample custom product attribute value" val eventAttributes: MutableMap = HashMap() eventAttributes["sample event attribute"] = "sample custom event value" - var commerceEvent = CommerceEvent.Builder(Product.CHECKOUT, product) - .addProduct( - Product.Builder("name 1", "sku", 0.0).category("category 1") - .customAttributes(productAttributes).build() - ) - .addProduct( - Product.Builder("name 2", "sku", 0.0).category("category 2") - .customAttributes(productAttributes).build() - ) - .addProduct(Product.Builder("name 3", "sku", 0.0).category("category 3").build()) - .addProduct(Product.Builder("name 4", "sku", 0.0).category("category 4").build()) - .productListSource("some product list source") - .customAttributes(eventAttributes) - .checkoutStep(4).build() + var commerceEvent = + CommerceEvent + .Builder(Product.CHECKOUT, product) + .addProduct( + Product + .Builder("name 1", "sku", 0.0) + .category("category 1") + .customAttributes(productAttributes) + .build(), + ).addProduct( + Product + .Builder("name 2", "sku", 0.0) + .category("category 2") + .customAttributes(productAttributes) + .build(), + ).addProduct(Product.Builder("name 3", "sku", 0.0).category("category 3").build()) + .addProduct(Product.Builder("name 4", "sku", 0.0).category("category 4").build()) + .productListSource("some product list source") + .customAttributes(eventAttributes) + .checkoutStep(4) + .build() Assert.assertFalse(customMapping.isMatch(CommerceEventWrapper(commerceEvent))) - commerceEvent = CommerceEvent.Builder(Product.CHECKOUT, product) - .addProduct( - Product.Builder("name 1", "sku", 0.0).category("category 1") - .customAttributes(productAttributes).build() - ) - .addProduct( - Product.Builder("name 2", "sku", 0.0).category("category 2") - .customAttributes(productAttributes).build() - ) - .addProduct(Product.Builder("name 3", "sku", 0.0).category("category 3").build()) - .addProduct(Product.Builder("name 4", "sku", 0.0).category("category 4").build()) - .productListSource("some product list source") - .customAttributes(eventAttributes) - .checkoutStep(5).build() + commerceEvent = + CommerceEvent + .Builder(Product.CHECKOUT, product) + .addProduct( + Product + .Builder("name 1", "sku", 0.0) + .category("category 1") + .customAttributes(productAttributes) + .build(), + ).addProduct( + Product + .Builder("name 2", "sku", 0.0) + .category("category 2") + .customAttributes(productAttributes) + .build(), + ).addProduct(Product.Builder("name 3", "sku", 0.0).category("category 3").build()) + .addProduct(Product.Builder("name 4", "sku", 0.0).category("category 4").build()) + .productListSource("some product list source") + .customAttributes(eventAttributes) + .checkoutStep(5) + .build() Assert.assertTrue(customMapping.isMatch(CommerceEventWrapper(commerceEvent))) - commerceEvent = CommerceEvent.Builder(Product.CHECKOUT, product) - .addProduct( - Product.Builder("name 1", "sku", 0.0).category("category 1") - .customAttributes(productAttributes).build() - ) - .addProduct( - Product.Builder("name 2", "sku", 0.0).category("category 2") - .customAttributes(productAttributes).build() - ) - .addProduct(Product.Builder("name 3", "sku", 0.0).category("category 3").build()) - .addProduct(Product.Builder("name 4", "sku", 0.0).category("category 4").build()) - .productListSource("some product list source") - .customAttributes(eventAttributes) - .checkoutStep(7).build() + commerceEvent = + CommerceEvent + .Builder(Product.CHECKOUT, product) + .addProduct( + Product + .Builder("name 1", "sku", 0.0) + .category("category 1") + .customAttributes(productAttributes) + .build(), + ).addProduct( + Product + .Builder("name 2", "sku", 0.0) + .category("category 2") + .customAttributes(productAttributes) + .build(), + ).addProduct(Product.Builder("name 3", "sku", 0.0).category("category 3").build()) + .addProduct(Product.Builder("name 4", "sku", 0.0).category("category 4").build()) + .productListSource("some product list source") + .customAttributes(eventAttributes) + .checkoutStep(7) + .build() Assert.assertTrue(customMapping.isMatch(CommerceEventWrapper(commerceEvent))) var result = customMapping.project(CommerceEventWrapper(commerceEvent)) Assert.assertEquals(1, result.size.toLong()) @@ -854,15 +1002,15 @@ class CustomMappingTest { Assert.assertEquals(5, event.products!!.size.toLong()) Assert.assertEquals( "category 4", - event.customAttributeStrings!!["Last Place Order Category"] + event.customAttributeStrings!!["Last Place Order Category"], ) Assert.assertEquals( "some product list source", - event.customAttributeStrings!!["Projected list source"] + event.customAttributeStrings!!["Projected list source"], ) Assert.assertEquals( "sample custom event value", - event.customAttributeStrings!!["Projected sample event attribute"] + event.customAttributeStrings!!["Projected sample event attribute"], ) config.getJSONObject("behavior").put("selector", "foreach") result = CustomMapping(config).project(CommerceEventWrapper(commerceEvent)) @@ -874,27 +1022,30 @@ class CustomMappingTest { Assert.assertEquals(1, event1.products!!.size.toLong()) Assert.assertEquals( "some product list source", - event1.customAttributeStrings!!["Projected list source"] + event1.customAttributeStrings!!["Projected list source"], ) Assert.assertEquals( "sample custom event value", - event1.customAttributeStrings!!["Projected sample event attribute"] + event1.customAttributeStrings!!["Projected sample event attribute"], ) if (i == 1 || i == 2) { Assert.assertEquals( "sample custom product attribute value", - event1.customAttributeStrings!!["Projected sample custom attribute"] + event1.customAttributeStrings!!["Projected sample custom attribute"], ) } Assert.assertNotNull(event1) Assert.assertEquals( "category $i", - event1.customAttributeStrings!!["Last Place Order Category"] + event1.customAttributeStrings!!["Last Place Order Category"], ) } // make the ProductAttribute mapping required, should limit down the results to 2 products - config.getJSONObject("action").getJSONArray("attribute_maps").getJSONObject(1) + config + .getJSONObject("action") + .getJSONArray("attribute_maps") + .getJSONObject(1) .put("is_required", "true") result = CustomMapping(config).project(CommerceEventWrapper(commerceEvent)) Assert.assertEquals(2, result.size.toLong()) @@ -918,16 +1069,21 @@ class CustomMappingTest { val name = "product_1" val sku = "sku_12345" val quantity = 3f - val kitConfiguration = MockKitConfiguration.createKitConfiguration( - JSONObject( - "{ \"id\":92, \"as\":{ \"devKey\":\"HXpL4jHPTkUzwmcrJJFV9k\", \"appleAppId\":null }, \"hs\":{ }, \"pr\":[ { \"id\":166, \"behavior\":{ \"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ ], \"outbound_message_type\":4 }, \"matches\":[ { \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" } ] }, { \"id\":157, \"pmid\":540, \"behavior\":{ \"append_unmapped_as_is\":true }, \"action\":{ \"projected_event_name\":\"$cmEventName\", \"attribute_maps\":[ { \"projected_attribute_name\":\"$cmProductName\", \"match_type\":\"Hash\", \"value\":\"1455148719\", \"data_type\":\"String\", \"property\":\"ProductField\" }, { \"projected_attribute_name\":\"$cmQuantityName\", \"match_type\":\"Hash\", \"value\":\"1817448224\", \"data_type\":\"Float\", \"property\":\"ProductField\" }, { \"projected_attribute_name\":\"$cmCurrencyName\", \"match_type\":\"Static\", \"value\":\"$cmStaticCurrency\", \"data_type\":\"String\" } ], \"outbound_message_type\":4 }, \"matches\":[ { \"message_type\":16, \"event_match_type\":\"Hash\", \"event\":\"1572\" } ] } ] }" + val kitConfiguration = + MockKitConfiguration.createKitConfiguration( + JSONObject( + "{ \"id\":92, \"as\":{ \"devKey\":\"HXpL4jHPTkUzwmcrJJFV9k\", \"appleAppId\":null }, \"hs\":{ }, \"pr\":[ { \"id\":166, \"behavior\":{ \"append_unmapped_as_is\":true, \"is_default\":true }, \"action\":{ \"projected_event_name\":\"\", \"attribute_maps\":[ ], \"outbound_message_type\":4 }, \"matches\":[ { \"message_type\":4, \"event_match_type\":\"\", \"event\":\"\" } ] }, { \"id\":157, \"pmid\":540, \"behavior\":{ \"append_unmapped_as_is\":true }, \"action\":{ \"projected_event_name\":\"$cmEventName\", \"attribute_maps\":[ { \"projected_attribute_name\":\"$cmProductName\", \"match_type\":\"Hash\", \"value\":\"1455148719\", \"data_type\":\"String\", \"property\":\"ProductField\" }, { \"projected_attribute_name\":\"$cmQuantityName\", \"match_type\":\"Hash\", \"value\":\"1817448224\", \"data_type\":\"Float\", \"property\":\"ProductField\" }, { \"projected_attribute_name\":\"$cmCurrencyName\", \"match_type\":\"Static\", \"value\":\"$cmStaticCurrency\", \"data_type\":\"String\" } ], \"outbound_message_type\":4 }, \"matches\":[ { \"message_type\":16, \"event_match_type\":\"Hash\", \"event\":\"1572\" } ] } ] }", + ), ) - ) - val product = Product.Builder(name, sku, quantity.toDouble()) - .build() - val commerceEvent = CommerceEvent.Builder(Product.DETAIL, product) - .customAttributes(customAttributes) - .build() + val product = + Product + .Builder(name, sku, quantity.toDouble()) + .build() + val commerceEvent = + CommerceEvent + .Builder(Product.DETAIL, product) + .customAttributes(customAttributes) + .build() val results = CustomMapping.projectEvents(commerceEvent, kitConfiguration.customMappingList, null) val expectedInfo: MutableMap = HashMap() @@ -935,15 +1091,19 @@ class CustomMappingTest { expectedInfo[cmProductName] = name expectedInfo[cmCurrencyName] = cmStaticCurrency expectedInfo.putAll(customAttributes) - val expectedMappedEvent = MPEvent.Builder(cmEventName) - .customAttributes(expectedInfo) - .build() + val expectedMappedEvent = + MPEvent + .Builder(cmEventName) + .customAttributes(expectedInfo) + .build() Assert.assertEquals(1, results.size.toLong()) val result = results[0].mpEvent Assert.assertEquals(expectedMappedEvent.eventName, result.eventName) Assert.assertEquals( - expectedMappedEvent.customAttributeStrings!!.keys.size.toLong(), - result.customAttributeStrings!!.size.toLong() + expectedMappedEvent.customAttributeStrings!! + .keys.size + .toLong(), + result.customAttributeStrings!!.size.toLong(), ) for (key in expectedMappedEvent.customAttributeStrings!!.keys) { val `val` = result.customAttributeStrings!![key] @@ -956,7 +1116,9 @@ class CustomMappingTest { @Throws(Exception::class) fun testSingleBasicMatch() { val config = - JSONObject("{ \"id\":144, \"pmmid\":24, \"behavior\":{ \"append_unmapped_as_is\":true }, \"action\":{ \"projected_event_name\":\"new_premium_subscriber\", \"attribute_maps\":[ ], \"outbound_message_type\":4 }, \"matches\":[ { \"message_type\":4, \"event_match_type\":\"String\", \"event\":\"subscription_success\", \"attribute_key\":\"plan\", \"attribute_values\":[ \"premium\" ] } ] }") + JSONObject( + "{ \"id\":144, \"pmmid\":24, \"behavior\":{ \"append_unmapped_as_is\":true }, \"action\":{ \"projected_event_name\":\"new_premium_subscriber\", \"attribute_maps\":[ ], \"outbound_message_type\":4 }, \"matches\":[ { \"message_type\":4, \"event_match_type\":\"String\", \"event\":\"subscription_success\", \"attribute_key\":\"plan\", \"attribute_values\":[ \"premium\" ] } ] }", + ) val mapping = CustomMapping(config) val info: MutableMap = HashMap() info["plan"] = "premium" @@ -977,7 +1139,9 @@ class CustomMappingTest { @Throws(Exception::class) fun testORingAttributeValues() { val config = - JSONObject("{ \"id\":167, \"pmmid\":26, \"behavior\":{ \"append_unmapped_as_is\":true }, \"action\":{ \"projected_event_name\":\"X_FIRST_APP_OPEN\", \"attribute_maps\":[ ], \"outbound_message_type\":4 }, \"matches\":[ { \"message_type\":4, \"event_match_type\":\"String\", \"event\":\"APPLICATION_START\", \"attribute_key\":\"has_launched_before\", \"attribute_values\":[ \"false\", \"N\" ] } ] }") + JSONObject( + "{ \"id\":167, \"pmmid\":26, \"behavior\":{ \"append_unmapped_as_is\":true }, \"action\":{ \"projected_event_name\":\"X_FIRST_APP_OPEN\", \"attribute_maps\":[ ], \"outbound_message_type\":4 }, \"matches\":[ { \"message_type\":4, \"event_match_type\":\"String\", \"event\":\"APPLICATION_START\", \"attribute_key\":\"has_launched_before\", \"attribute_values\":[ \"false\", \"N\" ] } ] }", + ) val mapping = CustomMapping(config) val info: MutableMap = HashMap() info["has_launched_before"] = "Y" @@ -990,7 +1154,7 @@ class CustomMappingTest { event = MPEvent.Builder("APPLICATION_START").customAttributes(info).build() Assert.assertTrue( mapping.matchList[0].attributeValues.toString(), - mapping.isMatch(MPEventWrapper(event)) + mapping.isMatch(MPEventWrapper(event)), ) } @@ -998,7 +1162,9 @@ class CustomMappingTest { @Throws(Exception::class) fun testANDingMatchedeMatches() { val config = - JSONObject("{ \"id\":171, \"pmmid\":30, \"behavior\":{ \"append_unmapped_as_is\":true }, \"action\":{ \"projected_event_name\":\"X_NEW_NOAH_SUBSCRIPTION\", \"attribute_maps\":[ ], \"outbound_message_type\":4 }, \"matches\":[ { \"message_type\":4, \"event_match_type\":\"String\", \"event\":\"SUBSCRIPTION_END\", \"attribute_key\":\"outcome\", \"attribute_values\":[ \"new_subscription\" ] }, { \"message_type\":4, \"event_match_type\":\"String\", \"event\":\"SUBSCRIPTION_END\", \"attribute_key\":\"plan_id\", \"attribute_values\":[ \"3\", \"8\" ] } ] }") + JSONObject( + "{ \"id\":171, \"pmmid\":30, \"behavior\":{ \"append_unmapped_as_is\":true }, \"action\":{ \"projected_event_name\":\"X_NEW_NOAH_SUBSCRIPTION\", \"attribute_maps\":[ ], \"outbound_message_type\":4 }, \"matches\":[ { \"message_type\":4, \"event_match_type\":\"String\", \"event\":\"SUBSCRIPTION_END\", \"attribute_key\":\"outcome\", \"attribute_values\":[ \"new_subscription\" ] }, { \"message_type\":4, \"event_match_type\":\"String\", \"event\":\"SUBSCRIPTION_END\", \"attribute_key\":\"plan_id\", \"attribute_values\":[ \"3\", \"8\" ] } ] }", + ) val mapping = CustomMapping(config) val info: MutableMap = HashMap() info["outcome"] = "new_subscription" diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/sample_dataplan.json b/android-kit-base/src/test/kotlin/com/mparticle/kits/sample_dataplan.json index eb41503a9..4ab333a10 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/sample_dataplan.json +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/sample_dataplan.json @@ -46,10 +46,7 @@ "type": "object" } }, - "required": [ - "custom_event_type", - "event_name" - ], + "required": ["custom_event_type", "event_name"], "type": "object" } } @@ -87,11 +84,7 @@ "properties": { "foo": { "description": "", - "enum": [ - "bar", - "barr", - "bar bar" - ], + "enum": ["bar", "barr", "bar bar"], "type": "string" }, "foo foo": { @@ -102,11 +95,7 @@ }, "foo number": { "description": "", - "enum": [ - "10", - "20", - "30" - ], + "enum": ["10", "20", "30"], "type": "number" } }, @@ -114,10 +103,7 @@ "type": "object" } }, - "required": [ - "custom_event_type", - "event_name" - ], + "required": ["custom_event_type", "event_name"], "type": "object" } } @@ -142,11 +128,7 @@ "properties": { "currency_code": { "description": "", - "enum": [ - "USD", - "CAD", - "AUS" - ], + "enum": ["USD", "CAD", "AUS"], "type": "string" }, "custom_attributes": { @@ -166,11 +148,7 @@ }, "attributeNumEnum": { "description": "", - "enum": [ - "2", - "7", - "9" - ], + "enum": ["2", "7", "9"], "type": "number" }, "attributeStringAlpha": { @@ -223,15 +201,11 @@ "type": "string" } }, - "required": [ - "required" - ], + "required": ["required"], "type": "object" } }, - "required": [ - "custom_attributes" - ], + "required": ["custom_attributes"], "type": "object" } } @@ -257,10 +231,7 @@ "properties": { "canonical_name": { "description": "", - "enum": [ - "This", - "That" - ], + "enum": ["This", "That"], "type": "string" } }, @@ -395,9 +366,7 @@ "type": "string" } }, - "required": [ - "my other attribute" - ] + "required": ["my other attribute"] } }, "active_transformation_ids": null @@ -426,9 +395,7 @@ "type": "string" } }, - "required": [ - "email" - ], + "required": ["email"], "type": "object" } }, @@ -491,4 +458,4 @@ "transformations": null, "active_transformation_ids": null } -} \ No newline at end of file +} diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/sample_dataplan2.json b/android-kit-base/src/test/kotlin/com/mparticle/kits/sample_dataplan2.json index cda540a32..2b3509a0e 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/sample_dataplan2.json +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/sample_dataplan2.json @@ -34,15 +34,11 @@ "type": "string" } }, - "required": [ - ], + "required": [], "type": "object" } }, - "required": [ - "custom_event_type", - "event_name" - ], + "required": ["custom_event_type", "event_name"], "type": "object" } } @@ -79,11 +75,7 @@ "properties": { "foo": { "description": "", - "enum": [ - "bar", - "barr", - "bar bar" - ], + "enum": ["bar", "barr", "bar bar"], "type": "string" }, "foo foo": { @@ -94,23 +86,15 @@ }, "foo number": { "description": "", - "enum": [ - "10", - "20", - "30" - ], + "enum": ["10", "20", "30"], "type": "number" } }, - "required": [ - ], + "required": [], "type": "object" } }, - "required": [ - "custom_event_type", - "event_name" - ], + "required": ["custom_event_type", "event_name"], "type": "object" } } @@ -134,11 +118,7 @@ "properties": { "currency_code": { "description": "", - "enum": [ - "USD", - "CAD", - "AUS" - ], + "enum": ["USD", "CAD", "AUS"], "type": "string" }, "custom_attributes": { @@ -158,11 +138,7 @@ }, "attributeNumEnum": { "description": "", - "enum": [ - "2", - "7", - "9" - ], + "enum": ["2", "7", "9"], "type": "number" }, "attributeStringAlpha": { @@ -175,8 +151,7 @@ "type": "boolean" } }, - "required": [ - ], + "required": [], "type": "object" }, "product_action": { @@ -202,25 +177,21 @@ "type": "string" } }, - "required": [ - ], + "required": [], "type": "object" } }, - "required": [ - ], + "required": [], "type": "object" }, "type": "array" } }, - "required": [ - ], + "required": [], "type": "object" } }, - "required": [ - ], + "required": [], "type": "object" } } @@ -255,15 +226,11 @@ "type": "string" } }, - "required": [ - "required" - ], + "required": ["required"], "type": "object" } }, - "required": [ - "custom_attributes" - ], + "required": ["custom_attributes"], "type": "object" } } @@ -288,15 +255,11 @@ "properties": { "canonical_name": { "description": "", - "enum": [ - "This", - "That" - ], + "enum": ["This", "That"], "type": "string" } }, - "required": [ - ], + "required": [], "type": "object" } } @@ -307,8 +270,7 @@ "description": "", "match": { "type": "product_impression", - "criteria": { - } + "criteria": {} }, "validator": { "type": "json_schema", @@ -326,8 +288,7 @@ "type": "boolean" } }, - "required": [ - ], + "required": [], "type": "object" }, "custom_attributes": { @@ -339,15 +300,11 @@ "type": "string" } }, - "required": [ - "thing1" - ], + "required": ["thing1"], "type": "object" } }, - "required": [ - "custom_attributes" - ], + "required": ["custom_attributes"], "type": "object" } } @@ -375,8 +332,7 @@ "type": "string" } }, - "required": [ - ], + "required": [], "type": "object" } } @@ -411,13 +367,11 @@ "type": "string" } }, - "required": [ - ], + "required": [], "type": "object" } }, - "required": [ - ], + "required": [], "type": "object" } } @@ -446,8 +400,7 @@ "type": "object" } }, - "required": [ - ], + "required": [], "type": "object" } } @@ -458,8 +411,7 @@ "description": "User Attributes", "match": { "type": "user_attributes", - "criteria": { - } + "criteria": {} }, "validator": { "type": "json_schema", @@ -479,20 +431,16 @@ "type": "string" } }, - "required": [ - "my other attribute" - ] + "required": ["my other attribute"] } }, - "active_transformation_ids": [ - ] + "active_transformation_ids": [] }, { "description": "User Identities", "match": { "type": "user_identities", - "criteria": { - } + "criteria": {} }, "validator": { "type": "json_schema", @@ -512,9 +460,7 @@ "type": "string" } }, - "required": [ - "email" - ], + "required": ["email"], "type": "object" } } @@ -541,8 +487,7 @@ "type": "object" } }, - "required": [ - ], + "required": [], "type": "object" } } @@ -587,8 +532,7 @@ "type": "string" } }, - "required": [ - ], + "required": [], "type": "object" }, "position": { @@ -600,15 +544,13 @@ "type": "string" } }, - "required": [ - ], + "required": [], "type": "object" }, "type": "array" } }, - "required": [ - ], + "required": [], "type": "object" }, "custom_attributes": { @@ -624,13 +566,11 @@ "type": "string" } }, - "required": [ - ], + "required": [], "type": "object" } }, - "required": [ - ], + "required": [], "type": "object" } } @@ -666,8 +606,7 @@ "type": "array" } }, - "required": [ - ], + "required": [], "type": "object" }, "custom_attributes": { @@ -683,13 +622,11 @@ "type": "string" } }, - "required": [ - ], + "required": [], "type": "object" } }, - "required": [ - ], + "required": [], "type": "object" } } @@ -698,4 +635,4 @@ } ] } -} \ No newline at end of file +} diff --git a/release.config.js b/release.config.js index e9785ea3b..184b791a1 100644 --- a/release.config.js +++ b/release.config.js @@ -7,18 +7,18 @@ module.exports = { { preset: "angular", releaseRules: [ - {type: 'feat', release: 'minor'}, - {type: 'ci', release: 'patch'}, - {type: 'fix', release: 'patch'}, - {type: 'docs', release: 'patch'}, - {type: 'test', release: 'patch'}, - {type: 'refactor', release: 'patch'}, - {type: 'style', release: 'patch'}, - {type: 'build', release: 'patch'}, - {type: 'chore', release: 'patch'}, - {type: 'revert', release: 'patch'} - ] - } + { type: "feat", release: "minor" }, + { type: "ci", release: "patch" }, + { type: "fix", release: "patch" }, + { type: "docs", release: "patch" }, + { type: "test", release: "patch" }, + { type: "refactor", release: "patch" }, + { type: "style", release: "patch" }, + { type: "build", release: "patch" }, + { type: "chore", release: "patch" }, + { type: "revert", release: "patch" }, + ], + }, ], [ "@semantic-release/release-notes-generator", @@ -27,53 +27,53 @@ module.exports = { presetConfig: { types: [ { - "type": "feat", - "section": "Features", - "hidden": false + type: "feat", + section: "Features", + hidden: false, }, { - "type": "fix", - "section": "Bug Fixes", - "hidden": false + type: "fix", + section: "Bug Fixes", + hidden: false, }, { - "type": "docs", - "section": "Documentation", - "hidden": false + type: "docs", + section: "Documentation", + hidden: false, }, { - "type": "style", - "section": "Updates & Maintenance", - "hidden": false + type: "style", + section: "Updates & Maintenance", + hidden: false, }, { - "type": "refactor", - "section": "Updates & Maintenance", - "hidden": false + type: "refactor", + section: "Updates & Maintenance", + hidden: false, }, { - "type": "perf", - "section": "Updates & Maintenance", - "hidden": false + type: "perf", + section: "Updates & Maintenance", + hidden: false, }, { - "type": "test", - "section": "Updates & Maintenance", - "hidden": false + type: "test", + section: "Updates & Maintenance", + hidden: false, }, { - "type": "ci", - "section": "Updates & Maintenance", - "hidden": false + type: "ci", + section: "Updates & Maintenance", + hidden: false, }, { - "type": "chore", - "section": "Updates & Maintenance", - "hidden": false - } - ] - } - } + type: "chore", + section: "Updates & Maintenance", + hidden: false, + }, + ], + }, + }, ], [ "@semantic-release/changelog", diff --git a/scripts/install-start-emulator.sh b/scripts/install-start-emulator.sh index 43c861d61..1b8398f49 100755 --- a/scripts/install-start-emulator.sh +++ b/scripts/install-start-emulator.sh @@ -1,3 +1,5 @@ +#!/bin/bash + # if there's already an emulator, just exit #export PATH=${ANDROID_HOME}:${ANDROID_HOME}/emulator:${TOOLS}:${TOOLS}/bin:${ANDROID_HOME}/platform-tools:${PATH} #echo "users file dump:" @@ -13,16 +15,16 @@ # If there is an emulator already started, just use that one -echo "run: started=$(adb get-state 1)" -started=$(adb get-state 1) -if [ "$started" = "device" ]; then - exit 0 +echo "run: started=$(adb get-state 1 || true)" +started=$(adb get-state 1 || true) +if [[ ${started} == "device" ]]; then + exit 0 fi # Set PATH variable so we can find sdkmanager and avdmanager echo "Setting Path (emulator before tools hack)" -export ANDROID_SDK=$HOME/Library/Android/sdk -export PATH=$ANDROID_SDK/emulator:$ANDROID_SDK/tools/:$ANDROID_HOME/tools/bin:$PATH +export ANDROID_SDK=${HOME}/Library/Android/sdk +export PATH=${ANDROID_SDK}/emulator:${ANDROID_SDK}/tools/:${ANDROID_HOME}/tools/bin:${PATH} #echo "run: sdkmanager tools" #sdkmanager tools #echo "run: kill-server" @@ -35,11 +37,11 @@ export PATH=$ANDROID_SDK/emulator:$ANDROID_SDK/tools/:$ANDROID_HOME/tools/bin:$P #echo "run: adb devices | grep emulator | cut -f1 | while read line; do adb -s $line emu kill; done &" #adb devices | grep emulator | cut -f1 | while read line; do adb -s $line emu kill; done & echo "starting emulator" -echo "run: echo yes | sdkmanager --install \"system-images;android-28;default;x86\"" +echo 'run: echo yes | sdkmanager --install "system-images;android-28;default;x86"' echo yes | sdkmanager --install "system-images;android-29;default;x86" # create new Emulator -echo "run: echo no | avdmanager create avd --force -n test -k \"system-images;android-29;default;x86\" -c 10M" +echo 'run: echo no | avdmanager create avd --force -n test -k "system-images;android-29;default;x86" -c 10M' echo no | avdmanager create avd --force -n test -k "system-images;android-29;default;x86" -c 10M # sanity check, make sure new Emulator was created @@ -47,22 +49,22 @@ echo "run: emulator -list-avds" emulator -list-avds # start Emulator (not sure if we actually have to run this as sudo or not -echo "run: sudo -E sudo -u $USER -E bash -c \"./emulator -avd test -verbose -no-snapshot -no-window -camera-back none -camera-front none -selinux permissive -qemu -m 2048 &\"" -sudo -E sudo -u "$USER" -E bash -c "${ANDROID_HOME}/emulator/emulator -avd test -verbose -no-snapshot -no-window -camera-back none -camera-front none -selinux permissive -qemu -m 2048 &" +echo "run: sudo -E sudo -u ${USER} -E bash -c \"./emulator -avd test -verbose -no-snapshot -no-window -camera-back none -camera-front none -selinux permissive -qemu -m 2048 &\"" +sudo -E sudo -u "${USER}" -E bash -c "${ANDROID_HOME}/emulator/emulator -avd test -verbose -no-snapshot -no-window -camera-back none -camera-front none -selinux permissive -qemu -m 2048 &" echo "run: adb shell input keyevent 82 &" adb shell input keyevent 82 & #block until emulator is ready to run tests echo "Waiting for Emulator to start" -until [[ "$bootanim" =~ "stopped" ]]; do - echo "run: adb reconnect offline" - adb reconnect offline - adb devices - bootanim=`adb -e shell getprop init.svc.bootanim 2>&1 &` - echo "Waiting for emulator, status is: $bootanim" - sleep 1 - echo +until [[ ${bootanim} =~ "stopped" ]]; do + echo "run: adb reconnect offline" + adb reconnect offline + adb devices + bootanim=$(adb -e shell getprop init.svc.bootanim 2>&1 &) + echo "Waiting for emulator, status is: ${bootanim}" + sleep 1 + echo done echo "Emulator has started - dismissing keyboard and sleeping for 1 second." diff --git a/scripts/kits/merge-updates.sh b/scripts/kits/merge-updates.sh index 059969505..80c86345c 100755 --- a/scripts/kits/merge-updates.sh +++ b/scripts/kits/merge-updates.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash : "${2?"Kit Test Branch missing - usage: $0 \{branch_name\} \{target_branch\}"}" -CURRENT_BRANCH=`git rev-parse --abbrev-ref HEAD` +CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) echo "Fetch" git fetch origin echo "Rebase" @@ -12,4 +12,4 @@ echo "Delete Kit Feature branch Locally" git branch -D "$1" echo "Push Delete remote" git push origin --delete "$1" -git checkout "$CURRENT_BRANCH" +git checkout "${CURRENT_BRANCH}" diff --git a/scripts/kits/update.sh b/scripts/kits/update.sh index edbc3f99a..aebd9e0c8 100755 --- a/scripts/kits/update.sh +++ b/scripts/kits/update.sh @@ -1,17 +1,17 @@ #!/usr/bin/env bash : "${1?"Kit Test Branch missing - usage: $0 \{branch_name\}"}" -CURRENT_BRANCH=`git rev-parse --abbrev-ref HEAD` +CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) # checkout a kit branch for testing git branch -D "$1" git checkout -b "$1" # update kit references -git submodule foreach "git fetch; git reset --hard origin/master"; +git submodule foreach "git fetch; git reset --hard origin/master" # commit kit reference deltas and push to private -git add kits/*; +git add kits/* git commit -m "Update submodules" git push -f origin "$1" -git checkout "$CURRENT_BRANCH" +git checkout "${CURRENT_BRANCH}" diff --git a/scripts/release.sh b/scripts/release.sh index b7f34abb9..92d3f3b08 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -: ${1?"Version missing - usage: $0 x.y.z"} # nosemgrep +: "${1?"Version missing - usage: $0 x.y.z"}" # nosemgrep #update build.gradle sed -i '.bak' "s/version = '.*-SNAPSHOT/version = '$1-SNAPSHOT/g" build.gradle diff --git a/scripts/startup_perf_tests.sh b/scripts/startup_perf_tests.sh index e69de29bb..a9bf588e2 100644 --- a/scripts/startup_perf_tests.sh +++ b/scripts/startup_perf_tests.sh @@ -0,0 +1 @@ +#!/bin/bash diff --git a/testutils/src/main/java/com/google/firebase/iid/FirebaseInstanceId.kt b/testutils/src/main/java/com/google/firebase/iid/FirebaseInstanceId.kt index dcf748084..0a42cbb33 100644 --- a/testutils/src/main/java/com/google/firebase/iid/FirebaseInstanceId.kt +++ b/testutils/src/main/java/com/google/firebase/iid/FirebaseInstanceId.kt @@ -5,7 +5,6 @@ object FirebaseInstanceIdToken { } class FirebaseInstanceId { - companion object { @JvmStatic fun getInstance() = FirebaseInstanceId() @@ -17,5 +16,9 @@ class FirebaseInstanceId { } fun getToken() = FirebaseInstanceIdToken.token - fun getToken(authority: String, scope: String) = FirebaseInstanceIdToken.token + + fun getToken( + authority: String, + scope: String, + ) = FirebaseInstanceIdToken.token } diff --git a/testutils/src/main/java/com/mparticle/testutils/CaptureLogcatOnFailingTest.java b/testutils/src/main/java/com/mparticle/testutils/CaptureLogcatOnFailingTest.java index e15a9a9e5..91149a3a4 100644 --- a/testutils/src/main/java/com/mparticle/testutils/CaptureLogcatOnFailingTest.java +++ b/testutils/src/main/java/com/mparticle/testutils/CaptureLogcatOnFailingTest.java @@ -48,7 +48,7 @@ public void evaluate() throws Throwable { } message = throwable.getMessage() + ORIGINAL_CLASS_HEADER + throwable.getClass().getName() + LOGCAT_HEADER - + message + MOCKSERVER_HEADER + + + message + MOCKSERVER_HEADER requestReceivedBuilder.toString() + STACKTRACE_HEADER; Throwable modifiedThrowable = new Throwable(message); modifiedThrowable.setStackTrace(throwable.getStackTrace()); diff --git a/testutils/src/main/kotlin/com.mparticle/Utils.kt b/testutils/src/main/kotlin/com.mparticle/Utils.kt index f57145ad2..c93bd6b1f 100644 --- a/testutils/src/main/kotlin/com.mparticle/Utils.kt +++ b/testutils/src/main/kotlin/com.mparticle/Utils.kt @@ -6,52 +6,48 @@ import java.lang.reflect.Modifier import kotlin.random.Random object Utils { + fun randomPromotionAction(): String = randomConstString(Promotion::class.java) - fun randomPromotionAction(): String { - return randomConstString(Promotion::class.java) - } - - fun randomConstString(clazz: Class<*>): String { - return clazz.fields + fun randomConstString(clazz: Class<*>): String = + clazz.fields .filter { Modifier.isPublic(it.modifiers) && Modifier.isStatic(it.modifiers) } .filter { it.name.all { it.isUpperCase() } } .filter { it.type == String::class.java } .let { it[Random.Default.nextInt(0, it.size - 1)].get(null) as String } - } val chars: List = ('a'..'z') + ('A'..'Z') - fun randomAttributes(): MutableMap { - return (0..Random.Default.nextInt(0, 5)).map { - randomString(4) to randomString(8) - }.toMap().toMutableMap() - } + fun randomAttributes(): MutableMap = + (0..Random.Default.nextInt(0, 5)) + .map { + randomString(4) to randomString(8) + }.toMap() + .toMutableMap() fun randomIdentities(): MutableMap { val identities = MParticle.IdentityType.values() - return (0..Random.Default.nextInt(3, 8)).map { - identities[Random.Default.nextInt(0, identities.size - 1)] to randomString(8) - }.toMap().toMutableMap() + return (0..Random.Default.nextInt(3, 8)) + .map { + identities[Random.Default.nextInt(0, identities.size - 1)] to randomString(8) + }.toMap() + .toMutableMap() } - fun randomString(length: Int): String { - return (0..length - 1).map { - chars[Random.Default.nextInt(0, chars.size - 1)] - }.joinToString("") - } + fun randomString(length: Int): String = + (0..length - 1) + .map { + chars[Random.Default.nextInt(0, chars.size - 1)] + }.joinToString("") - fun randomEventType(): MParticle.EventType { - return MParticle.EventType.values()[ + fun randomEventType(): MParticle.EventType = + MParticle.EventType.values()[ Random.Default.nextInt( 0, - MParticle.EventType.values().size - 1 - ) + MParticle.EventType.values().size - 1, + ), ] - } - fun randomProductAction(): String { - return randomConstString(Product::class.java) - } + fun randomProductAction(): String = randomConstString(Product::class.java) } diff --git a/tooling/android-plugin/src/main/java/com/mparticle/MParticlePlugin.kt b/tooling/android-plugin/src/main/java/com/mparticle/MParticlePlugin.kt index b41a65904..23f87e039 100644 --- a/tooling/android-plugin/src/main/java/com/mparticle/MParticlePlugin.kt +++ b/tooling/android-plugin/src/main/java/com/mparticle/MParticlePlugin.kt @@ -13,7 +13,6 @@ import org.json.JSONObject import java.io.File class MParticlePlugin : Plugin { - companion object { val MParticleCliVersion: String? = null } @@ -127,25 +126,27 @@ class MParticlePlugin : Plugin { private fun readConfig(extension: MParticleExtension): Config { val staticConfigFile = File("./mp.config.json") - var config = if (staticConfigFile.exists()) { - Logger.verbose("Config File found") - val text = staticConfigFile.readText() - try { - val json = JSONObject(text) - Config.from(json) - } catch (jse: JSONException) { - Logger.warning("Error reading mp.config.json: ${jse.message}") + var config = + if (staticConfigFile.exists()) { + Logger.verbose("Config File found") + val text = staticConfigFile.readText() + try { + val json = JSONObject(text) + Config.from(json) + } catch (jse: JSONException) { + Logger.warning("Error reading mp.config.json: ${jse.message}") + Config() + } + } else { + Logger.verbose("Config File Not Found, using extension values") Config() } - } else { - Logger.verbose("Config File Not Found, using extension values") - Config() - } var credentialsFile = File("mp.config.json") if (credentialsFile.exists()) { - config.credentialsFilePath = credentialsFile.absolutePath.let { - it.substring(0, it.length - "/mp.config.json".length) - } + config.credentialsFilePath = + credentialsFile.absolutePath.let { + it.substring(0, it.length - "/mp.config.json".length) + } } else { Logger.verbose("Credentials File Not Found") Config() diff --git a/tooling/android-plugin/src/test/java/com/mparticle/MParticlePluginTest.kt b/tooling/android-plugin/src/test/java/com/mparticle/MParticlePluginTest.kt index 187fa00fc..678f6f835 100644 --- a/tooling/android-plugin/src/test/java/com/mparticle/MParticlePluginTest.kt +++ b/tooling/android-plugin/src/test/java/com/mparticle/MParticlePluginTest.kt @@ -5,23 +5,24 @@ import groovy.util.GroovyTestCase.assertEquals import org.junit.Test class MParticlePluginTest { - @Test fun testConfigSerialization() { - val config = Config().apply { - this.credentialsFilePath = "credentialsFilePath" - this.dataPlanVersionFile = "dataplanfile" - this.dataPlanId = "dataplanid" - this.dataPlanVersion = "dataplanversion" - this.debugReportServerMessage = true - this.resultsFile = "resultsfilelocation" - this.verbose = null - this.workspaceId = "workspaceId" - this.internalConfig = Config.InternalConfig( - "path/to/node", - "path/to/mp" - ) - } + val config = + Config().apply { + this.credentialsFilePath = "credentialsFilePath" + this.dataPlanVersionFile = "dataplanfile" + this.dataPlanId = "dataplanid" + this.dataPlanVersion = "dataplanversion" + this.debugReportServerMessage = true + this.resultsFile = "resultsfilelocation" + this.verbose = null + this.workspaceId = "workspaceId" + this.internalConfig = + Config.InternalConfig( + "path/to/node", + "path/to/mp", + ) + } val json = config.toJson() assertEquals(config, Config.from(json)) } diff --git a/tooling/common/src/main/java/com/mparticle/tooling/Config.kt b/tooling/common/src/main/java/com/mparticle/tooling/Config.kt index 78a6d1903..2d35b079a 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/Config.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/Config.kt @@ -11,9 +11,8 @@ data class Config( var resultsFile: String? = null, var verbose: Boolean? = null, var disabled: Boolean? = null, - var debugReportServerMessage: Boolean? = null + var debugReportServerMessage: Boolean? = null, ) { - var internalConfig: InternalConfig = InternalConfig() fun toJson(): JSONObject { @@ -37,10 +36,11 @@ data class Config( } else { Config::class.java.declaredMethods .firstOrNull { - it.name.removePrefix("set").toLowerCase() == key?.toString() - ?.toLowerCase() - } - ?.invoke(config, json.opt(key.toString())) + it.name.removePrefix("set").toLowerCase() == + key + ?.toString() + ?.toLowerCase() + }?.invoke(config, json.opt(key.toString())) } } return config @@ -49,22 +49,19 @@ data class Config( data class InternalConfig( var nodePath: String? = null, - var mpPath: String? = null + var mpPath: String? = null, ) { - - fun toJson(): JSONObject { - return JSONObject() + fun toJson(): JSONObject = + JSONObject() .putOpt("node-path", nodePath) .putOpt("mp-path", mpPath) - } companion object { - fun fromJson(json: JSONObject): InternalConfig { - return InternalConfig( + fun fromJson(json: JSONObject): InternalConfig = + InternalConfig( nodePath = json.optString("node-path", null), - mpPath = json.optString("mp-path", null) + mpPath = json.optString("mp-path", null), ) - } } } } diff --git a/tooling/common/src/main/java/com/mparticle/tooling/DataPlanningNodeApp.kt b/tooling/common/src/main/java/com/mparticle/tooling/DataPlanningNodeApp.kt index 8c97bd4c3..99bea36ee 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/DataPlanningNodeApp.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/DataPlanningNodeApp.kt @@ -4,11 +4,15 @@ import com.mparticle.tooling.Utils.executeCLI import java.io.File import java.io.IOException -enum class DataPlanError(val message: String) { - VersionInvalid("Error: Data Plan Version is Invalid"); +enum class DataPlanError( + val message: String, +) { + VersionInvalid("Error: Data Plan Version is Invalid"), } -class DataPlanningNodeApp(val config: Config) { +class DataPlanningNodeApp( + val config: Config, +) { var path = System.getenv("PATH") init { @@ -25,35 +29,38 @@ class DataPlanningNodeApp(val config: Config) { fun validate( dataplan: String, message: String, - version: String? + version: String?, ): NodeAppResult> { try { val mpCommand = config.internalConfig.mpPath ?: "mp" - val args = if (version == null) { - mutableListOf( - mpCommand, - "planning:events:validate", - "--dataPlanVersion", - dataplan, - "--translateEvents", - "--event", - message - ) - } else { - mutableListOf( - mpCommand, - "planning:events:validate", - "--dataPlan", - dataplan, - "--translateEvents", - "--event", - message, - "--versionNumber", - version - ) - } - val results = args.toTypedArray() - .executeCLI(path, workingDirectory = config.credentialsFilePath ?: ".") + val args = + if (version == null) { + mutableListOf( + mpCommand, + "planning:events:validate", + "--dataPlanVersion", + dataplan, + "--translateEvents", + "--event", + message, + ) + } else { + mutableListOf( + mpCommand, + "planning:events:validate", + "--dataPlan", + dataplan, + "--translateEvents", + "--event", + message, + "--versionNumber", + version, + ) + } + val results = + args + .toTypedArray() + .executeCLI(path, workingDirectory = config.credentialsFilePath ?: ".") val error = DataPlanError.values().firstOrNull { results.contains(it.message) } if (error != null) { return NodeAppResult(listOf(ValidationResult(error = error, arguments = args))) @@ -63,22 +70,27 @@ class DataPlanningNodeApp(val config: Config) { return NodeAppResult( ValidationResult.from( "", - listOf("${ioe.message}\n${ioe.stackTrace.joinToString("\n")}") - ) + listOf("${ioe.message}\n${ioe.stackTrace.joinToString("\n")}"), + ), ) } } - fun fetchDataPlan(accountId: String, planId: String, version: String?): NodeAppResult { + fun fetchDataPlan( + accountId: String, + planId: String, + version: String?, + ): NodeAppResult { try { - val arguments = mutableListOf( - "mp", - "data-plan:fetch", - "--accountId", - accountId, - "--dataPlanId", - planId - ) + val arguments = + mutableListOf( + "mp", + "data-plan:fetch", + "--accountId", + accountId, + "--dataPlanId", + planId, + ) if (version != null) { arguments.add("--version") arguments.add(version) @@ -151,15 +163,16 @@ class DataPlanningNodeApp(val config: Config) { } } - fun fromJS(jsFileBlob: String): DataPlanningNodeApp? { - return Utils.getFileLocation(tempNodeFileName)?.let { nodeFile -> + fun fromJS(jsFileBlob: String): DataPlanningNodeApp? = + Utils.getFileLocation(tempNodeFileName)?.let { nodeFile -> val nodeFile = File(nodeFile) nodeFile.createNewFile() nodeFile.writeText(jsFileBlob) DataPlanningNodeApp(Config()) } - } } - class NodeAppResult(val response: T? = null) + class NodeAppResult( + val response: T? = null, + ) } diff --git a/tooling/common/src/main/java/com/mparticle/tooling/Utils.kt b/tooling/common/src/main/java/com/mparticle/tooling/Utils.kt index d0f2ecbf9..dd2630686 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/Utils.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/Utils.kt @@ -7,24 +7,29 @@ import java.io.File import java.io.InputStreamReader object Utils { - fun getCurrentFileLocation(fileName: String): String { - return javaClass.getResource(fileName).path.replace( - "file:", - "" - ).split("lint.jar")[0] - } + fun getCurrentFileLocation(fileName: String): String = + javaClass + .getResource(fileName) + .path + .replace( + "file:", + "", + ).split("lint.jar")[0] - fun Array.executeCLI(path: String? = null, workingDirectory: String = "."): String { + fun Array.executeCLI( + path: String? = null, + workingDirectory: String = ".", + ): String { Logger.verbose( "command line operation: ${ - joinToString(" ") { - if (it.contains(" ")) { - "\"$it\"" - } else { - it + joinToString(" ") { + if (it.contains(" ")) { + "\"$it\"" + } else { + it + } } - } - }" + }", ) var error = "" var result = "" @@ -33,10 +38,11 @@ object Utils { val envMap = mapOf("PATH" to path) processBuilder.environment().putAll(envMap) } - val p = processBuilder - .directory(File(workingDirectory)) - .command(*this) - .start() + val p = + processBuilder + .directory(File(workingDirectory)) + .command(*this) + .start() result = BufferedReader(InputStreamReader(p.inputStream)).readText() error = BufferedReader(InputStreamReader(p.errorStream)).readText() Logger.verbose("result: $result") diff --git a/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt b/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt index b2675a811..e44ac3492 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt @@ -13,24 +13,28 @@ data class ValidationResult( var originalString: String? = null companion object { - - fun from(json: String?, arguments: List): List? { - return try { + fun from( + json: String?, + arguments: List + ): List? = + try { val jsonArray = JSONObject(json).getJSONArray("results") from(jsonArray, arguments) } catch (jse: JSONException) { listOf(ValidationResult(arguments = arguments).apply { originalString = json }) } - } - fun from(json: JSONArray, arguments: List): List { + fun from( + json: JSONArray, + arguments: List, + ): List { val validationResults = ArrayList() - for (i in 0..json.length() - 1) { + for (i in 0 until json.length()) { val validationResultJson = json.getJSONObject(i) val eventType = validationResultJson.optString("event_type") val data = ValidationResultData.from(validationResultJson.optJSONObject("data")) validationResults.add( - ValidationResult(eventType, data, arguments = arguments) + ValidationResult(eventType, data, arguments = arguments), ) } return validationResults @@ -54,24 +58,17 @@ data class ValidationResult( ) .put("Event Type", eventType) return """ - Arguments: - ${ - arguments.indexOfFirst { it.startsWith("--dataPlan") }.let { - arguments.toMutableList().apply { - if (it >= 0) { - val dataplan = removeAt(it + 1) - add( - it + 1, - "${dataplan.substring(0, Math.min(dataplan.length, 20))}..." - ) + Arguments: + ${arguments.indexOfFirst { it.startsWith("--dataPlan") }.let { index -> + arguments.toMutableList().apply { + if (index >= 0) { + val dataplan = removeAt(index + 1) + add(index + 1, "${dataplan.substring(0, dataplan.length.coerceAtMost(20))}...") + } } - } - }.joinToString(" ") - } - - Response: - ${jsonResponse.toString(4)} - + }.joinToString(" ")} + Response: + ${jsonResponse.toString(4)} """.trimIndent() } catch (e: Exception) { return e.message + e.stackTrace.joinToString(("\n")) @@ -81,29 +78,30 @@ data class ValidationResult( data class ValidationResultData( val match: ValidationResultMatch?, - val validationErrors: List + val validationErrors: List, ) { companion object { - fun from(json: JSONObject?): ValidationResultData? { - return json?.let { + fun from(json: JSONObject?): ValidationResultData? = + json?.let { ValidationResultData( ValidationResultMatch.from(it.optJSONObject("match")), - ValidationResultErrors.from(it.optJSONArray("validation_errors")) + ValidationResultErrors.from(it.optJSONArray("validation_errors")), ) } - } } } -data class ValidationResultMatch(val type: String, val criteria: Map) { +data class ValidationResultMatch( + val type: String, + val criteria: Map, +) { companion object { - fun from(json: JSONObject?): ValidationResultMatch? { - return json?.let { + fun from(json: JSONObject?): ValidationResultMatch? = + json?.let { val type = it.optString("type") val criteria = it.optJSONObject("criteria")?.toHashMap() ?: hashMapOf() ValidationResultMatch(type, criteria) } - } } } @@ -113,12 +111,12 @@ data class ValidationResultErrors( val key: String?, val expected: String?, val actual: String?, - val schemaKeyworkd: String? + val schemaKeyword: String?, ) { companion object { fun from(json: JSONArray): List { val validationResultErrors = ArrayList() - for (i in 0..json.length() - 1) { + for (i in 0 until json.length()) { val jsonObject = json.getJSONObject(i) val validationErrorTypeString = jsonObject.getString("validation_error_type") val validationErrorType = ValidationErrorType.forName(validationErrorTypeString) @@ -134,8 +132,8 @@ data class ValidationResultErrors( key, expected, actual, - schemaKeyword - ) + schemaKeyword, + ), ) } return validationResultErrors @@ -143,16 +141,16 @@ data class ValidationResultErrors( } } -enum class ValidationErrorType(val text: String) { +enum class ValidationErrorType( + val text: String, +) { Unplanned("unplanned"), MissingRequied("missing_required"), InvalidValue("invalid_value"), - Unknown("unknown"); + Unknown("unknown") companion object { - fun forName(text: String): ValidationErrorType { - return values().first { it.text == text } - } + fun forName(text: String): ValidationErrorType = values().first { it.text == text } } } @@ -161,7 +159,7 @@ fun JSONObject.toHashMap(): HashMap { val map = HashMap() while (keys?.hasNext() == true) { val key = keys.next() - map.put(key, getString(key)) + map[key] = getString(key) } return map } diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/Extensions.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/Extensions.kt index 71f8c97fc..2b1b8bf34 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/Extensions.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/Extensions.kt @@ -41,17 +41,18 @@ import org.json.JSONObject internal fun UCallExpression.resolveExpression( instance: Expression, - returnValue: Boolean + returnValue: Boolean, ): Expression { - val expression = if (isConstructorCall()) { - Constructor(instance, methodName, this) - } else { - if (instance is RootParent) { - StaticFactory(methodName, this) + val expression = + if (isConstructorCall()) { + Constructor(instance, methodName, this) } else { - MethodCall(instance, methodName, this, returnValue) + if (instance is RootParent) { + StaticFactory(methodName, this) + } else { + MethodCall(instance, methodName, this, returnValue) + } } - } expression.arguments = valueArguments.map { it.resolveValue(expression) } return expression } @@ -93,11 +94,12 @@ internal fun PsiVariable.getClassName(): String? { } internal fun UExpression.getUltimateReceiverVariable(): PsiVariable? { - val receiver = when (this) { - is UCallExpression -> receiver - is UQualifiedReferenceExpression -> receiver - else -> null - } + val receiver = + when (this) { + is UCallExpression -> receiver + is UQualifiedReferenceExpression -> receiver + else -> null + } if (receiver == null) { return null } @@ -110,7 +112,7 @@ internal fun UExpression.getUltimateReceiverVariable(): PsiVariable? { internal fun UExpression.getVariableElement( allowChainedCalls: Boolean, - allowFields: Boolean + allowFields: Boolean, ): PsiVariable? { var parent = skipParenthesizedExprUp(getQualifiedParentOrThis().uastParent) @@ -176,7 +178,8 @@ internal fun UCallExpression.receiverClassName(stripGenerics: Boolean = true): S isConstructorCall() -> returnType?.getClassName() receiver == null -> { (this.resolve() as? ClsMethodImpl)?.run { - stub.parentStub.psi.containingFile.name.split("__")[0] + stub.parentStub.psi.containingFile.name + .split("__")[0] } } else -> (receiverType as? PsiClassReferenceType)?.reference?.qualifiedName @@ -198,13 +201,12 @@ internal fun UCallExpression.receiverClassName(stripGenerics: Boolean = true): S return className } -internal fun PsiType.getClassName(): String? { - return when (this) { +internal fun PsiType.getClassName(): String? = + when (this) { is PsiClassReferenceType -> this.reference.qualifiedName is PsiImmediateClassType -> this.resolve()?.qualifiedName else -> null } -} internal fun PsiClass.getQualifiedName(reflectable: Boolean): String? { if (!reflectable) { @@ -215,9 +217,10 @@ internal fun PsiClass.getQualifiedName(reflectable: Boolean): String? { fun isParentTopLevel(child: PsiElement) { if (!child.isTopLevelKtOrJavaMember()) { val index = qualifiedName.indexOfLast { it == '.' } - qualifiedName = qualifiedName.substring(0, index) + "$" + qualifiedName.substring( + qualifiedName = qualifiedName.substring(0, index) + "$" + qualifiedName.substring( index + 1, - qualifiedName.length + qualifiedName.length, ) isParentTopLevel(child.parent) } @@ -228,41 +231,44 @@ internal fun PsiClass.getQualifiedName(reflectable: Boolean): String? { internal fun UExpression.resolveChainedCalls( returnValue: Boolean, - instance: Expression + instance: Expression, ): Expression { val initialInstance = instance var calls = (getOutermostQualified() ?: this).getQualifiedChain().toMutableList() calls = calls.filter { it is UCallExpression }.toMutableList() // check if first call is a constructor - Product.Builder().brand("") otherwise, the instance // argument should be the object the chain is being called on - return calls.fold(initialInstance) { acc, item -> - (item as UCallExpression).resolveExpression(acc, true) - }.apply { - if (this is MethodCall) { - this.returnValue = returnValue + return calls + .fold(initialInstance) { acc, item -> + (item as UCallExpression).resolveExpression(acc, true) + }.apply { + if (this is MethodCall) { + this.returnValue = returnValue + } } - } } internal fun Pair<*, *>.resolveToEnum(): Enum<*> { - val className = when (first) { - is ClassId -> "${(first as ClassId).packageFqName}.${ - (first as ClassId).relativeClassName.asString().replace(".", "$") - }" - is String -> first as String - else -> null - } + val className = + when (first) { + is ClassId -> "${(first as ClassId).packageFqName}.${ + (first as ClassId).relativeClassName.asString().replace(".", "$") + }" + is String -> first as String + else -> null + } return className?.let { className -> val enumName = second.toString() - val constructor = Class.forName(className) - .methods.first { it.name == "valueOf" } + val constructor = + Class + .forName(className) + .methods + .first { it.name == "valueOf" } constructor.invoke(null, enumName) } as Enum<*> } -internal fun List.resolve(): List { - return map { it.resolve() } -} +internal fun List.resolve(): List = map { it.resolve() } internal fun JSONObject.stringify(): JSONObject { val newJSONObject = JSONObject() diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/MParticleIssueRegistry.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/MParticleIssueRegistry.kt index a39045396..acc79c6a4 100755 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/MParticleIssueRegistry.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/MParticleIssueRegistry.kt @@ -13,20 +13,22 @@ import com.mparticle.lints.detectors.ReferrerReceiverDetector */ @SuppressWarnings("unused") class MParticleIssueRegistry : IssueRegistry() { - override val issues = listOf( - GradleBuildDetector.ISSUE, - MpApiDetectorKt.ISSUE, - ReferrerReceiverDetector.ISSUE, - DataplanDetector.ISSUE, - DataplanDetector.NODE_MISSING, - DataplanDetector.NO_DATA_PLAN - ) + override val issues = + listOf( + GradleBuildDetector.ISSUE, + MpApiDetectorKt.ISSUE, + ReferrerReceiverDetector.ISSUE, + DataplanDetector.ISSUE, + DataplanDetector.NODE_MISSING, + DataplanDetector.NO_DATA_PLAN, + ) override val api: Int = CURRENT_API - override val vendor: Vendor = Vendor( - vendorName = "mParticle", - identifier = "android-core", - feedbackUrl = "https://github.com/mParticle/mparticle-android-sdk" - ) + override val vendor: Vendor = + Vendor( + vendorName = "mParticle", + identifier = "android-core", + feedbackUrl = "https://github.com/mParticle/mparticle-android-sdk", + ) } diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/VariableCollector.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/VariableCollector.kt index 399dbb7b9..3c54cb082 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/VariableCollector.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/VariableCollector.kt @@ -27,7 +27,7 @@ internal class VariableCollector( val variable: PsiVariable, private val method: UMethod, val parent: Expression, - val includeInitialization: Boolean = false + val includeInitialization: Boolean = false, ) : AbstractUastVisitor() { private var expression: Expression? = null @@ -61,28 +61,33 @@ internal class VariableCollector( is USimpleNameReferenceExpression -> { val reference = uastInitializer.resolve() if (reference is PsiVariable) { - expression = VariableCollector( - reference, - method, - parent, - true - ).getUnresolvedObject(true) + expression = + VariableCollector( + reference, + method, + parent, + true, + ).getUnresolvedObject(true) } } is UQualifiedReferenceExpression -> { // get the first call in a potential chain of calls - val reference = uastInitializer.getOutermostQualified() - .getQualifiedChain()[0].tryResolve() + val reference = + uastInitializer + .getOutermostQualified() + .getQualifiedChain()[0] + .tryResolve() when (reference) { // product = productBuilder.build() is PsiVariable -> { - expression = VariableCollector( - reference, - method, - parent, - true - ).getUnresolvedObject(true) + expression = + VariableCollector( + reference, + method, + parent, + true, + ).getUnresolvedObject(true) } // product = Product.Builder() (static method) is PsiClass -> { @@ -96,10 +101,11 @@ internal class VariableCollector( // product = new Product() // map = mapOf() is UCallExpression -> { - expression = uastInitializer.resolveChainedCalls( - true, - RootParent(uastInitializer) - ) + expression = + uastInitializer.resolveChainedCalls( + true, + RootParent(uastInitializer), + ) } } } diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/basedetectors/CallScanner.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/basedetectors/CallScanner.kt index 674495483..be9b6f8b1 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/basedetectors/CallScanner.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/basedetectors/CallScanner.kt @@ -23,18 +23,19 @@ import org.jetbrains.uast.util.isConstructorCall * * @see com.mparticle.lints.dtos.UnresolvedObject */ -abstract class CallScanner : BaseDetector(), Detector.UastScanner { - +abstract class CallScanner : + BaseDetector(), + Detector.UastScanner { abstract fun onInstanceCollected( context: JavaContext, unresolvedExpression: Expression, - reportingNode: UExpression + reportingNode: UExpression, ) abstract fun getApplicableClasses(): List> - override fun createUastHandler(context: JavaContext): UElementHandler? { - return object : UElementHandler() { + override fun createUastHandler(context: JavaContext): UElementHandler? = + object : UElementHandler() { override fun visitCallExpression(node: UCallExpression) { try { if (!disabled && ofInterest(node)) { @@ -45,7 +46,7 @@ abstract class CallScanner : BaseDetector(), Detector.UastScanner { if (variable != null && method != null) { VariableCollector(variable, method, expression).getUnresolvedObject( - false + false, ) } if (expression != null) { @@ -61,17 +62,15 @@ abstract class CallScanner : BaseDetector(), Detector.UastScanner { } } } - } - override fun getApplicableUastTypes(): List>? { - return listOf(UCallExpression::class.java) - } + override fun getApplicableUastTypes(): List>? = listOf(UCallExpression::class.java) private fun ofInterest(node: UCallExpression): Boolean { val receiverClassName = node.receiverClassName() ?: return false - return node.isConstructorCall() && getApplicableClasses().any { - it.canonicalName == receiverClassName - } + return node.isConstructorCall() && + getApplicableClasses().any { + it.canonicalName == receiverClassName + } } } diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt index edae1185d..f7d611589 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt @@ -22,62 +22,69 @@ import org.json.JSONObject import java.io.File class DataplanDetector : CallScanner() { - private var dataplanningNode: DataPlanningNodeApp? = null private var dataplan: String? = null companion object { + val ISSUE = + Issue.create( + "DataplanViolation", + "Field conflicts with data plan's constraints", + "This field is in violation of constrains defined in your organization or workspace's data plan", + Category.create("DataPlanning", 1), + 10, + Severity.ERROR, + Implementation(DataplanDetector::class.java, Scope.JAVA_FILE_SCOPE), + ) - val ISSUE = Issue.create( - "DataplanViolation", - "Field conflicts with data plan's constraints", - "This field is in violation of constrains defined in your organization or workspace's data plan", - Category.create("DataPlanning", 1), - 10, - Severity.ERROR, - Implementation(DataplanDetector::class.java, Scope.JAVA_FILE_SCOPE) - ) - - val NODE_MISSING = Issue.create( - "NodeMissing", - "Unable to validate Dataplan, Node is not present", - "The MParticle Dataplan validation library requirs Node CLI tools to be installed. To insure you have Node installed, run \"node -v\" from the Command Line", - Category.USABILITY, - 4, - Severity.INFORMATIONAL, - Implementation(DataplanDetector::class.java, Scope.JAVA_FILE_SCOPE) - ) + val NODE_MISSING = + Issue.create( + "NodeMissing", + "Unable to validate Dataplan, Node is not present", + "The MParticle Dataplan validation library requirs Node CLI tools to be installed. To insure you have Node installed, run \"node -v\" from the Command Line", + Category.USABILITY, + 4, + Severity.INFORMATIONAL, + Implementation(DataplanDetector::class.java, Scope.JAVA_FILE_SCOPE), + ) - val NO_DATA_PLAN = Issue.create( - "DataPlanMissing", - "Unable to read Data Plan", - "Retrieving the MParticle Data Plan is necessary to evaluate any violations. There may be a problem with locating your \"dataPlanVersionFile\". Please double check the values is correct in your \"mparticle\" block in build.gradle or your mp.config.json file", - Category.USABILITY, - 4, - Severity.INFORMATIONAL, - Implementation(DataplanDetector::class.java, Scope.JAVA_FILE_SCOPE) - ) + val NO_DATA_PLAN = + Issue.create( + "DataPlanMissing", + "Unable to read Data Plan", + "Retrieving the MParticle Data Plan is necessary to evaluate any violations. There may be a problem with locating your \"dataPlanVersionFile\". Please double check the values is correct in your \"mparticle\" block in build.gradle or your mp.config.json file", + Category.USABILITY, + 4, + Severity.INFORMATIONAL, + Implementation(DataplanDetector::class.java, Scope.JAVA_FILE_SCOPE), + ) } - override fun getApplicableClasses() = - listOf(MPEvent.Builder::class.java, CommerceEvent.Builder::class.java) + override fun getApplicableClasses() = listOf(MPEvent.Builder::class.java, CommerceEvent.Builder::class.java) override fun beforeCheckRootProject(context: Context) { super.beforeCheckRootProject(context) // stub logger in MParticle to avoid any dependencies on Android Log when building Events - Logger.setLogHandler(object : Logger.DefaultLogHandler() { - override fun log(priority: MParticle.LogLevel?, error: Throwable?, messages: String?) {} - }) + Logger.setLogHandler( + object : Logger.DefaultLogHandler() { + override fun log( + priority: MParticle.LogLevel?, + error: Throwable?, + messages: String?, + ) {} + }, + ) if (config != null) { dataplanningNode = DataPlanningNodeApp(config!!) - dataplan = try { - Utils.getLocalDataplan() - } catch (e: Exception) { - disabled = true - return - } + dataplan = + try { + Utils.getLocalDataplan() + } catch (e: Exception) { + disabled = true + return + } if (config?.resultsFile?.isEmpty() == false) { File(config!!.resultsFile!!).apply { if (exists()) { @@ -94,20 +101,22 @@ class DataplanDetector : CallScanner() { override fun onInstanceCollected( context: JavaContext, unresolvedObject: Expression, - reportingNode: UExpression + reportingNode: UExpression, ) { - val instance = try { - unresolvedObject.resolve() - } catch (e: Exception) { - } + val instance = + try { + unresolvedObject.resolve() + } catch (e: Exception) { + } // this will make MParticle not break incase Logger happens to be called - val message = when (instance) { - is MPEvent.Builder -> instance.build().message - is CommerceEvent.Builder -> instance.build().message - is CommerceEvent -> instance.message - is MPEvent -> instance.message - else -> null - } + val message = + when (instance) { + is MPEvent.Builder -> instance.build().message + is CommerceEvent.Builder -> instance.build().message + is CommerceEvent -> instance.message + is MPEvent -> instance.message + else -> null + } if (message == null) { return @@ -115,26 +124,27 @@ class DataplanDetector : CallScanner() { val dp = dataplan if (dp == null) { - val message = "Data Plan missing" + - if (config?.dataPlanVersionFile != null) { - config?.dataPlanVersionFile?.let { - ", $it not found" - } - } else { - "" + val message = + "Data Plan missing" + if (config?.dataPlanVersionFile != null) { + config?.dataPlanVersionFile?.let { + ", $it not found" } + } else { + "" + } context.report( NO_DATA_PLAN, reportingNode, context.getLocation(reportingNode), - message + message, ) } else if (dataplanningNode?.checkMPInstalled() == false) { context.report( NODE_MISSING, reportingNode, context.getLocation(reportingNode), - "MParticle CLI tools missing, run \"./gradlew mpInstall\"" + "MParticle CLI tools missing, run \"./gradlew mpInstall\"", ) } else { val messageString = message.attributesToNumbers().toString() @@ -146,7 +156,7 @@ class DataplanDetector : CallScanner() { ISSUE, reportingNode, context.getLocation(reportingNode), - response.toString() + response.toString(), ) return } @@ -155,15 +165,17 @@ class DataplanDetector : CallScanner() { validationResult.data?.validationErrors?.forEach { error -> var errorMessage = when (error.errorPointer) { - "#/data/custom_attributes", "#/data/custom_attributes/${error.key}" -> getErrorMessageBySchemaKeyword( - ViolationSchemaKeywordType.get(error.schemaKeyworkd), - error.expected - ) - "#" -> when (validationResult.data?.match?.type) { - "commerce_event" -> "Unplanned Commerce Event" - "custom_event" -> "Unplanned Custom Event (MPEvent)" - else -> null - } + "#/data/custom_attributes", "#/data/custom_attributes/${error.key}" -> + getErrorMessageBySchemaKeyword( + ViolationSchemaKeywordType.get(error.schemaKeyworkd), + error.expected, + ) + "#" -> + when (validationResult.data?.match?.type) { + "commerce_event" -> "Unplanned Commerce Event" + "custom_event" -> "Unplanned Custom Event (MPEvent)" + else -> null + } else -> "Event does not conform to DataPlan" } val matchingValues = ArrayList() @@ -177,24 +189,28 @@ class DataplanDetector : CallScanner() { } val match = validationResult.data?.match errorMessage = errorMessage - ?: validationResult.data?.match?.criteria?.entries?.firstOrNull { - it.value == error.key - }?.let { entry -> - "For ${match?.type}, unexpected ${entry.key} value of \"${entry.value}\". exprected ${error.expected}" - } + ?: validationResult.data + ?.match + ?.criteria + ?.entries + ?.firstOrNull { + it.value == error.key + }?.let { entry -> + "For ${match?.type}, unexpected ${entry.key} value of \"${entry.value}\". exprected ${error.expected}" + } if (matchingValues.size == 1) { context.report( ISSUE, matchingValues[0], context.getLocation(matchingValues[0]), - errorMessage ?: "Event is not in accordance with Data Plan" + errorMessage ?: "Event is not in accordance with Data Plan", ) } else { context.report( ISSUE, reportingNode, context.getLocation(reportingNode), - errorMessage ?: "Event is not in accordance with Data Plan" + errorMessage ?: "Event is not in accordance with Data Plan", ) } } @@ -204,7 +220,7 @@ class DataplanDetector : CallScanner() { if (config?.resultsFile?.isEmpty() == false) { File(config!!.resultsFile!!).appendText( result?.response?.joinToString { it.toString() } - ?: "" + ?: "", ) } } @@ -212,7 +228,7 @@ class DataplanDetector : CallScanner() { fun getErrorMessageBySchemaKeyword( schemaKeyword: ViolationSchemaKeywordType, - expectedValue: String? = null + expectedValue: String? = null, ): String { val expectedValueMessage = expectedValue?.let { ": $it" } ?: "" return when (schemaKeyword) { @@ -261,13 +277,13 @@ class DataplanDetector : CallScanner() { AdditionalProperties, Required, Type, - Unknown; + Unknown, + ; companion object { - fun get(value: String?): ViolationSchemaKeywordType { - return values().firstOrNull { it.toString().toLowerCase() == value?.toLowerCase() } + fun get(value: String?): ViolationSchemaKeywordType = + values().firstOrNull { it.toString().toLowerCase() == value?.toLowerCase() } ?: Unknown - } } } diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt index ba826cbbb..6d2e6bd1d 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt @@ -28,8 +28,9 @@ import org.jetbrains.uast.getContainingUClass import org.jetbrains.uast.getParentOfType import org.jetbrains.uast.resolveToUElement -class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { - +class MpApiDetectorKt : + BaseDetector(), + Detector.UastScanner { companion object { val MESSAGE_MULTIPLE_START_CALLS = "Duplicate call to MParticle.start" val MESSAGE_NO_START_CALL_IN_ON_CREATE = "This Method should call MParticle.start()" @@ -39,15 +40,16 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { "In order to Initialize MParticle, you need to extend android.app.Application, and call MParticle.start() in it's onCreate() method" @JvmStatic - val ISSUE = Issue.create( - "MParticleInitialization", - "mParticle is being started improperly", - "MParticle.start() is not called in the onCreate method of the Application class", - Category.MESSAGES, - 7, - Severity.WARNING, - Implementation(MpApiDetectorKt::class.java, Scope.JAVA_FILE_SCOPE) - ) + val ISSUE = + Issue.create( + "MParticleInitialization", + "mParticle is being started improperly", + "MParticle.start() is not called in the onCreate method of the Application class", + Category.MESSAGES, + 7, + Severity.WARNING, + Implementation(MpApiDetectorKt::class.java, Scope.JAVA_FILE_SCOPE), + ) private val TARGET_METHOD_QUALIFIED_NAME = "com.mparticle.MParticle.start" @@ -83,7 +85,7 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { context.report( ISSUE, applicationOnCreateCall!!.location, - MESSAGE_NO_START_CALL_IN_ON_CREATE + MESSAGE_NO_START_CALL_IN_ON_CREATE, ) } else { context.report(ISSUE, Location.create(context.file), MESSAGE_NO_START_CALL_AT_ALL) @@ -107,8 +109,8 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { * including the same call made through different code paths, these are "Duplicate calls". Any method we find outside of a code path originating * in Application.onCreate() is a "Wrong place call" */ - override fun createUastHandler(context: JavaContext): UElementHandler { - return object : UElementHandler() { + override fun createUastHandler(context: JavaContext): UElementHandler = + object : UElementHandler() { override fun visitMethod(node: UMethod) { try { this@MpApiDetectorKt.context = context @@ -124,9 +126,9 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { extraProperMethodCalls.add( LocationWrapper( context.getLocation( - methodCall - ) - ) + methodCall, + ), + ), ) } } @@ -137,15 +139,15 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { findMethodCall( node, TARGET_METHOD_QUALIFIED_NAME, - 1 + 1, ).forEach { methodCall -> if (isTargetMethod(TARGET_METHOD_QUALIFIED_NAME, methodCall)) { wrongPlaceMethodCalls.add( LocationWrapper( context.getLocation( - methodCall - ) - ) + methodCall, + ), + ), ) } } @@ -155,14 +157,16 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { } } } - } private fun findMethodCall( method: UMethod, targetMethodName: String, - depth: Int + depth: Int, ): List { - fun findMethodCall(element: UElement?, depth: Int): List { + fun findMethodCall( + element: UElement?, + depth: Int, + ): List { var callExpressions = mutableListOf() if (depth == 0) { return callExpressions @@ -183,10 +187,11 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { } } // Test this, but I think this just applies to kotlin extension blocks, like apply, let, also, etc - is UBlockExpression -> element.expressions.forEach { e -> - // increment depth here, because we are essentially diving into the expression - callExpressions.addAll(findMethodCall(e, depth)) - } + is UBlockExpression -> + element.expressions.forEach { e -> + // increment depth here, because we are essentially diving into the expression + callExpressions.addAll(findMethodCall(e, depth)) + } is UDeclarationsExpression -> // This covers the case if there is a method being used to initialize a variable.. // i.e int a = random(); @@ -202,10 +207,11 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { return@apply } val index = text.indexOf(name ?: "") - if (index > 0 && " ${ - text.substring( + if (index > 0 && + " ${ + text.substring( 0, - index + index, ) } ".contains(" fun ") ) { @@ -245,10 +251,9 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { * Especially with local functions, introduced in kotlin, we have to check both whether is method * call refers to a local function, or a class level function, */ - private fun getMethod(callExpression: UCallExpression): UExpression? { - return getLocalMethodImplmentation(callExpression) + private fun getMethod(callExpression: UCallExpression): UExpression? = + getLocalMethodImplmentation(callExpression) ?: getMethodImplementation(callExpression) - } private fun getLocalMethodImplmentation(callExpression: UCallExpression): UExpression? { (callExpression.uastParent as? UBlockExpression) @@ -278,11 +283,13 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { /** * */ - private fun getMethodImplementation(callExpression: UCallExpression): UExpression? { - return (callExpression.tryResolveUDeclaration() as? UMethod)?.uastBody - } + private fun getMethodImplementation(callExpression: UCallExpression): UExpression? = + (callExpression.tryResolveUDeclaration() as? UMethod)?.uastBody - private fun isTargetMethod(targetMethodName: String, element: UCallExpression): Boolean { + private fun isTargetMethod( + targetMethodName: String, + element: UCallExpression, + ): Boolean { // before we resolve the method, do a quick check to see if the name matches if (targetMethodName.endsWith(element.methodName ?: "")) { // if the name matches, do the more expensive operation of resolving the method implementation, @@ -294,13 +301,18 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { return false } - private fun isApplicationSubClassOnCreate(context: JavaContext, method: UMethod): Boolean { - return isApplicationSubClass(context, method) && method.name.equals("onCreate") - } + private fun isApplicationSubClassOnCreate( + context: JavaContext, + method: UMethod, + ): Boolean = isApplicationSubClass(context, method) && method.name.equals("onCreate") - private fun isApplicationSubClass(context: JavaContext, method: UMethod): Boolean { + private fun isApplicationSubClass( + context: JavaContext, + method: UMethod, + ): Boolean { val evaluator = context.evaluator - return method.getParentOfType(true, UClass::class.java) + return method + .getParentOfType(true, UClass::class.java) ?.let { var isApplicationSubclass = evaluator.extendsClass(it, "android.app.Application", false) @@ -315,12 +327,10 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { * before or not, is to compare their location. The Location object does not have an effective "equals()" * method, so this class provides us with a way to compare locations */ - internal class LocationWrapper constructor(val location: Location) : - Comparable { - - override fun hashCode(): Int { - return toString().hashCode() - } + internal class LocationWrapper constructor( + val location: Location, + ) : Comparable { + override fun hashCode(): Int = toString().hashCode() override fun equals(other: Any?): Boolean { if (other === this) { @@ -338,20 +348,19 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { return false } - fun compareLocation(l1: Position?, l2: Position?): Boolean { - return l1?.column == l2?.column && + fun compareLocation( + l1: Position?, + l2: Position?, + ): Boolean = + l1?.column == l2?.column && l1?.line == l2?.line && l1?.offset == l2?.offset - } - override fun toString(): String { - return location.file.getAbsolutePath() + "\n" + - location.start?.offset + " " + location.start?.line + " " + location.start?.column + + override fun toString(): String = + location.file.getAbsolutePath() + "\n" + location.start?.offset + " " + location.start?.line + " " + location.start?.column location.end?.offset + " " + location.end?.line + " " + location.end?.column - } - override fun compareTo(other: LocationWrapper): Int { - return toString().compareTo(other.toString()) - } + override fun compareTo(other: LocationWrapper): Int = toString().compareTo(other.toString()) } } diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/ReferrerReceiverDetector.java b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/ReferrerReceiverDetector.java index 6d35bbfed..cb75722d1 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/ReferrerReceiverDetector.java +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/ReferrerReceiverDetector.java @@ -27,10 +27,10 @@ public class ReferrerReceiverDetector extends ResourceXmlDetector implements Det public static final Issue ISSUE = Issue.create( "MParticleInstallRefReceiver", "com.mparticle.ReferrerReceiver should no longer be used", - "MParticle ReferrerReceiver should no longer be registered in " + ANDROID_MANIFEST_XML + ". In order to receive InstallReferrer data, add the following dependency to your build.gradle\n" + - "\n" + - "dependencies {\n" + - "\timplementation 'com.android.installreferrer:installreferrer:1+'" + + "MParticle ReferrerReceiver should no longer be registered in " + ANDROID_MANIFEST_XML + ". In order to receive InstallReferrer data, add the following dependency to your build.gradle\n" + "\n" + "dependencies {\n" + "\timplementation 'com.android.installreferrer:installreferrer:1+'" "\n}", Category.MESSAGES, 10, diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Constructor.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Constructor.kt index 5a3da1447..274be5a63 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Constructor.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Constructor.kt @@ -7,7 +7,7 @@ import org.jetbrains.uast.UCallExpression data class Constructor( override val parent: Expression, val methodName: String?, - override val node: UCallExpression + override val node: UCallExpression, ) : ParameterizedExpression { override var arguments: List = listOf() @@ -16,18 +16,19 @@ data class Constructor( node.receiverClassName()?.replace(".Builder", "\$Builder") val clazz = Class.forName(qualifiedClassName) val params: List = arguments.resolve() - val argumentClasses = params.map { - if (it != null) { - it::class.java - } else { - Nothing::class.java + val argumentClasses = + params.map { + if (it != null) { + it::class.java + } else { + Nothing::class.java + } } - } val constructor = try { clazz.getConstructor(*argumentClasses.toTypedArray()) } catch (ex: Exception) { - clazz.constructors.firstOrNull() { it.parameterTypes.size == argumentClasses.size } + clazz.constructors.firstOrNull { it.parameterTypes.size == argumentClasses.size } } try { if (constructor != null) { diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Expression.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Expression.kt index 42d1b4a00..397c4b450 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Expression.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Expression.kt @@ -5,7 +5,9 @@ import org.jetbrains.uast.UExpression interface Expression { val node: UExpression val parent: Expression + fun resolve(): Any? + fun forEachExpression(predicate: (Expression) -> Unit) } @@ -13,7 +15,9 @@ interface ParameterizedExpression : Expression { var arguments: List } -class RootParent(override val node: UExpression) : Expression { +class RootParent( + override val node: UExpression, +) : Expression { override val parent: Expression = this override fun resolve() = null diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/MethodCall.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/MethodCall.kt index f6c71b767..0d62baac1 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/MethodCall.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/MethodCall.kt @@ -7,9 +7,8 @@ data class MethodCall( override val parent: Expression, val methodName: String?, override val node: UCallExpression, - var returnValue: Boolean + var returnValue: Boolean, ) : ParameterizedExpression { - override var arguments: List = listOf() init { @@ -21,19 +20,21 @@ data class MethodCall( if (instance == null) { return null } - var matchingMethods = instance::class.java.methods - .filter { it.name == methodName } - .filter { it.parameterCount == arguments.size } + var matchingMethods = + instance::class.java.methods + .filter { it.name == methodName } + .filter { it.parameterCount == arguments.size } if (matchingMethods.size == 1) { - val method = matchingMethods.first { - it.parameterTypes.forEachIndexed { i, type -> - val value = arguments[i].value - if (type.name != "null" && value != null && type.name != value::class.java.name) { - false + val method = + matchingMethods.first { + it.parameterTypes.forEachIndexed { i, type -> + val value = arguments[i].value + if (type.name != "null" && value != null && type.name != value::class.java.name) { + false + } } + true } - true - } val arguments = arguments.resolve() val value = method.invoke(instance, *arguments.toTypedArray()) if (returnValue) { @@ -45,17 +46,11 @@ data class MethodCall( return null } - override fun equals(other: Any?): Boolean { - return node.equals((other as? MethodCall)?.node) - } + override fun equals(other: Any?): Boolean = node.equals((other as? MethodCall)?.node) - override fun hashCode(): Int { - return node.hashCode() - } + override fun hashCode(): Int = node.hashCode() - override fun toString(): String { - return "$methodName (${arguments.joinToString("\n")})" - } + override fun toString(): String = "$methodName (${arguments.joinToString("\n")})" override fun forEachExpression(predicate: (Expression) -> Unit) { parent.forEachExpression(predicate) diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/StaticFactory.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/StaticFactory.kt index 41ccbc983..d9a89e0ce 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/StaticFactory.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/StaticFactory.kt @@ -5,8 +5,10 @@ import com.mparticle.lints.resolve import org.jetbrains.uast.UCallExpression import java.lang.reflect.Method -class StaticFactory(val methodName: String?, override val node: UCallExpression) : - ParameterizedExpression { +class StaticFactory( + val methodName: String?, + override val node: UCallExpression, +) : ParameterizedExpression { override val parent = RootParent(node) override var arguments: List = listOf() @@ -15,19 +17,21 @@ class StaticFactory(val methodName: String?, override val node: UCallExpression) val methods = HashSet() val clazz = Class.forName(qualifiedClassName) methods.addAll(clazz.declaredMethods) - var matchingMethods = methods - .filter { it.name == methodName } - .filter { it.parameterCount == arguments.size } + var matchingMethods = + methods + .filter { it.name == methodName } + .filter { it.parameterCount == arguments.size } if (matchingMethods.size == 1) { - val method = matchingMethods.first { - it.parameterTypes.forEachIndexed { i, type -> - val value = if (arguments.size > i) arguments.get(i).value else null - if (type.name != "null" && value != null && type.name != value::class.java.name) { - false + val method = + matchingMethods.first { + it.parameterTypes.forEachIndexed { i, type -> + val value = if (arguments.size > i) arguments.get(i).value else null + if (type.name != "null" && value != null && type.name != value::class.java.name) { + false + } } + true } - true - } val arguments = arguments.resolve() method.isAccessible = true return method.invoke(null, *arguments.toTypedArray()) diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Value.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Value.kt index 223c280e0..63c2553f1 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Value.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Value.kt @@ -3,22 +3,21 @@ package com.mparticle.lints.dtos import com.mparticle.lints.resolveToEnum import org.jetbrains.uast.UExpression -data class Value(override var parent: Expression, val value: Any?, override val node: UExpression) : - Expression { +data class Value( + override var parent: Expression, + val value: Any?, + override val node: UExpression, +) : Expression { + override fun toString(): String = "$value" - override fun toString(): String { - return "$value" - } - - override fun resolve(): Any? { - return when (value) { + override fun resolve(): Any? = + when (value) { is Expression -> { value.resolve() } is Pair<*, *> -> value.resolveToEnum() else -> value } - } override fun forEachExpression(predicate: (Expression) -> Unit) { predicate(this) diff --git a/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/Constants.kt b/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/Constants.kt index bc9295540..2958b3385 100644 --- a/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/Constants.kt +++ b/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/Constants.kt @@ -8,9 +8,10 @@ object Constants { const val ERROR_WARNING_FORMAT = "%d errors, %d warnings" - fun getErrorWarningMessageString(errors: Int, warnings: Int): String { - return String.format(ERROR_WARNING_FORMAT, errors, warnings) - } + fun getErrorWarningMessageString( + errors: Int, + warnings: Int, + ): String = String.format(ERROR_WARNING_FORMAT, errors, warnings) @Language("JAVA") const val mparticleStub = diff --git a/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/DataplanDetectorTest.kt b/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/DataplanDetectorTest.kt index 7784dd016..dabf4c961 100644 --- a/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/DataplanDetectorTest.kt +++ b/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/DataplanDetectorTest.kt @@ -9,11 +9,11 @@ import org.junit.Test import java.io.File class DataplanDetectorTest : LintDetectorTest() { - @Test fun testCollection() { - val sdkHome = System.getenv("ANDROID_HOME") - ?: "${System.getProperty("user.home")}/Library/Android/sdk" + val sdkHome = + System.getenv("ANDROID_HOME") + ?: "${System.getProperty("user.home")}/Library/Android/sdk" @Language("KT") val source = """ @@ -36,7 +36,8 @@ class DataplanDetectorTest : LintDetectorTest() { } override fun requireCompileSdk() = false + override fun getDetector() = DataplanDetector() - override fun getIssues() = - listOf(DataplanDetector.ISSUE, DataplanDetector.NODE_MISSING, DataplanDetector.NO_DATA_PLAN) + + override fun getIssues() = listOf(DataplanDetector.ISSUE, DataplanDetector.NODE_MISSING, DataplanDetector.NO_DATA_PLAN) } diff --git a/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/ValidationResultDeserializationTest.kt b/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/ValidationResultDeserializationTest.kt index a7d3ac021..bceee257a 100644 --- a/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/ValidationResultDeserializationTest.kt +++ b/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/ValidationResultDeserializationTest.kt @@ -7,33 +7,33 @@ import org.junit.Assert.assertEquals import org.junit.Test class ValidationResultDeserializationTest { - @Test fun testDeserializeValidationResult() { @Language("JSON") - val serialized = """ - [ - { - "event_type": "validation_result", - "data": { - "match": { - "type": "custom_event", - "criteria": { - "event_name": "testEvent1", - "custom_event_type": "Other" - } - }, - "validation_errors": [ - { - "validation_error_type": "unplanned", - "key": "testEvent1", - "error_pointer": "#" - } - ] - } - } - ] - """.trimIndent() + val serialized = + """ + [ + { + "event_type": "validation_result", + "data": { + "match": { + "type": "custom_event", + "criteria": { + "event_name": "testEvent1", + "custom_event_type": "Other" + } + }, + "validation_errors": [ + { + "validation_error_type": "unplanned", + "key": "testEvent1", + "error_pointer": "#" + } + ] + } + } + ] + """.trimIndent() val validationResult = ValidationResult.from(JSONArray(serialized), listOf("")) assertEquals(1, validationResult.size) From 609a66140acba4972f9bf84ccc515f2207a6adbe Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Mon, 15 Sep 2025 17:06:12 -0400 Subject: [PATCH 02/23] fix linting issue and adress review comment --- .github/workflows/daily.yml | 2 +- .trunk/trunk.yaml | 3 - .../internal/MParticleJSInterfaceITest.java | 224 ++++++++--------- .../com.mparticle/PushRegistrationTest.kt | 38 +-- .../database/UpgradeMessageTableTest.kt | 20 +- .../internal/database/UpgradeVersionTest.kt | 18 +- .../database/tables/BreadcrumbTableTest.kt | 14 +- .../database/tables/MessageTableTest.kt | 38 +-- .../database/tables/ReportingTableTest.kt | 12 +- .../database/tables/SessionTableTest.kt | 22 +- .../database/tables/UserAttributeTableTest.kt | 12 +- .../main/java/com/mparticle/MParticle.java | 6 +- .../java/com/mparticle/MParticleOptions.java | 12 +- .../internal/MParticleApiClientImpl.java | 20 +- .../mparticle/internal/SegmentDatabase.java | 18 +- .../database/tables/BreadcrumbTable.java | 16 +- .../database/tables/MessageTable.java | 28 +-- .../database/tables/ReportingTable.java | 16 +- .../database/tables/SessionTable.java | 28 +-- .../internal/database/tables/UploadTable.java | 18 +- .../database/tables/UserAttributesTable.java | 14 +- .../com/mparticle/segmentation/Segment.java | 4 +- .../com/mparticle/internal/Constants.kt | 231 +++++++++--------- .../com/mparticle/kits/KitManagerImpl.java | 10 +- .../testutils/CaptureLogcatOnFailingTest.java | 2 +- 25 files changed, 395 insertions(+), 431 deletions(-) diff --git a/.github/workflows/daily.yml b/.github/workflows/daily.yml index ac168ba84..833a431bd 100644 --- a/.github/workflows/daily.yml +++ b/.github/workflows/daily.yml @@ -48,7 +48,7 @@ jobs: uses: actions/checkout@v4 with: repository: mparticle/mparticle-android-sdk - ref: developmentreq + ref: ${{ inputs.branch_name }} submodules: recursive - name: "Import GPG Key" uses: crazy-max/ghaction-import-gpg@82a020f1f7f605c65dd2449b392a52c3fcfef7ef #v6.0 diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index 1c2f253f6..320944bb2 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -40,12 +40,9 @@ lint: ignore: - linters: [ALL] paths: - - feature/legacy/** - gradlew - linters: - checkov - paths: - - core/network/**/*.json actions: enabled: - trunk-announce diff --git a/android-core/src/androidTest/java/com/mparticle/internal/MParticleJSInterfaceITest.java b/android-core/src/androidTest/java/com/mparticle/internal/MParticleJSInterfaceITest.java index 507e3fc52..3e6286b87 100644 --- a/android-core/src/androidTest/java/com/mparticle/internal/MParticleJSInterfaceITest.java +++ b/android-core/src/androidTest/java/com/mparticle/internal/MParticleJSInterfaceITest.java @@ -69,98 +69,98 @@ public class MParticleJSInterfaceITest extends BaseCleanStartedEachTest { private static String bridgeToken = new RandomUtils().getAlphaString(5); private static String bridgeVersion = "2"; - private static final String jsStartupMParticle = "window.mParticle = {\n" - " config: {\n" - " isDevelopmentMode: true,\n" - " useCookieStorage: true,\n" - " identifyRequest: {\n" - " userIdentities: { email: 'email@example.com', customerid: '123456' }\n" - " },\n " - " requiredWebviewBridgeName: \"" + bridgeToken + "\",\n" - " minWebviewBridgeVersion:\"" + bridgeVersion + "\"\n" - " }\n" - " };" - " window.mParticle = window.mParticle || {};\n" - " window.mParticle.config = window.mParticle.config || {};\n" - " window.mParticle.config.rq = [];\n" - " window.mParticle.ready = function (f) {\n" - " window.mParticle.config.rq.push(f);\n" - " console.log(\"pushed f\");\n" + private static final String jsStartupMParticle = "window.mParticle = {\n" + + " config: {\n" + + " isDevelopmentMode: true,\n" + + " useCookieStorage: true,\n" + + " identifyRequest: {\n" + + " userIdentities: { email: 'email@example.com', customerid: '123456' }\n" + + " },\n " + + " requiredWebviewBridgeName: \"" + bridgeToken + "\",\n" + + " minWebviewBridgeVersion:\"" + bridgeVersion + "\"\n" + + " }\n" + + " };" + + " window.mParticle = window.mParticle || {};\n" + + " window.mParticle.config = window.mParticle.config || {};\n" + + " window.mParticle.config.rq = [];\n" + + " window.mParticle.ready = function (f) {\n" + + " window.mParticle.config.rq.push(f);\n" + + " console.log(\"pushed f\");\n" + " };\n"; private static final String jsTestWrapper = - " mParticle.init();\n" - " mParticle.isDebug = true;\n" - " console.log(\"testing started\")\n " - " window.mParticle.ready(function () {\n" - " console.log(\"mparticle started in JS land\");\n" - "%s\n" + " mParticle.init();\n" + + " mParticle.isDebug = true;\n" + + " console.log(\"testing started\")\n " + + " window.mParticle.ready(function () {\n" + + " console.log(\"mparticle started in JS land\");\n" + + "%s\n" + " })\n"; - private static final String jsSetMpidFunction = "function getCookieDomain() {\n" - " var rootDomain = getDomain(document, location.hostname);\n" - " if (rootDomain === '') {\n" - " return '';\n" - " } else {\n" - " return '.' + rootDomain;\n" - " }\n" - "}\n" - "\n" - "function getDomain(doc, locationHostname) {\n" - " var i,\n" - " testParts,\n" - " mpTest = 'mptest=cookie',\n" - " hostname = locationHostname.split('.');\n" - " for (i = hostname.length - 1; i >= 0; i--) {\n" - " testParts = hostname.slice(i).join('.');\n" - " doc.cookie = mpTest + ';domain=.' + testParts + ';';\n" - " if (doc.cookie.indexOf(mpTest) > -1){\n" - " doc.cookie = mpTest.split('=')[0] + '=;domain=.' + testParts + ';expires=Thu, 01 Jan 1970 00:00:01 GMT;';\n" - " return testParts;\n" - " }\n" - " }\n" - " return '';\n" - "}\n" - "\n" - "\n" - "function setCookie(cname, data, raw) {\n" - " var date = new Date(),\n" - " expires = new Date(date.getTime() +\n" - " (365 * 24 * 60 * 60 * 1000)).toGMTString(),\n" - " domain, cookieDomain,\n" - " value;\n" - "\n" - " value = data;\n" - "\n" - " cookieDomain = getCookieDomain();\n" - "\n" - " if (cookieDomain === '') {\n" - " domain = '';\n" - " } else {\n" - " domain = ';domain=' + cookieDomain;\n" - " }\n" - "\n" - "var cookie = encodeURIComponent(cname) + '=' + value +\n" - " ';expires=' + expires;\n" - " // +\n" - " // ';path=/' + domain;\n" - " console.log(\"SETTNG COOKIE: \" + cookie);\n" - " window.document.cookie = cookie;\n" - " console.log(\"RETRIEVING cookie: \" + window.document.cookie);\n" + private static final String jsSetMpidFunction = "function getCookieDomain() {\n" + + " var rootDomain = getDomain(document, location.hostname);\n" + + " if (rootDomain === '') {\n" + + " return '';\n" + + " } else {\n" + + " return '.' + rootDomain;\n" + + " }\n" + + "}\n" + + "\n" + + "function getDomain(doc, locationHostname) {\n" + + " var i,\n" + + " testParts,\n" + + " mpTest = 'mptest=cookie',\n" + + " hostname = locationHostname.split('.');\n" + + " for (i = hostname.length - 1; i >= 0; i--) {\n" + + " testParts = hostname.slice(i).join('.');\n" + + " doc.cookie = mpTest + ';domain=.' + testParts + ';';\n" + + " if (doc.cookie.indexOf(mpTest) > -1){\n" + + " doc.cookie = mpTest.split('=')[0] + '=;domain=.' + testParts + ';expires=Thu, 01 Jan 1970 00:00:01 GMT;';\n" + + " return testParts;\n" + + " }\n" + + " }\n" + + " return '';\n" + + "}\n" + + "\n" + + "\n" + + "function setCookie(cname, data, raw) {\n" + + " var date = new Date(),\n" + + " expires = new Date(date.getTime() +\n" + + " (365 * 24 * 60 * 60 * 1000)).toGMTString(),\n" + + " domain, cookieDomain,\n" + + " value;\n" + + "\n" + + " value = data;\n" + + "\n" + + " cookieDomain = getCookieDomain();\n" + + "\n" + + " if (cookieDomain === '') {\n" + + " domain = '';\n" + + " } else {\n" + + " domain = ';domain=' + cookieDomain;\n" + + " }\n" + + "\n" + + "var cookie = encodeURIComponent(cname) + '=' + value +\n" + + " ';expires=' + expires;\n" + + " // +\n" + + " // ';path=/' + domain;\n" + + " console.log(\"SETTNG COOKIE: \" + cookie);\n" + + " window.document.cookie = cookie;\n" + + " console.log(\"RETRIEVING cookie: \" + window.document.cookie);\n" + "}"; - private static final String htmlWrapper = "\n" - "\n" - "\n" - " \n" - " Mocha Tests\n" - "\n" - "\n" - "
\n" - "" - "\n" + private static final String htmlWrapper = "\n" + + "\n" + + "\n" + + " \n" + + " Mocha Tests\n" + + "\n" + + "\n" + + "
\n" + + "" + + "\n" + ""; @BeforeClass @@ -170,16 +170,16 @@ public static void beforeClass() { InputStream inputStream = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(R.raw.mparticle_js_sdk); //add in all the basic configuration stuff the server would send with a production sdk fetch from the url jsSdk = new StringBuilder() - .append("window.mParticle = window.mParticle || {};;\n" - "window.mParticle.config = window.mParticle.config || {};;\n" - "window.mParticle.config.serviceUrl = 'jssdk.mparticle.com/v2/JS/';;\n" - "window.mParticle.config.secureServiceUrl = 'jssdks.mparticle.com/v2/JS/';;\n" - "window.mParticle.config.minWebviewBridgeVersion = 1;\n" - "window.mParticle.config.aliasMaxWindow = 90;\n" - "window.mParticle.config.kitConfigs = window.mParticle.config.kitConfigs || [];;\n" + .append("window.mParticle = window.mParticle || {};;\n" + + "window.mParticle.config = window.mParticle.config || {};;\n" + + "window.mParticle.config.serviceUrl = 'jssdk.mparticle.com/v2/JS/';;\n" + + "window.mParticle.config.secureServiceUrl = 'jssdks.mparticle.com/v2/JS/';;\n" + + "window.mParticle.config.minWebviewBridgeVersion = 1;\n" + + "window.mParticle.config.aliasMaxWindow = 90;\n" + + "window.mParticle.config.kitConfigs = window.mParticle.config.kitConfigs || [];;\n" + "window.mParticle.config.pixelConfigs = window.mParticle.config.pixelConfigs || [];;") .append(toString(inputStream)) - .append("window.mParticle.config.requestConfig = false;;\n" + .append("window.mParticle.config.requestConfig = false;;\n" + "mParticle.init(null, window.mParticle.config);;") .toString(); } else { @@ -312,9 +312,9 @@ public void setUserAttribute(String json) { public void testLogEvent() throws Exception { final JSONObject customAttributes = MPUtility.mapToJson(mRandomUtils.getRandomAttributes(10)); final JSONObject customFlagsJSON = MPUtility.mapToJson(getCustomFlags()); - String testJavascript = String.format("mParticle.logEvent('Play Movie Tapped',\n" - " mParticle.EventType.Navigation,\n" - " %s,\n" + String testJavascript = String.format("mParticle.logEvent('Play Movie Tapped'," + + " mParticle.EventType.Navigation," + + " %s," + " %s);", customAttributes.toString(4), customFlagsJSON.toString(4)); final MutableBoolean called = new MutableBoolean(false); final CountDownLatch latch = new MPLatch(2); @@ -369,22 +369,22 @@ public void logEvent(String json) { public void testLogCommerceEvent() throws Exception { final JSONObject customAttributes = MPUtility.mapToJson(mRandomUtils.getRandomAttributes(10)); final JSONObject customFlags = MPUtility.mapToJson(getCustomFlags()); - String testJavascript = String.format("// 1. Create the product\n" - "var product = mParticle.eCommerce.createProduct(\n" - " 'Double Room - Econ Rate', //\n" - " 'econ-1', \n" - " 100.00, \n" - " 4\n" - ");\n" - "\n" - "// 2. Summarize the transaction\n" - "var transactionAttributes = {\n" - " Id: 'foo-transaction-id',\n" - " Revenue: 430.00,\n" - " Tax: 30\n" - "};\n" - "\n" - "// 3. Log the purchase event\n" + String testJavascript = String.format("// 1. Create the product\n" + + "var product = mParticle.eCommerce.createProduct(\n" + + " 'Double Room - Econ Rate', //\n" + + " 'econ-1', \n" + + " 100.00, \n" + + " 4\n" + + ");\n" + + "\n" + + "// 2. Summarize the transaction\n" + + "var transactionAttributes = {\n" + + " Id: 'foo-transaction-id',\n" + + " Revenue: 430.00,\n" + + " Tax: 30\n" + + "};\n" + + "\n" + + "// 3. Log the purchase event\n" + "mParticle.eCommerce.logPurchase(transactionAttributes, product, true, %s, %s);", customAttributes.toString(4), customFlags); final MutableBoolean called = new MutableBoolean(false); diff --git a/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt index cddc693e3..03408abd1 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt @@ -65,22 +65,10 @@ class PushRegistrationTest : BaseCleanStartedEachTest() { val fetchedSenderId = fetchedPushValue.senderId val fetchedInstanceId = fetchedPushValue.instanceId if (pushRegistration.senderId != fetchedSenderId) { - Assert.fail( - "Mismatch! When push value of \"" + pushRegistration.senderId + "\" is set with: " + setPush.name - ". A different value \"" - fetchedSenderId - "\" is returned with:" - getPush.name, - ) + Assert.fail("Mismatch! When push value of \"" + pushRegistration.senderId + "\" is set with: " + setPush.name + ". A different value \"" + fetchedSenderId + "\" is returned with:" + getPush.name) } if (pushRegistration.instanceId != fetchedInstanceId) { - Assert.fail( - "Mismatch! When push value of \"" + pushRegistration.instanceId + "\" is set with: " + setPush.name - ". A different value \"" - fetchedInstanceId - "\" is returned with:" - getPush.name, - ) + Assert.fail("Mismatch! When push value of \"" + pushRegistration.instanceId + "\" is set with: " + setPush.name + ". A different value \"" + fetchedInstanceId + "\" is returned with:" + getPush.name) } } } @@ -100,13 +88,7 @@ class PushRegistrationTest : BaseCleanStartedEachTest() { for (getPush in getPushes) { val fetchedPushRegistration = getPush.pushRegistration if (fetchedPushRegistration.instanceId != null && fetchedPushRegistration.senderId != null) { - Assert.fail( - "Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name - ", and cleared with: " - clearPush.name - ", the value is not null when fetched with:" - getPush.name, - ) + Assert.fail("Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name + ", and cleared with: " + clearPush.name + ", the value is not null when fetched with:" + getPush.name) } } } @@ -124,24 +106,14 @@ class PushRegistrationTest : BaseCleanStartedEachTest() { setPush.setPushRegistration(pushRegistration) for (pushEnabled in pushEnableds) { if (!pushEnabled.isPushEnabled) { - Assert.fail( - "Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name - ", push IS NOT enabled with:" - pushEnabled.name, - ) + Assert.fail("Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name + ", push IS NOT enabled with:" + pushEnabled.name) } } for (clearPush in clearPushes) { clearPush.clearPush() for (pushEnabled in pushEnableds) { if (pushEnabled.isPushEnabled) { - Assert.fail( - "Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name - ", and cleared with: " - clearPush.name - ", push IS enabled with:" - pushEnabled.name, - ) + Assert.fail("Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name + ", and cleared with: " + clearPush.name + ", push IS enabled with:" + pushEnabled.name) } } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeMessageTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeMessageTableTest.kt index bd7767494..7e59e9efe 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeMessageTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeMessageTableTest.kt @@ -48,16 +48,16 @@ class UpgradeMessageTableTest : BaseTableTest() { companion object { const val CREATE_MESSAGES_DDL = - "CREATE TABLE IF NOT EXISTS " + MessageTable.MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID - " INTEGER PRIMARY KEY AUTOINCREMENT, " - MessageTable.MessageTableColumns.SESSION_ID + " STRING NOT NULL, " - MessageTable.MessageTableColumns.API_KEY + " STRING NOT NULL, " - MessageTable.MessageTableColumns.MESSAGE + " TEXT, " - MessageTable.MessageTableColumns.STATUS + " INTEGER, " - MessageTable.MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " - MessageTable.MessageTableColumns.MESSAGE_TYPE + " TEXT, " - MessageTable.MessageTableColumns.CF_UUID + " TEXT, " - MessageTable.MessageTableColumns.MP_ID + " INTEGER" + "CREATE TABLE IF NOT EXISTS " + MessageTable.MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID + + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + MessageTable.MessageTableColumns.SESSION_ID + " STRING NOT NULL, " + + MessageTable.MessageTableColumns.API_KEY + " STRING NOT NULL, " + + MessageTable.MessageTableColumns.MESSAGE + " TEXT, " + + MessageTable.MessageTableColumns.STATUS + " INTEGER, " + + MessageTable.MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " + + MessageTable.MessageTableColumns.MESSAGE_TYPE + " TEXT, " + + MessageTable.MessageTableColumns.CF_UUID + " TEXT, " + + MessageTable.MessageTableColumns.MP_ID + " INTEGER" + ");" } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeVersionTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeVersionTest.kt index 8b80cb5e7..63a9716dd 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeVersionTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeVersionTest.kt @@ -208,15 +208,15 @@ class UpgradeVersionTest : BaseTableTest() { companion object { const val CREATE_GCM_MSG_DDL = - "CREATE TABLE IF NOT EXISTS " + FcmMessageTableColumns.TABLE_NAME + " (" + FcmMessageTableColumns.CONTENT_ID - " INTEGER PRIMARY KEY, " - FcmMessageTableColumns.PAYLOAD + " TEXT NOT NULL, " - FcmMessageTableColumns.APPSTATE + " TEXT NOT NULL, " - FcmMessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " - FcmMessageTableColumns.EXPIRATION + " INTEGER NOT NULL, " - FcmMessageTableColumns.BEHAVIOR + " INTEGER NOT NULL," - FcmMessageTableColumns.CAMPAIGN_ID + " TEXT NOT NULL, " - FcmMessageTableColumns.DISPLAYED_AT + " INTEGER NOT NULL " + "CREATE TABLE IF NOT EXISTS " + FcmMessageTableColumns.TABLE_NAME + " (" + FcmMessageTableColumns.CONTENT_ID + + " INTEGER PRIMARY KEY, " + + FcmMessageTableColumns.PAYLOAD + " TEXT NOT NULL, " + + FcmMessageTableColumns.APPSTATE + " TEXT NOT NULL, " + + FcmMessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " + + FcmMessageTableColumns.EXPIRATION + " INTEGER NOT NULL, " + + FcmMessageTableColumns.BEHAVIOR + " INTEGER NOT NULL," + + FcmMessageTableColumns.CAMPAIGN_ID + " TEXT NOT NULL, " + + FcmMessageTableColumns.DISPLAYED_AT + " INTEGER NOT NULL " + ");" } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BreadcrumbTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BreadcrumbTableTest.kt index f317644a9..deb678347 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BreadcrumbTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BreadcrumbTableTest.kt @@ -32,13 +32,13 @@ class BreadcrumbTableTest : BaseTableTest() { companion object { const val old_CREATE_BREADCRUMBS_DDL = - "CREATE TABLE IF NOT EXISTS " + BreadcrumbTable.BreadcrumbTableColumns.TABLE_NAME + " (" + BaseColumns._ID - " INTEGER PRIMARY KEY AUTOINCREMENT, " - BreadcrumbTable.BreadcrumbTableColumns.SESSION_ID + " STRING NOT NULL, " - BreadcrumbTable.BreadcrumbTableColumns.API_KEY + " STRING NOT NULL, " - BreadcrumbTable.BreadcrumbTableColumns.MESSAGE + " TEXT, " - BreadcrumbTable.BreadcrumbTableColumns.CREATED_AT + " INTEGER NOT NULL, " - BreadcrumbTable.BreadcrumbTableColumns.CF_UUID + " TEXT" + "CREATE TABLE IF NOT EXISTS " + BreadcrumbTable.BreadcrumbTableColumns.TABLE_NAME + " (" + BaseColumns._ID + + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + BreadcrumbTable.BreadcrumbTableColumns.SESSION_ID + " STRING NOT NULL, " + + BreadcrumbTable.BreadcrumbTableColumns.API_KEY + " STRING NOT NULL, " + + BreadcrumbTable.BreadcrumbTableColumns.MESSAGE + " TEXT, " + + BreadcrumbTable.BreadcrumbTableColumns.CREATED_AT + " INTEGER NOT NULL, " + + BreadcrumbTable.BreadcrumbTableColumns.CF_UUID + " TEXT" + ");" } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/MessageTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/MessageTableTest.kt index e3af25531..018bb9aae 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/MessageTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/MessageTableTest.kt @@ -61,27 +61,27 @@ class MessageTableTest : BaseTableTest() { companion object { const val old_no_mpid_CREATE_MESSAGES_DDL = - "CREATE TABLE IF NOT EXISTS " + MessageTable.MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID - " INTEGER PRIMARY KEY AUTOINCREMENT, " - MessageTable.MessageTableColumns.SESSION_ID + " STRING NOT NULL, " - MessageTable.MessageTableColumns.API_KEY + " STRING NOT NULL, " - MessageTable.MessageTableColumns.MESSAGE + " TEXT, " - MessageTable.MessageTableColumns.STATUS + " INTEGER, " - MessageTable.MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " - MessageTable.MessageTableColumns.MESSAGE_TYPE + " TEXT, " - MessageTable.MessageTableColumns.CF_UUID + " TEXT" + "CREATE TABLE IF NOT EXISTS " + MessageTable.MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID + + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + MessageTable.MessageTableColumns.SESSION_ID + " STRING NOT NULL, " + + MessageTable.MessageTableColumns.API_KEY + " STRING NOT NULL, " + + MessageTable.MessageTableColumns.MESSAGE + " TEXT, " + + MessageTable.MessageTableColumns.STATUS + " INTEGER, " + + MessageTable.MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " + + MessageTable.MessageTableColumns.MESSAGE_TYPE + " TEXT, " + + MessageTable.MessageTableColumns.CF_UUID + " TEXT" + ");" private const val old_no_dp_CREATE_MESSAGES_DDL = - "CREATE TABLE IF NOT EXISTS " + MessageTable.MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID - " INTEGER PRIMARY KEY AUTOINCREMENT, " - MessageTable.MessageTableColumns.SESSION_ID + " STRING NOT NULL, " - MessageTable.MessageTableColumns.API_KEY + " STRING NOT NULL, " - MessageTable.MessageTableColumns.MESSAGE + " TEXT, " - MessageTable.MessageTableColumns.STATUS + " INTEGER, " - MessageTable.MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " - MessageTable.MessageTableColumns.MESSAGE_TYPE + " TEXT, " - MessageTable.MessageTableColumns.CF_UUID + " TEXT, " - MessageTable.MessageTableColumns.MP_ID + " INTEGER " + "CREATE TABLE IF NOT EXISTS " + MessageTable.MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID + + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + MessageTable.MessageTableColumns.SESSION_ID + " STRING NOT NULL, " + + MessageTable.MessageTableColumns.API_KEY + " STRING NOT NULL, " + + MessageTable.MessageTableColumns.MESSAGE + " TEXT, " + + MessageTable.MessageTableColumns.STATUS + " INTEGER, " + + MessageTable.MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " + + MessageTable.MessageTableColumns.MESSAGE_TYPE + " TEXT, " + + MessageTable.MessageTableColumns.CF_UUID + " TEXT, " + + MessageTable.MessageTableColumns.MP_ID + " INTEGER " + ");" } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/ReportingTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/ReportingTableTest.kt index 40e4e8a76..0915a2d2f 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/ReportingTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/ReportingTableTest.kt @@ -32,12 +32,12 @@ class ReportingTableTest : BaseTableTest() { companion object { const val old_CREATE_REPORTING_DDL = - "CREATE TABLE IF NOT EXISTS " + ReportingTable.ReportingTableColumns.TABLE_NAME + " (" + BaseColumns._ID - " INTEGER PRIMARY KEY AUTOINCREMENT, " - ReportingTable.ReportingTableColumns.MODULE_ID + " INTEGER NOT NULL, " - ReportingTable.ReportingTableColumns.MESSAGE + " TEXT NOT NULL, " - ReportingTable.ReportingTableColumns.SESSION_ID + " STRING NOT NULL, " - ReportingTable.ReportingTableColumns.CREATED_AT + " INTEGER NOT NULL" + "CREATE TABLE IF NOT EXISTS " + ReportingTable.ReportingTableColumns.TABLE_NAME + " (" + BaseColumns._ID + + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + ReportingTable.ReportingTableColumns.MODULE_ID + " INTEGER NOT NULL, " + + ReportingTable.ReportingTableColumns.MESSAGE + " TEXT NOT NULL, " + + ReportingTable.ReportingTableColumns.SESSION_ID + " STRING NOT NULL, " + + ReportingTable.ReportingTableColumns.CREATED_AT + " INTEGER NOT NULL" + ");" } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/SessionTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/SessionTableTest.kt index 96e3eeb9b..b1ec29a71 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/SessionTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/SessionTableTest.kt @@ -32,17 +32,17 @@ class SessionTableTest : BaseTableTest() { companion object { const val old_CREATE_SESSION_DDL = - "CREATE TABLE IF NOT EXISTS " + SessionTable.SessionTableColumns.TABLE_NAME + " (" + BaseColumns._ID - " INTEGER PRIMARY KEY AUTOINCREMENT, " - SessionTable.SessionTableColumns.SESSION_ID + " STRING NOT NULL, " - SessionTable.SessionTableColumns.API_KEY + " STRING NOT NULL, " - SessionTable.SessionTableColumns.START_TIME + " INTEGER NOT NULL," - SessionTable.SessionTableColumns.END_TIME + " INTEGER NOT NULL," - SessionTable.SessionTableColumns.SESSION_FOREGROUND_LENGTH + " INTEGER NOT NULL," - SessionTable.SessionTableColumns.ATTRIBUTES + " TEXT, " - SessionTable.SessionTableColumns.STATUS + " TEXT," - SessionTable.SessionTableColumns.APP_INFO + " TEXT, " - SessionTable.SessionTableColumns.DEVICE_INFO + " TEXT" + "CREATE TABLE IF NOT EXISTS " + SessionTable.SessionTableColumns.TABLE_NAME + " (" + BaseColumns._ID + + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + SessionTable.SessionTableColumns.SESSION_ID + " STRING NOT NULL, " + + SessionTable.SessionTableColumns.API_KEY + " STRING NOT NULL, " + + SessionTable.SessionTableColumns.START_TIME + " INTEGER NOT NULL," + + SessionTable.SessionTableColumns.END_TIME + " INTEGER NOT NULL," + + SessionTable.SessionTableColumns.SESSION_FOREGROUND_LENGTH + " INTEGER NOT NULL," + + SessionTable.SessionTableColumns.ATTRIBUTES + " TEXT, " + + SessionTable.SessionTableColumns.STATUS + " TEXT," + + SessionTable.SessionTableColumns.APP_INFO + " TEXT, " + + SessionTable.SessionTableColumns.DEVICE_INFO + " TEXT" + ");" } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UserAttributeTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UserAttributeTableTest.kt index 3b938ccf6..0aacff006 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UserAttributeTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UserAttributeTableTest.kt @@ -32,12 +32,12 @@ class UserAttributeTableTest : BaseTableTest() { companion object { const val old_CREATE_USER_ATTRIBUTES_DDL = - "CREATE TABLE IF NOT EXISTS " + UserAttributesTable.UserAttributesTableColumns.TABLE_NAME + " (" + BaseColumns._ID - " INTEGER PRIMARY KEY AUTOINCREMENT, " - UserAttributesTable.UserAttributesTableColumns.ATTRIBUTE_KEY + " COLLATE NOCASE NOT NULL, " - UserAttributesTable.UserAttributesTableColumns.ATTRIBUTE_VALUE + " TEXT, " - UserAttributesTable.UserAttributesTableColumns.IS_LIST + " INTEGER NOT NULL, " - UserAttributesTable.UserAttributesTableColumns.CREATED_AT + " INTEGER NOT NULL " + "CREATE TABLE IF NOT EXISTS " + UserAttributesTable.UserAttributesTableColumns.TABLE_NAME + " (" + BaseColumns._ID + + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + UserAttributesTable.UserAttributesTableColumns.ATTRIBUTE_KEY + " COLLATE NOCASE NOT NULL, " + + UserAttributesTable.UserAttributesTableColumns.ATTRIBUTE_VALUE + " TEXT, " + + UserAttributesTable.UserAttributesTableColumns.IS_LIST + " INTEGER NOT NULL, " + + UserAttributesTable.UserAttributesTableColumns.CREATED_AT + " INTEGER NOT NULL " + ");" } } diff --git a/android-core/src/main/java/com/mparticle/MParticle.java b/android-core/src/main/java/com/mparticle/MParticle.java index e1d292c3f..26d07c2d4 100644 --- a/android-core/src/main/java/com/mparticle/MParticle.java +++ b/android-core/src/main/java/com/mparticle/MParticle.java @@ -656,7 +656,7 @@ public void logError(@NonNull String message, @Nullable Map erro mAppStateManager.ensureActiveSession(); JSONObject eventDataJSON = MPUtility.enforceAttributeConstraints(errorAttributes); mMessageManager.logErrorEvent(message, null, eventDataJSON); - Logger.debug("Logged error with message: " + (message == null ? "" : message) + Logger.debug("Logged error with message: " + (message == null ? "" : message) + " with data: " + (eventDataJSON == null ? "" : eventDataJSON.toString()) ); mKitManager.logError(message, errorAttributes); @@ -729,8 +729,8 @@ public void logException(@NonNull Exception exception, @Nullable Map" : message) - " with data: " + (eventDataJSON == null ? "" : eventDataJSON.toString()) + "Logged exception with message: " + (message == null ? "" : message) + + " with data: " + (eventDataJSON == null ? "" : eventDataJSON.toString()) + " with exception: " + (exception == null ? "" : exception.getMessage()) ); mKitManager.logException(exception, eventData, message); diff --git a/android-core/src/main/java/com/mparticle/MParticleOptions.java b/android-core/src/main/java/com/mparticle/MParticleOptions.java index 3dd6cd6b8..e6fd4c123 100644 --- a/android-core/src/main/java/com/mparticle/MParticleOptions.java +++ b/android-core/src/main/java/com/mparticle/MParticleOptions.java @@ -906,12 +906,12 @@ public String toString() { } catch (JSONException e) { dataplanString = "Unable to print Dataplan"; } - return "DataplanOptions {" - "\n\tblockUserAttributes=" + blockUserAttributes - ", \n\tblockUserIdentities=" + blockUserIdentities - ", \n\tblockEventAttributes=" + blockEventAttributes - ", \n\tblockEvents=" + blockEvents - ",\n\tdataplan=" + dataplanString + return "DataplanOptions {" + + "\n\tblockUserAttributes=" + blockUserAttributes + + ", \n\tblockUserIdentities=" + blockUserIdentities + + ", \n\tblockEventAttributes=" + blockEventAttributes + + ", \n\tblockEvents=" + blockEvents + + ",\n\tdataplan=" + dataplanString + "\n}"; } diff --git a/android-core/src/main/java/com/mparticle/internal/MParticleApiClientImpl.java b/android-core/src/main/java/com/mparticle/internal/MParticleApiClientImpl.java index 656cf5d89..49ae09eb4 100644 --- a/android-core/src/main/java/com/mparticle/internal/MParticleApiClientImpl.java +++ b/android-core/src/main/java/com/mparticle/internal/MParticleApiClientImpl.java @@ -155,7 +155,7 @@ public void fetchConfig(boolean force) throws IOException, MPConfigException { addMessageSignature(connection, null); - Logger.verbose("Config request attempt:\n" + Logger.verbose("Config request attempt:\n" + "URL- " + mConfigUrl.toString()); if (InternalListenerManager.isEnabled()) { @@ -174,9 +174,9 @@ public void fetchConfig(boolean force) throws IOException, MPConfigException { if (responseCode >= 200 && responseCode < 300) { parseCookies(response); - Logger.verbose("Config result: \n " - connection.getResponseCode() + ": " - connection.getResponseMessage() + "\n" + Logger.verbose("Config result: \n " + + connection.getResponseCode() + ": " + + connection.getResponseMessage() + "\n" + "response:\n" + response.toString()); String newEtag = connection.getHeaderField("ETag"); @@ -260,7 +260,7 @@ public int sendMessageBatch(@NonNull String message, @NonNull UploadSettings upl makeUrlRequest(Endpoint.EVENTS, connection, message, true); - Logger.verbose("Upload request attempt:\n" + Logger.verbose("Upload request attempt:\n" + "URL- " + eventUrl.toString()); Logger.verbose(message); @@ -273,9 +273,9 @@ public int sendMessageBatch(@NonNull String message, @NonNull UploadSettings upl InternalListenerManager.getListener().onNetworkRequestFinished(SdkListener.Endpoint.EVENTS, connection.getURL().toString(), response, responseCode); } - Logger.verbose("Upload result response: \n" - connection.getResponseCode() + ": " - connection.getResponseMessage() + "\n" + Logger.verbose("Upload result response: \n" + + connection.getResponseCode() + ": " + + connection.getResponseMessage() + "\n" + "response:\n" + response.toString()); parseCookies(response); } else { @@ -317,8 +317,8 @@ public AliasNetworkResponse sendAliasRequest(@NonNull String message, @NonNull U String error = ""; JSONObject response = new JSONObject(); if (responseCode >= 200 && responseCode < 300) { - Logger.verbose("Alias Request response: \n " - connection.getResponseCode() + ": " + Logger.verbose("Alias Request response: \n " + + connection.getResponseCode() + ": " + connection.getResponseMessage()); } else { response = MPUtility.getJsonResponse(connection); diff --git a/android-core/src/main/java/com/mparticle/internal/SegmentDatabase.java b/android-core/src/main/java/com/mparticle/internal/SegmentDatabase.java index 7c19f3bab..761de42c8 100644 --- a/android-core/src/main/java/com/mparticle/internal/SegmentDatabase.java +++ b/android-core/src/main/java/com/mparticle/internal/SegmentDatabase.java @@ -24,10 +24,10 @@ interface SegmentTable { } private static final String CREATE_SEGMENT_DDL = - "CREATE TABLE IF NOT EXISTS " + SegmentTable.TABLE_NAME + " (" - "_id INTEGER PRIMARY KEY, " - SegmentTable.NAME + " TEXT NOT NULL, " - SegmentTable.ENDPOINTS + " TEXT " + "CREATE TABLE IF NOT EXISTS " + SegmentTable.TABLE_NAME + " (" + + "_id INTEGER PRIMARY KEY, " + + SegmentTable.NAME + " TEXT NOT NULL, " + + SegmentTable.ENDPOINTS + " TEXT " + ");"; interface SegmentMembershipTable { @@ -39,11 +39,11 @@ interface SegmentMembershipTable { } private static final String CREATE_SEGMENT_MEMBERSHIP_DDL = - "CREATE TABLE IF NOT EXISTS " + SegmentMembershipTable.TABLE_NAME + " (" - "_id INTEGER PRIMARY KEY AUTOINCREMENT, " - SegmentMembershipTable.SEGMENT_ID + " INTEGER NOT NULL, " - SegmentMembershipTable.TIMESTAMP + " REAL NOT NULL, " - SegmentMembershipTable.MEMBERSHIP_ACTION + " INTEGER NOT NULL, " + "CREATE TABLE IF NOT EXISTS " + SegmentMembershipTable.TABLE_NAME + " (" + + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + + SegmentMembershipTable.SEGMENT_ID + " INTEGER NOT NULL, " + + SegmentMembershipTable.TIMESTAMP + " REAL NOT NULL, " + + SegmentMembershipTable.MEMBERSHIP_ACTION + " INTEGER NOT NULL, " + " FOREIGN KEY (" + SegmentMembershipTable.SEGMENT_ID + ") REFERENCES " + SegmentTable.TABLE_NAME + " (" + SegmentTable.SEGMENT_ID + "));"; diff --git a/android-core/src/main/java/com/mparticle/internal/database/tables/BreadcrumbTable.java b/android-core/src/main/java/com/mparticle/internal/database/tables/BreadcrumbTable.java index d0308210c..9636906a8 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/tables/BreadcrumbTable.java +++ b/android-core/src/main/java/com/mparticle/internal/database/tables/BreadcrumbTable.java @@ -20,13 +20,13 @@ protected interface BreadcrumbTableColumns { } static final String CREATE_BREADCRUMBS_DDL = - "CREATE TABLE IF NOT EXISTS " + BreadcrumbTableColumns.TABLE_NAME + " (" + BaseColumns._ID - " INTEGER PRIMARY KEY AUTOINCREMENT, " - BreadcrumbTableColumns.SESSION_ID + " STRING NOT NULL, " - BreadcrumbTableColumns.API_KEY + " STRING NOT NULL, " - BreadcrumbTableColumns.MESSAGE + " TEXT, " - BreadcrumbTableColumns.CREATED_AT + " INTEGER NOT NULL, " - BreadcrumbTableColumns.CF_UUID + " TEXT, " - BreadcrumbTableColumns.MP_ID + " INTEGER" + "CREATE TABLE IF NOT EXISTS " + BreadcrumbTableColumns.TABLE_NAME + " (" + BaseColumns._ID + + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + BreadcrumbTableColumns.SESSION_ID + " STRING NOT NULL, " + + BreadcrumbTableColumns.API_KEY + " STRING NOT NULL, " + + BreadcrumbTableColumns.MESSAGE + " TEXT, " + + BreadcrumbTableColumns.CREATED_AT + " INTEGER NOT NULL, " + + BreadcrumbTableColumns.CF_UUID + " TEXT, " + + BreadcrumbTableColumns.MP_ID + " INTEGER" + ");"; } diff --git a/android-core/src/main/java/com/mparticle/internal/database/tables/MessageTable.java b/android-core/src/main/java/com/mparticle/internal/database/tables/MessageTable.java index 736993199..f3fb7d42c 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/tables/MessageTable.java +++ b/android-core/src/main/java/com/mparticle/internal/database/tables/MessageTable.java @@ -4,9 +4,9 @@ public class MessageTable extends MpIdDependentTable { - public static final String ADD_DATAPLAN_VERSION_COLUMN = "ALTER TABLE " + MessageTableColumns.TABLE_NAME + public static final String ADD_DATAPLAN_VERSION_COLUMN = "ALTER TABLE " + MessageTableColumns.TABLE_NAME + " ADD COLUMN " + MessageTableColumns.DATAPLAN_VERSION + " NUMBER"; - public static final String ADD_DATAPLAN_ID_COLUMN = "ALTER TABLE " + MessageTableColumns.TABLE_NAME + public static final String ADD_DATAPLAN_ID_COLUMN = "ALTER TABLE " + MessageTableColumns.TABLE_NAME + " ADD COLUMN " + MessageTableColumns.DATAPLAN_ID + " TEXT"; @Override @@ -29,18 +29,18 @@ public interface MessageTableColumns extends BaseColumns { } static final String CREATE_MESSAGES_DDL = - "CREATE TABLE IF NOT EXISTS " + MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID - " INTEGER PRIMARY KEY AUTOINCREMENT, " - MessageTableColumns.SESSION_ID + " STRING NOT NULL, " - MessageTableColumns.API_KEY + " STRING NOT NULL, " - MessageTableColumns.MESSAGE + " TEXT, " - MessageTableColumns.STATUS + " INTEGER, " - MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " - MessageTableColumns.MESSAGE_TYPE + " TEXT, " - MessageTableColumns.CF_UUID + " TEXT, " - MessageTableColumns.MP_ID + " INTEGER, " - MessageTableColumns.DATAPLAN_ID + " TEXT," - MessageTableColumns.DATAPLAN_VERSION + " INTEGER" + "CREATE TABLE IF NOT EXISTS " + MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID + + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + MessageTableColumns.SESSION_ID + " STRING NOT NULL, " + + MessageTableColumns.API_KEY + " STRING NOT NULL, " + + MessageTableColumns.MESSAGE + " TEXT, " + + MessageTableColumns.STATUS + " INTEGER, " + + MessageTableColumns.CREATED_AT + " INTEGER NOT NULL, " + + MessageTableColumns.MESSAGE_TYPE + " TEXT, " + + MessageTableColumns.CF_UUID + " TEXT, " + + MessageTableColumns.MP_ID + " INTEGER, " + + MessageTableColumns.DATAPLAN_ID + " TEXT," + + MessageTableColumns.DATAPLAN_VERSION + " INTEGER" + ");"; } diff --git a/android-core/src/main/java/com/mparticle/internal/database/tables/ReportingTable.java b/android-core/src/main/java/com/mparticle/internal/database/tables/ReportingTable.java index fac26a7cc..fe919d13e 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/tables/ReportingTable.java +++ b/android-core/src/main/java/com/mparticle/internal/database/tables/ReportingTable.java @@ -19,16 +19,16 @@ protected interface ReportingTableColumns extends BaseColumns { } static final String CREATE_REPORTING_DDL = - "CREATE TABLE IF NOT EXISTS " + ReportingTableColumns.TABLE_NAME + " (" + BaseColumns._ID - " INTEGER PRIMARY KEY AUTOINCREMENT, " - ReportingTableColumns.MODULE_ID + " INTEGER NOT NULL, " - ReportingTableColumns.MESSAGE + " TEXT NOT NULL, " - ReportingTableColumns.SESSION_ID + " STRING NOT NULL, " - ReportingTableColumns.CREATED_AT + " INTEGER NOT NULL, " - ReportingTableColumns.MP_ID + " INTEGER" + "CREATE TABLE IF NOT EXISTS " + ReportingTableColumns.TABLE_NAME + " (" + BaseColumns._ID + + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + ReportingTableColumns.MODULE_ID + " INTEGER NOT NULL, " + + ReportingTableColumns.MESSAGE + " TEXT NOT NULL, " + + ReportingTableColumns.SESSION_ID + " STRING NOT NULL, " + + ReportingTableColumns.CREATED_AT + " INTEGER NOT NULL, " + + ReportingTableColumns.MP_ID + " INTEGER" + ");"; - static final String REPORTING_ADD_SESSION_ID_COLUMN = "ALTER TABLE " + ReportingTableColumns.TABLE_NAME + static final String REPORTING_ADD_SESSION_ID_COLUMN = "ALTER TABLE " + ReportingTableColumns.TABLE_NAME + " ADD COLUMN " + ReportingTableColumns.SESSION_ID + " STRING"; diff --git a/android-core/src/main/java/com/mparticle/internal/database/tables/SessionTable.java b/android-core/src/main/java/com/mparticle/internal/database/tables/SessionTable.java index 93c8ce077..67efa484d 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/tables/SessionTable.java +++ b/android-core/src/main/java/com/mparticle/internal/database/tables/SessionTable.java @@ -37,24 +37,24 @@ public interface SessionStatus { String CLOSED = "1"; } - static final String SESSION_ADD_DEVICE_INFO_COLUMN = "ALTER TABLE " + SessionTableColumns.TABLE_NAME + static final String SESSION_ADD_DEVICE_INFO_COLUMN = "ALTER TABLE " + SessionTableColumns.TABLE_NAME + " ADD COLUMN " + SessionTableColumns.DEVICE_INFO + " TEXT"; - static final String SESSION_ADD_APP_INFO_COLUMN = "ALTER TABLE " + SessionTableColumns.TABLE_NAME + static final String SESSION_ADD_APP_INFO_COLUMN = "ALTER TABLE " + SessionTableColumns.TABLE_NAME + " ADD COLUMN " + SessionTableColumns.APP_INFO + " TEXT"; static final String CREATE_SESSIONS_DDL = - "CREATE TABLE IF NOT EXISTS " + SessionTableColumns.TABLE_NAME + " (" + BaseColumns._ID - " INTEGER PRIMARY KEY AUTOINCREMENT, " - SessionTableColumns.SESSION_ID + " STRING NOT NULL, " - SessionTableColumns.API_KEY + " STRING NOT NULL, " - SessionTableColumns.START_TIME + " INTEGER NOT NULL," - SessionTableColumns.END_TIME + " INTEGER NOT NULL," - SessionTableColumns.SESSION_FOREGROUND_LENGTH + " INTEGER NOT NULL," - SessionTableColumns.ATTRIBUTES + " TEXT, " - SessionTableColumns.STATUS + " TEXT," - SessionTableColumns.APP_INFO + " TEXT, " - SessionTableColumns.DEVICE_INFO + " TEXT, " - SessionTableColumns.MP_ID + " INTEGER" + "CREATE TABLE IF NOT EXISTS " + SessionTableColumns.TABLE_NAME + " (" + BaseColumns._ID + + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + SessionTableColumns.SESSION_ID + " STRING NOT NULL, " + + SessionTableColumns.API_KEY + " STRING NOT NULL, " + + SessionTableColumns.START_TIME + " INTEGER NOT NULL," + + SessionTableColumns.END_TIME + " INTEGER NOT NULL," + + SessionTableColumns.SESSION_FOREGROUND_LENGTH + " INTEGER NOT NULL," + + SessionTableColumns.ATTRIBUTES + " TEXT, " + + SessionTableColumns.STATUS + " TEXT," + + SessionTableColumns.APP_INFO + " TEXT, " + + SessionTableColumns.DEVICE_INFO + " TEXT, " + + SessionTableColumns.MP_ID + " INTEGER" + ");"; } diff --git a/android-core/src/main/java/com/mparticle/internal/database/tables/UploadTable.java b/android-core/src/main/java/com/mparticle/internal/database/tables/UploadTable.java index 580552750..c089ba959 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/tables/UploadTable.java +++ b/android-core/src/main/java/com/mparticle/internal/database/tables/UploadTable.java @@ -23,16 +23,16 @@ protected interface UploadTableColumns extends BaseColumns { static final String CREATE_UPLOADS_DDL = - "CREATE TABLE IF NOT EXISTS " + UploadTableColumns.TABLE_NAME + " (" + BaseColumns._ID - " INTEGER PRIMARY KEY AUTOINCREMENT, " - UploadTableColumns.API_KEY + " STRING NOT NULL, " - UploadTableColumns.MESSAGE + " TEXT, " - UploadTableColumns.CREATED_AT + " INTEGER NOT NULL, " - UploadTableColumns.REQUEST_TYPE + " TEXT, " - UploadTableColumns.SESSION_ID + " TEXT, " - UploadTableColumns.UPLOAD_SETTINGS + " TEXT" + "CREATE TABLE IF NOT EXISTS " + UploadTableColumns.TABLE_NAME + " (" + BaseColumns._ID + + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + UploadTableColumns.API_KEY + " STRING NOT NULL, " + + UploadTableColumns.MESSAGE + " TEXT, " + + UploadTableColumns.CREATED_AT + " INTEGER NOT NULL, " + + UploadTableColumns.REQUEST_TYPE + " TEXT, " + + UploadTableColumns.SESSION_ID + " TEXT, " + + UploadTableColumns.UPLOAD_SETTINGS + " TEXT" + ");"; - static final String UPLOAD_ADD_UPLOAD_SETTINGS_COLUMN = "ALTER TABLE " + UploadTableColumns.TABLE_NAME + static final String UPLOAD_ADD_UPLOAD_SETTINGS_COLUMN = "ALTER TABLE " + UploadTableColumns.TABLE_NAME + " ADD COLUMN " + UploadTableColumns.UPLOAD_SETTINGS + " TEXT"; } diff --git a/android-core/src/main/java/com/mparticle/internal/database/tables/UserAttributesTable.java b/android-core/src/main/java/com/mparticle/internal/database/tables/UserAttributesTable.java index 1dbdf5d1a..882d2da31 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/tables/UserAttributesTable.java +++ b/android-core/src/main/java/com/mparticle/internal/database/tables/UserAttributesTable.java @@ -19,12 +19,12 @@ protected interface UserAttributesTableColumns { } static final String CREATE_USER_ATTRIBUTES_DDL = - "CREATE TABLE IF NOT EXISTS " + UserAttributesTableColumns.TABLE_NAME + " (" + BaseColumns._ID - " INTEGER PRIMARY KEY AUTOINCREMENT, " - UserAttributesTableColumns.ATTRIBUTE_KEY + " COLLATE NOCASE NOT NULL, " - UserAttributesTableColumns.ATTRIBUTE_VALUE + " TEXT, " - UserAttributesTableColumns.IS_LIST + " INTEGER NOT NULL, " - UserAttributesTableColumns.CREATED_AT + " INTEGER NOT NULL, " - UserAttributesTableColumns.MP_ID + " INTEGER" + "CREATE TABLE IF NOT EXISTS " + UserAttributesTableColumns.TABLE_NAME + " (" + BaseColumns._ID + + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + UserAttributesTableColumns.ATTRIBUTE_KEY + " COLLATE NOCASE NOT NULL, " + + UserAttributesTableColumns.ATTRIBUTE_VALUE + " TEXT, " + + UserAttributesTableColumns.IS_LIST + " INTEGER NOT NULL, " + + UserAttributesTableColumns.CREATED_AT + " INTEGER NOT NULL, " + + UserAttributesTableColumns.MP_ID + " INTEGER" + ");"; } diff --git a/android-core/src/main/java/com/mparticle/segmentation/Segment.java b/android-core/src/main/java/com/mparticle/segmentation/Segment.java index 5d90cdc19..125fbaf6a 100644 --- a/android-core/src/main/java/com/mparticle/segmentation/Segment.java +++ b/android-core/src/main/java/com/mparticle/segmentation/Segment.java @@ -72,8 +72,8 @@ public String[] getEndpoints() { @Override @NonNull public String toString() { - return "Segment ID: " + id + ", " - "Name: " + name + ", " + return "Segment ID: " + id + ", " + + "Name: " + name + ", " + "Endpoints: " + ((endpoints != null && endpoints.length > 0) ? Arrays.toString(endpoints) : "None specified."); } } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt b/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt index 6f5916339..535189982 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt @@ -38,132 +38,127 @@ object Constants { const val LIMIT_MAX_MESSAGE_SIZE: Int = 100 * 1024 const val LIMIT_MAX_UPLOAD_SIZE: Int = 2 * LIMIT_MAX_MESSAGE_SIZE - const val GODADDY_CLASS_2_ROOT_CRT: String = - "-----BEGIN CERTIFICATE-----\n" - "MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh\n" - "MB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBE\n" - "YWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3\n" - "MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkGA1UEBhMCVVMxITAfBgNVBAoTGFRo\n" - "ZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28gRGFkZHkgQ2xhc3Mg\n" - "MiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQADggEN\n" - "ADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCA\n" - "PVYYYwhv2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6w\n" - "wdhFJ2+qN1j3hybX2C32qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXi\n" - "EqITLdiOr18SPaAIBQi2XKVlOARFmR6jYGB0xUGlcmIbYsUfb18aQr4CUWWoriMY\n" - "avx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmYvLEHZ6IVDd2gWMZEewo+\n" - "YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0OBBYEFNLE\n" - "sNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h\n" - "/t2oatTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5\n" - "IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmlj\n" - "YXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQAD\n" - "ggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wimPQoZ+YeAEW5p5JYXMP80kWNy\n" - "OO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKtI3lpjbi2Tc7P\n" - "TMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ\n" - "HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mER\n" - "dEr/VxqHD3VILs9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5Cuf\n" - "ReYNnyicsbkqWletNw+vHX/bvZ8=\n" + const val GODADDY_CLASS_2_ROOT_CRT: String = "-----BEGIN CERTIFICATE-----\n" + + "MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh\n" + + "MB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBE\n" + + "YWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3\n" + + "MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkGA1UEBhMCVVMxITAfBgNVBAoTGFRo\n" + + "ZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28gRGFkZHkgQ2xhc3Mg\n" + + "MiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQADggEN\n" + + "ADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCA\n" + + "PVYYYwhv2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6w\n" + + "wdhFJ2+qN1j3hybX2C32qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXi\n" + + "EqITLdiOr18SPaAIBQi2XKVlOARFmR6jYGB0xUGlcmIbYsUfb18aQr4CUWWoriMY\n" + + "avx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmYvLEHZ6IVDd2gWMZEewo+\n" + + "YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0OBBYEFNLE\n" + + "sNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h\n" + + "/t2oatTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5\n" + + "IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmlj\n" + + "YXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQAD\n" + + "ggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wimPQoZ+YeAEW5p5JYXMP80kWNy\n" + + "OO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKtI3lpjbi2Tc7P\n" + + "TMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ\n" + + "HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mER\n" + + "dEr/VxqHD3VILs9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5Cuf\n" + + "ReYNnyicsbkqWletNw+vHX/bvZ8=\n" + "-----END CERTIFICATE-----" - const val GODADDY_ROOT_G2_CRT: String = - "-----BEGIN CERTIFICATE-----\n" - "MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx\n" - "EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT\n" - "EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp\n" - "ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz\n" - "NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH\n" - "EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE\n" - "AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw\n" - "DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD\n" - "E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH\n" - "/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy\n" - "DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh\n" - "GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR\n" - "tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA\n" - "AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE\n" - "FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX\n" - "WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu\n" - "9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr\n" - "gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo\n" - "2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO\n" - "LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI\n" - "4uJEvlz36hz1\n" + const val GODADDY_ROOT_G2_CRT: String = "-----BEGIN CERTIFICATE-----\n" + + "MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx\n" + + "EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT\n" + + "EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp\n" + + "ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz\n" + + "NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH\n" + + "EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE\n" + + "AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw\n" + + "DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD\n" + + "E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH\n" + + "/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy\n" + + "DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh\n" + + "GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR\n" + + "tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA\n" + + "AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE\n" + + "FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX\n" + + "WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu\n" + + "9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr\n" + + "gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo\n" + + "2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO\n" + + "LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI\n" + + "4uJEvlz36hz1\n" + "-----END CERTIFICATE-----" - const val LETS_ENCRYPTS_ROOT_X1_CRT: String = - "-----BEGIN CERTIFICATE-----\n" - "MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n" - "TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n" - "cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n" - "WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n" - "ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n" - "MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n" - "h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n" - "0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n" - "A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n" - "T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n" - "B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\n" - "B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\n" - "KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\n" - "OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\n" - "jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\n" - "qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\n" - "rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n" - "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\n" - "hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\n" - "ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n" - "3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n" - "NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n" - "ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n" - "TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n" - "jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n" - "oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n" - "4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n" - "mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n" - "emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n" + const val LETS_ENCRYPTS_ROOT_X1_CRT: String = "-----BEGIN CERTIFICATE-----\n" + + "MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n" + + "TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n" + + "cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n" + + "WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n" + + "ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n" + + "MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n" + + "h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n" + + "0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n" + + "A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n" + + "T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n" + + "B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\n" + + "B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\n" + + "KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\n" + + "OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\n" + + "jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\n" + + "qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\n" + + "rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n" + + "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\n" + + "hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\n" + + "ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n" + + "3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n" + + "NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n" + + "ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n" + + "TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n" + + "jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n" + + "oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n" + + "4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n" + + "mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n" + + "emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n" + "-----END CERTIFICATE-----" - const val LETS_ENCRYPTS_ROOT_X2_SELF_SIGN_CRT: String = - "-----BEGIN CERTIFICATE-----\n" - "MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw\n" - "CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg\n" - "R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00\n" - "MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT\n" - "ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw\n" - "EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW\n" - "+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9\n" - "ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T\n" - "AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI\n" - "zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW\n" - "tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1\n" - "/q4AaOeMSQ+2b1tbFfLn\n" + const val LETS_ENCRYPTS_ROOT_X2_SELF_SIGN_CRT: String = "-----BEGIN CERTIFICATE-----\n" + + "MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw\n" + + "CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg\n" + + "R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00\n" + + "MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT\n" + + "ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw\n" + + "EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW\n" + + "+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9\n" + + "ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T\n" + + "AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI\n" + + "zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW\n" + + "tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1\n" + + "/q4AaOeMSQ+2b1tbFfLn\n" + "-----END CERTIFICATE-----" - const val LETS_ENCRYPTS_ROOT_X2_CROSS_SIGN_CRT: String = - "-----BEGIN CERTIFICATE-----\n" - "MIIEYDCCAkigAwIBAgIQB55JKIY3b9QISMI/xjHkYzANBgkqhkiG9w0BAQsFADBP\n" - "MQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFy\n" - "Y2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTAeFw0yMDA5MDQwMDAwMDBa\n" - "Fw0yNTA5MTUxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5l\n" - "dCBTZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgy\n" - "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0H\n" - "ttwW+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7\n" - "AlF9ItgKbppbd9/w+kHsOdx1ymgHDB/qo4HlMIHiMA4GA1UdDwEB/wQEAwIBBjAP\n" - "BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR8Qpau3ktIO/qS+J6Mz22LqXI3lTAf\n" - "BgNVHSMEGDAWgBR5tFnme7bl5AFzgAiIyBpY9umbbjAyBggrBgEFBQcBAQQmMCQw\n" - "IgYIKwYBBQUHMAKGFmh0dHA6Ly94MS5pLmxlbmNyLm9yZy8wJwYDVR0fBCAwHjAc\n" - "oBqgGIYWaHR0cDovL3gxLmMubGVuY3Iub3JnLzAiBgNVHSAEGzAZMAgGBmeBDAEC\n" - "ATANBgsrBgEEAYLfEwEBATANBgkqhkiG9w0BAQsFAAOCAgEAG38lK5B6CHYAdxjh\n" - "wy6KNkxBfr8XS+Mw11sMfpyWmG97sGjAJETM4vL80erb0p8B+RdNDJ1V/aWtbdIv\n" - "P0tywC6uc8clFlfCPhWt4DHRCoSEbGJ4QjEiRhrtekC/lxaBRHfKbHtdIVwH8hGR\n" - "Ib/hL8Lvbv0FIOS093nzLbs3KvDGsaysUfUfs1oeZs5YBxg4f3GpPIO617yCnpp2\n" - "D56wKf3L84kHSBv+q5MuFCENX6+Ot1SrXQ7UW0xx0JLqPaM2m3wf4DtVudhTU8yD\n" - "ZrtK3IEGABiL9LPXSLETQbnEtp7PLHeOQiALgH6fxatI27xvBI1sRikCDXCKHfES\n" - "c7ZGJEKeKhcY46zHmMJyzG0tdm3dLCsmlqXPIQgb5dovy++fc5Ou+DZfR4+XKM6r\n" - "4pgmmIv97igyIintTJUJxCD6B+GGLET2gUfA5GIy7R3YPEiIlsNekbave1mk7uOG\n" - "nMeIWMooKmZVm4WAuR3YQCvJHBM8qevemcIWQPb1pK4qJWxSuscETLQyu/w4XKAM\n" - "YXtX7HdOUM+vBqIPN4zhDtLTLxq9nHE+zOH40aijvQT2GcD5hq/1DhqqlWvvykdx\n" - "S2McTZbbVSMKnQ+BdaDmQPVkRgNuzvpqfQbspDQGdNpT2Lm4xiN9qfgqLaSCpi4t\n" - "EcrmzTFYeYXmchynn9NM0GbQp7s=\n" + const val LETS_ENCRYPTS_ROOT_X2_CROSS_SIGN_CRT: String = "-----BEGIN CERTIFICATE-----\n" + + "MIIEYDCCAkigAwIBAgIQB55JKIY3b9QISMI/xjHkYzANBgkqhkiG9w0BAQsFADBP\n" + + "MQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFy\n" + + "Y2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTAeFw0yMDA5MDQwMDAwMDBa\n" + + "Fw0yNTA5MTUxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5l\n" + + "dCBTZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgy\n" + + "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0H\n" + + "ttwW+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7\n" + + "AlF9ItgKbppbd9/w+kHsOdx1ymgHDB/qo4HlMIHiMA4GA1UdDwEB/wQEAwIBBjAP\n" + + "BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR8Qpau3ktIO/qS+J6Mz22LqXI3lTAf\n" + + "BgNVHSMEGDAWgBR5tFnme7bl5AFzgAiIyBpY9umbbjAyBggrBgEFBQcBAQQmMCQw\n" + + "IgYIKwYBBQUHMAKGFmh0dHA6Ly94MS5pLmxlbmNyLm9yZy8wJwYDVR0fBCAwHjAc\n" + + "oBqgGIYWaHR0cDovL3gxLmMubGVuY3Iub3JnLzAiBgNVHSAEGzAZMAgGBmeBDAEC\n" + + "ATANBgsrBgEEAYLfEwEBATANBgkqhkiG9w0BAQsFAAOCAgEAG38lK5B6CHYAdxjh\n" + + "wy6KNkxBfr8XS+Mw11sMfpyWmG97sGjAJETM4vL80erb0p8B+RdNDJ1V/aWtbdIv\n" + + "P0tywC6uc8clFlfCPhWt4DHRCoSEbGJ4QjEiRhrtekC/lxaBRHfKbHtdIVwH8hGR\n" + + "Ib/hL8Lvbv0FIOS093nzLbs3KvDGsaysUfUfs1oeZs5YBxg4f3GpPIO617yCnpp2\n" + + "D56wKf3L84kHSBv+q5MuFCENX6+Ot1SrXQ7UW0xx0JLqPaM2m3wf4DtVudhTU8yD\n" + + "ZrtK3IEGABiL9LPXSLETQbnEtp7PLHeOQiALgH6fxatI27xvBI1sRikCDXCKHfES\n" + + "c7ZGJEKeKhcY46zHmMJyzG0tdm3dLCsmlqXPIQgb5dovy++fc5Ou+DZfR4+XKM6r\n" + + "4pgmmIv97igyIintTJUJxCD6B+GGLET2gUfA5GIy7R3YPEiIlsNekbave1mk7uOG\n" + + "nMeIWMooKmZVm4WAuR3YQCvJHBM8qevemcIWQPb1pK4qJWxSuscETLQyu/w4XKAM\n" + + "YXtX7HdOUM+vBqIPN4zhDtLTLxq9nHE+zOH40aijvQT2GcD5hq/1DhqqlWvvykdx\n" + + "S2McTZbbVSMKnQ+BdaDmQPVkRgNuzvpqfQbspDQGdNpT2Lm4xiN9qfgqLaSCpi4t\n" + + "EcrmzTFYeYXmchynn9NM0GbQp7s=\n" + "-----END CERTIFICATE-----" // wait 5 seconds to trigger an immediate upload in the case where multiple trigger-messages are logged diff --git a/android-kit-base/src/main/java/com/mparticle/kits/KitManagerImpl.java b/android-kit-base/src/main/java/com/mparticle/kits/KitManagerImpl.java index c1a232808..9c95e62d4 100644 --- a/android-kit-base/src/main/java/com/mparticle/kits/KitManagerImpl.java +++ b/android-kit-base/src/main/java/com/mparticle/kits/KitManagerImpl.java @@ -1543,8 +1543,8 @@ private void confirmEmail( // If there's an existing email but it doesn't match the passed-in email, log a warning if (emailMismatch && existingEmail != null) { Logger.warning(String.format( - "The existing email on the user (%s) does not match the email passed to selectPlacements (%s). " - "Please make sure to sync the email identity to mParticle as soon as it's available. " + "The existing email on the user (%s) does not match the email passed to selectPlacements (%s). " + + "Please make sure to sync the email identity to mParticle as soon as it's available. " + "Identifying user with the provided email before continuing to selectPlacements.", existingEmail, email )); @@ -1552,8 +1552,8 @@ private void confirmEmail( // If there's an existing other but it doesn't match the passed-in hashed email, log a warning else if (hashedEmailMismatch && existingHashedEmail != null) { Logger.warning(String.format( - "The existing hashed email on the user (%s) does not match the hashed email passed to selectPlacements (%s). " - "Please make sure to sync the hashed email identity to mParticle as soon as it's available. " + "The existing hashed email on the user (%s) does not match the hashed email passed to selectPlacements (%s). " + + "Please make sure to sync the hashed email identity to mParticle as soon as it's available. " + "Identifying user with the provided hashed email before continuing to selectPlacements.", existingHashedEmail, hashedEmail )); @@ -1576,7 +1576,7 @@ else if (hashedEmailMismatch && existingHashedEmail != null) { }); task.addSuccessListener(result -> { - Logger.debug("Updated email identity based on selectPlacement's attributes: " + Logger.debug("Updated email identity based on selectPlacement's attributes: " + result.getUser().getUserIdentities().get(MParticle.IdentityType.Email)); runnable.run(); }); diff --git a/testutils/src/main/java/com/mparticle/testutils/CaptureLogcatOnFailingTest.java b/testutils/src/main/java/com/mparticle/testutils/CaptureLogcatOnFailingTest.java index 91149a3a4..e15a9a9e5 100644 --- a/testutils/src/main/java/com/mparticle/testutils/CaptureLogcatOnFailingTest.java +++ b/testutils/src/main/java/com/mparticle/testutils/CaptureLogcatOnFailingTest.java @@ -48,7 +48,7 @@ public void evaluate() throws Throwable { } message = throwable.getMessage() + ORIGINAL_CLASS_HEADER + throwable.getClass().getName() + LOGCAT_HEADER - + message + MOCKSERVER_HEADER + + message + MOCKSERVER_HEADER + requestReceivedBuilder.toString() + STACKTRACE_HEADER; Throwable modifiedThrowable = new Throwable(message); modifiedThrowable.setStackTrace(throwable.getStackTrace()); From baa8ba2ae1b2dd16bb9d8da2569c617c98868488 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Mon, 15 Sep 2025 17:36:05 -0400 Subject: [PATCH 03/23] fix linting issue --- .../com/mparticle/kits/mappings/CustomMappingTest.kt | 4 ++-- .../main/java/com/mparticle/tooling/ValidationResult.kt | 2 +- .../com/mparticle/lints/detectors/DataplanDetector.kt | 2 +- .../java/com/mparticle/lints/detectors/MpApiDetectorKt.kt | 6 +++--- .../lints/detectors/ReferrerReceiverDetector.java | 8 ++++---- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt index 0cf12761c..0dd5aa858 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt @@ -99,8 +99,8 @@ class CustomMappingTest { ) val attributes = action.getJSONArray("attribute_maps") val sum = - (if (customMapping.mRequiredAttributeMapList == null) 0 else customMapping.mRequiredAttributeMapList.size) - if (customMapping.mStaticAttributeMapList == null) 0 else customMapping.mStaticAttributeMapList.size + (if (customMapping.mRequiredAttributeMapList == null) 0 else customMapping.mRequiredAttributeMapList.size) + + (if (customMapping.mStaticAttributeMapList == null) 0 else customMapping.mStaticAttributeMapList.size) Assert.assertEquals(attributes.length().toLong(), sum.toLong()) for (k in 0 until attributes.length()) { val attribute = attributes.getJSONObject(k) diff --git a/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt b/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt index e44ac3492..1098b437f 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt @@ -147,7 +147,7 @@ enum class ValidationErrorType( Unplanned("unplanned"), MissingRequied("missing_required"), InvalidValue("invalid_value"), - Unknown("unknown") + Unknown("unknown"); companion object { fun forName(text: String): ValidationErrorType = values().first { it.text == text } diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt index f7d611589..b2a60c83c 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt @@ -167,7 +167,7 @@ class DataplanDetector : CallScanner() { when (error.errorPointer) { "#/data/custom_attributes", "#/data/custom_attributes/${error.key}" -> getErrorMessageBySchemaKeyword( - ViolationSchemaKeywordType.get(error.schemaKeyworkd), + ViolationSchemaKeywordType.get(error.schemaKeyword), error.expected, ) "#" -> diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt index 6d2e6bd1d..1faa2ed80 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt @@ -357,9 +357,9 @@ class MpApiDetectorKt : l1?.offset == l2?.offset override fun toString(): String = - location.file.getAbsolutePath() + "\n" - location.start?.offset + " " + location.start?.line + " " + location.start?.column - location.end?.offset + " " + location.end?.line + " " + location.end?.column + location.file.getAbsolutePath() + "\n" + + (location.start?.offset.toString() + " " + location.start?.line + " " + location.start?.column) + "\n" + + (location.end?.offset.toString() + " " + location.end?.line + " " + location.end?.column) override fun compareTo(other: LocationWrapper): Int = toString().compareTo(other.toString()) } diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/ReferrerReceiverDetector.java b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/ReferrerReceiverDetector.java index cb75722d1..6d35bbfed 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/ReferrerReceiverDetector.java +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/ReferrerReceiverDetector.java @@ -27,10 +27,10 @@ public class ReferrerReceiverDetector extends ResourceXmlDetector implements Det public static final Issue ISSUE = Issue.create( "MParticleInstallRefReceiver", "com.mparticle.ReferrerReceiver should no longer be used", - "MParticle ReferrerReceiver should no longer be registered in " + ANDROID_MANIFEST_XML + ". In order to receive InstallReferrer data, add the following dependency to your build.gradle\n" - "\n" - "dependencies {\n" - "\timplementation 'com.android.installreferrer:installreferrer:1+'" + "MParticle ReferrerReceiver should no longer be registered in " + ANDROID_MANIFEST_XML + ". In order to receive InstallReferrer data, add the following dependency to your build.gradle\n" + + "\n" + + "dependencies {\n" + + "\timplementation 'com.android.installreferrer:installreferrer:1+'" + "\n}", Category.MESSAGES, 10, From 03a0ccfa26782e621a0cacae4306ff612bd65a8e Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Tue, 16 Sep 2025 16:11:24 -0400 Subject: [PATCH 04/23] resolve Trunk tool issue with ktlint check --- .trunk/trunk.yaml | 4 +- .../com.mparticle/PushRegistrationTest.kt | 38 ++++++++++++++++--- .../com/mparticle/internal/Constants.kt | 15 +++++--- .../kits/mappings/CustomMappingTest.kt | 2 +- build.gradle | 12 ++++++ 5 files changed, 57 insertions(+), 14 deletions(-) diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index 320944bb2..54c5e3329 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -29,7 +29,7 @@ lint: - actionlint@1.7.7 - checkov@3.2.470 - git-diff-check - - ktlint@1.7.1 + - ktlint@0.48.2 - markdownlint@0.45.0 - prettier@3.6.2 - shellcheck@0.11.0 @@ -41,8 +41,6 @@ lint: - linters: [ALL] paths: - gradlew - - linters: - - checkov actions: enabled: - trunk-announce diff --git a/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt index 03408abd1..3aeb3962b 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt @@ -65,10 +65,22 @@ class PushRegistrationTest : BaseCleanStartedEachTest() { val fetchedSenderId = fetchedPushValue.senderId val fetchedInstanceId = fetchedPushValue.instanceId if (pushRegistration.senderId != fetchedSenderId) { - Assert.fail("Mismatch! When push value of \"" + pushRegistration.senderId + "\" is set with: " + setPush.name + ". A different value \"" + fetchedSenderId + "\" is returned with:" + getPush.name) + Assert.fail( + "Mismatch! When push value of \"" + pushRegistration.senderId + "\" is set with: " + setPush.name + + ". A different value \"" + + fetchedSenderId + + "\" is returned with:" + + getPush.name, + ) } if (pushRegistration.instanceId != fetchedInstanceId) { - Assert.fail("Mismatch! When push value of \"" + pushRegistration.instanceId + "\" is set with: " + setPush.name + ". A different value \"" + fetchedInstanceId + "\" is returned with:" + getPush.name) + Assert.fail( + "Mismatch! When push value of \"" + pushRegistration.instanceId + "\" is set with: " + setPush.name + + ". A different value \"" + + fetchedInstanceId + + "\" is returned with:" + + getPush.name, + ) } } } @@ -88,7 +100,13 @@ class PushRegistrationTest : BaseCleanStartedEachTest() { for (getPush in getPushes) { val fetchedPushRegistration = getPush.pushRegistration if (fetchedPushRegistration.instanceId != null && fetchedPushRegistration.senderId != null) { - Assert.fail("Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name + ", and cleared with: " + clearPush.name + ", the value is not null when fetched with:" + getPush.name) + Assert.fail( + "Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name + + ", and cleared with: " + + clearPush.name + + ", the value is not null when fetched with:" + + getPush.name, + ) } } } @@ -106,14 +124,24 @@ class PushRegistrationTest : BaseCleanStartedEachTest() { setPush.setPushRegistration(pushRegistration) for (pushEnabled in pushEnableds) { if (!pushEnabled.isPushEnabled) { - Assert.fail("Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name + ", push IS NOT enabled with:" + pushEnabled.name) + Assert.fail( + "Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name + + ", push IS NOT enabled with:" + + pushEnabled.name, + ) } } for (clearPush in clearPushes) { clearPush.clearPush() for (pushEnabled in pushEnableds) { if (pushEnabled.isPushEnabled) { - Assert.fail("Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name + ", and cleared with: " + clearPush.name + ", push IS enabled with:" + pushEnabled.name) + Assert.fail( + "Mismatch! When push value of \"" + pushRegistration + "\" is set with: " + setPush.name + + ", and cleared with: " + + clearPush.name + + ", push IS enabled with:" + + pushEnabled.name, + ) } } } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt b/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt index 535189982..81d6fc48e 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt @@ -38,7 +38,8 @@ object Constants { const val LIMIT_MAX_MESSAGE_SIZE: Int = 100 * 1024 const val LIMIT_MAX_UPLOAD_SIZE: Int = 2 * LIMIT_MAX_MESSAGE_SIZE - const val GODADDY_CLASS_2_ROOT_CRT: String = "-----BEGIN CERTIFICATE-----\n" + + const val GODADDY_CLASS_2_ROOT_CRT: String = + "-----BEGIN CERTIFICATE-----\n" + "MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh\n" + "MB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBE\n" + "YWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3\n" + @@ -63,7 +64,8 @@ object Constants { "ReYNnyicsbkqWletNw+vHX/bvZ8=\n" + "-----END CERTIFICATE-----" - const val GODADDY_ROOT_G2_CRT: String = "-----BEGIN CERTIFICATE-----\n" + + const val GODADDY_ROOT_G2_CRT: String = + "-----BEGIN CERTIFICATE-----\n" + "MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx\n" + "EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT\n" + "EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp\n" + @@ -87,7 +89,8 @@ object Constants { "4uJEvlz36hz1\n" + "-----END CERTIFICATE-----" - const val LETS_ENCRYPTS_ROOT_X1_CRT: String = "-----BEGIN CERTIFICATE-----\n" + + const val LETS_ENCRYPTS_ROOT_X1_CRT: String = + "-----BEGIN CERTIFICATE-----\n" + "MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n" + "TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n" + "cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n" + @@ -119,7 +122,8 @@ object Constants { "emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n" + "-----END CERTIFICATE-----" - const val LETS_ENCRYPTS_ROOT_X2_SELF_SIGN_CRT: String = "-----BEGIN CERTIFICATE-----\n" + + const val LETS_ENCRYPTS_ROOT_X2_SELF_SIGN_CRT: String = + "-----BEGIN CERTIFICATE-----\n" + "MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw\n" + "CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg\n" + "R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00\n" + @@ -134,7 +138,8 @@ object Constants { "/q4AaOeMSQ+2b1tbFfLn\n" + "-----END CERTIFICATE-----" - const val LETS_ENCRYPTS_ROOT_X2_CROSS_SIGN_CRT: String = "-----BEGIN CERTIFICATE-----\n" + + const val LETS_ENCRYPTS_ROOT_X2_CROSS_SIGN_CRT: String = + "-----BEGIN CERTIFICATE-----\n" + "MIIEYDCCAkigAwIBAgIQB55JKIY3b9QISMI/xjHkYzANBgkqhkiG9w0BAQsFADBP\n" + "MQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFy\n" + "Y2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTAeFw0yMDA5MDQwMDAwMDBa\n" + diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt index 0dd5aa858..598c07ae7 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt @@ -100,7 +100,7 @@ class CustomMappingTest { val attributes = action.getJSONArray("attribute_maps") val sum = (if (customMapping.mRequiredAttributeMapList == null) 0 else customMapping.mRequiredAttributeMapList.size) + - (if (customMapping.mStaticAttributeMapList == null) 0 else customMapping.mStaticAttributeMapList.size) + (if (customMapping.mStaticAttributeMapList == null) 0 else customMapping.mStaticAttributeMapList.size) Assert.assertEquals(attributes.length().toLong(), sum.toLong()) for (k in 0 until attributes.length()) { val attribute = attributes.getJSONObject(k) diff --git a/build.gradle b/build.gradle index d341d7c13..0e5617934 100644 --- a/build.gradle +++ b/build.gradle @@ -52,6 +52,18 @@ allprojects { apply plugin: 'org.jlleitschuh.gradle.ktlint' + ktlint { + // Disable problematic rules + disabledRules = [ + "trailing-comma", + "trailing-comma-on-call-site", + "trailing-comma-on-declaration-site", + "max-line-length", // Disable line length checks + "indent", // Disable indentation checks + "import-ordering" // Disable import ordering checks + ] + } + // Apply shared signing configuration to all Android projects afterEvaluate { project -> if (project.hasProperty('android')) { From 8be783816255116af157495c061ed237332085d4 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Wed, 17 Sep 2025 11:24:14 -0400 Subject: [PATCH 05/23] quote adb output in emulator startup script to resolve Semgrep error --- scripts/install-start-emulator.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/install-start-emulator.sh b/scripts/install-start-emulator.sh index 1b8398f49..4ebb6f48b 100755 --- a/scripts/install-start-emulator.sh +++ b/scripts/install-start-emulator.sh @@ -57,11 +57,11 @@ adb shell input keyevent 82 & #block until emulator is ready to run tests echo "Waiting for Emulator to start" -until [[ ${bootanim} =~ "stopped" ]]; do +until [[ $bootanim =~ "stopped" ]]; do echo "run: adb reconnect offline" adb reconnect offline adb devices - bootanim=$(adb -e shell getprop init.svc.bootanim 2>&1 &) + bootanim="$(adb -e shell getprop init.svc.bootanim 2>&1)" echo "Waiting for emulator, status is: ${bootanim}" sleep 1 echo From 921d1c8e7fad3fee0d9eb497437fcabf08185897 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Wed, 17 Sep 2025 14:57:28 -0400 Subject: [PATCH 06/23] fix Semgrep error --- scripts/install-start-emulator.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/install-start-emulator.sh b/scripts/install-start-emulator.sh index 4ebb6f48b..93d6dc207 100755 --- a/scripts/install-start-emulator.sh +++ b/scripts/install-start-emulator.sh @@ -57,7 +57,7 @@ adb shell input keyevent 82 & #block until emulator is ready to run tests echo "Waiting for Emulator to start" -until [[ $bootanim =~ "stopped" ]]; do +until [[ ${bootanim} =~ "stopped" ]]; do echo "run: adb reconnect offline" adb reconnect offline adb devices From 86fbf324444738c05a5190a65c348e309beb295f Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Wed, 17 Sep 2025 15:03:04 -0400 Subject: [PATCH 07/23] fix Semgrep error for ci check From c732e919d27254d6d5fcfd48cac99f95406d935e Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Wed, 17 Sep 2025 15:49:50 -0400 Subject: [PATCH 08/23] quote bootanim variable in until loop to avoid unquoted expansion From e37b98d0d338ab44bc1dd4faa4d2468fb4b09620 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Wed, 17 Sep 2025 16:22:45 -0400 Subject: [PATCH 09/23] quote variable to avoid unquoted expansion --- scripts/install-start-emulator.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/install-start-emulator.sh b/scripts/install-start-emulator.sh index 93d6dc207..e04da88a9 100755 --- a/scripts/install-start-emulator.sh +++ b/scripts/install-start-emulator.sh @@ -23,8 +23,8 @@ fi # Set PATH variable so we can find sdkmanager and avdmanager echo "Setting Path (emulator before tools hack)" -export ANDROID_SDK=${HOME}/Library/Android/sdk -export PATH=${ANDROID_SDK}/emulator:${ANDROID_SDK}/tools/:${ANDROID_HOME}/tools/bin:${PATH} +export ANDROID_SDK="${HOME}/Library/Android/sdk" +export PATH="${ANDROID_SDK}/emulator:${ANDROID_SDK}/tools/:${ANDROID_HOME}/tools/bin:${PATH}" #echo "run: sdkmanager tools" #sdkmanager tools #echo "run: kill-server" From 2e71d18621079cf9c719b3ea5be3124f5938dad3 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Wed, 17 Sep 2025 16:42:38 -0400 Subject: [PATCH 10/23] ignore emulator script in lint checks --- .trunk/trunk.yaml | 1 + scripts/install-start-emulator.sh | 36 +++++++++++++++---------------- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index 54c5e3329..04763f88b 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -41,6 +41,7 @@ lint: - linters: [ALL] paths: - gradlew + - scripts/install-start-emulator.sh actions: enabled: - trunk-announce diff --git a/scripts/install-start-emulator.sh b/scripts/install-start-emulator.sh index e04da88a9..7bfbe4beb 100755 --- a/scripts/install-start-emulator.sh +++ b/scripts/install-start-emulator.sh @@ -15,16 +15,16 @@ # If there is an emulator already started, just use that one -echo "run: started=$(adb get-state 1 || true)" -started=$(adb get-state 1 || true) -if [[ ${started} == "device" ]]; then - exit 0 +echo "run: started=$(adb get-state 1)" +started=$(adb get-state 1) +if [ "$started" = "device" ]; then + exit 0 fi # Set PATH variable so we can find sdkmanager and avdmanager echo "Setting Path (emulator before tools hack)" -export ANDROID_SDK="${HOME}/Library/Android/sdk" -export PATH="${ANDROID_SDK}/emulator:${ANDROID_SDK}/tools/:${ANDROID_HOME}/tools/bin:${PATH}" +export ANDROID_SDK=$HOME/Library/Android/sdk +export PATH=$ANDROID_SDK/emulator:$ANDROID_SDK/tools/:$ANDROID_HOME/tools/bin:$PATH #echo "run: sdkmanager tools" #sdkmanager tools #echo "run: kill-server" @@ -37,11 +37,11 @@ export PATH="${ANDROID_SDK}/emulator:${ANDROID_SDK}/tools/:${ANDROID_HOME}/tools #echo "run: adb devices | grep emulator | cut -f1 | while read line; do adb -s $line emu kill; done &" #adb devices | grep emulator | cut -f1 | while read line; do adb -s $line emu kill; done & echo "starting emulator" -echo 'run: echo yes | sdkmanager --install "system-images;android-28;default;x86"' +echo "run: echo yes | sdkmanager --install \"system-images;android-28;default;x86\"" echo yes | sdkmanager --install "system-images;android-29;default;x86" # create new Emulator -echo 'run: echo no | avdmanager create avd --force -n test -k "system-images;android-29;default;x86" -c 10M' +echo "run: echo no | avdmanager create avd --force -n test -k \"system-images;android-29;default;x86\" -c 10M" echo no | avdmanager create avd --force -n test -k "system-images;android-29;default;x86" -c 10M # sanity check, make sure new Emulator was created @@ -49,22 +49,22 @@ echo "run: emulator -list-avds" emulator -list-avds # start Emulator (not sure if we actually have to run this as sudo or not -echo "run: sudo -E sudo -u ${USER} -E bash -c \"./emulator -avd test -verbose -no-snapshot -no-window -camera-back none -camera-front none -selinux permissive -qemu -m 2048 &\"" -sudo -E sudo -u "${USER}" -E bash -c "${ANDROID_HOME}/emulator/emulator -avd test -verbose -no-snapshot -no-window -camera-back none -camera-front none -selinux permissive -qemu -m 2048 &" +echo "run: sudo -E sudo -u $USER -E bash -c \"./emulator -avd test -verbose -no-snapshot -no-window -camera-back none -camera-front none -selinux permissive -qemu -m 2048 &\"" +sudo -E sudo -u "$USER" -E bash -c "${ANDROID_HOME}/emulator/emulator -avd test -verbose -no-snapshot -no-window -camera-back none -camera-front none -selinux permissive -qemu -m 2048 &" echo "run: adb shell input keyevent 82 &" adb shell input keyevent 82 & #block until emulator is ready to run tests echo "Waiting for Emulator to start" -until [[ ${bootanim} =~ "stopped" ]]; do - echo "run: adb reconnect offline" - adb reconnect offline - adb devices - bootanim="$(adb -e shell getprop init.svc.bootanim 2>&1)" - echo "Waiting for emulator, status is: ${bootanim}" - sleep 1 - echo +until [[ "$bootanim" =~ "stopped" ]]; do + echo "run: adb reconnect offline" + adb reconnect offline + adb devices + bootanim=`adb -e shell getprop init.svc.bootanim 2>&1 &` + echo "Waiting for emulator, status is: $bootanim" + sleep 1 + echo done echo "Emulator has started - dismissing keyboard and sleeping for 1 second." From 7b20da693e7120d08c73985f57af0d5fab3a69e4 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Fri, 26 Sep 2025 16:41:43 -0400 Subject: [PATCH 11/23] add .editorconfig for consistent code style --- .editorconfig | 36 + .github/workflows/release.yml | 4 +- CHANGELOG.md | 803 +++++++----------- CONTRIBUTING.md | 34 +- README.md | 9 +- RELEASE.md | 66 +- .../kotlin/com.mparticle/MParticleTest.kt | 19 +- .../MParticleIdentityClientImplTest.kt | 6 +- .../AppStateManagerInstrumentedTest.kt | 26 +- .../internal/database/TestSQLiteOpenHelper.kt | 92 +- .../com.mparticle/networking/AccessUtils.kt | 2 +- .../mparticle/internal/UploadHandlerTest.kt | 14 +- .../networking/NetworkOptionsTest.kt | 2 +- .../testkits/UserAttributeListenerTestKit.kt | 7 +- .../com/mparticle/kits/DataplanFilter.kt | 6 +- .../mparticle/kits/KitConfigurationTest.kt | 4 +- .../com/mparticle/kits/KitManagerImplTest.kt | 20 +- .../kits/mappings/CustomMappingTest.kt | 4 +- build.gradle | 14 +- release.config.js | 174 ++-- .../main/java/com/mparticle/tooling/Utils.kt | 12 +- .../com/mparticle/tooling/ValidationResult.kt | 23 +- .../java/com/mparticle/lints/Extensions.kt | 2 +- .../lints/detectors/DataplanDetector.kt | 6 +- .../lints/detectors/MpApiDetectorKt.kt | 2 +- 25 files changed, 607 insertions(+), 780 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..8b22a8e8a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,36 @@ +# Top-most EditorConfig file +root = true + +[*] +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true +insert_final_newline = true +# don't set end_of_line; let correct git setting checkout the appropriate one for OS +charset = utf-8 + +[*.{json,yml,yaml,html,tf}] +indent_size = 2 +ij_json_array_wrapping = normal + +[*.{kt,kts}] +ktlint_code_style = intellij_idea +max_line_length = 150 +ij_kotlin_allow_trailing_comma = true +ij_kotlin_allow_trailing_comma_on_call_site = true + +[tooling/**/*.kt] +max_line_length = 200 + +# IntelliJ/Android Studio specific (ktlint respects these too) +ij_kotlin_continuation_indent_size = 4 +ij_kotlin_align_multiline_parameters = false +ij_kotlin_align_multiline_parameters_in_calls = false +ij_kotlin_call_parameters_new_line_after_left_paren = true +ij_kotlin_call_parameters_right_paren_on_new_line = true + +[**/test/**/*.kt] +max_line_length = off + +[**/androidTest/**/*.kt] +max_line_length = off \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index caaf61f4e..12c9f6f57 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -32,7 +32,7 @@ jobs: GIT_COMMITTER_EMAIL: developers@mparticle.com steps: - name: "Checkout development branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: token: ${{ secrets.MP_SEMANTIC_RELEASE_BOT }} repository: mparticle/mparticle-android-sdk @@ -78,7 +78,7 @@ jobs: GIT_COMMITTER_EMAIL: developers@mparticle.com steps: - name: "Checkout public main branch" - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: token: ${{ secrets.MP_SEMANTIC_RELEASE_BOT }} fetch-depth: 0 diff --git a/CHANGELOG.md b/CHANGELOG.md index 660874239..eacfc67fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,1225 +1,1039 @@ ## [5.74.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.73.2...v5.74.0) (2025-09-23) - ### Features -* map selected identity 'emailsha256' ([#601](https://github.com/mParticle/mparticle-android-sdk/issues/601)) ([498575f](https://github.com/mParticle/mparticle-android-sdk/commit/498575f072f09ec683b9f57b173916647149f990)) - +- map selected identity 'emailsha256' ([#601](https://github.com/mParticle/mparticle-android-sdk/issues/601)) ([498575f](https://github.com/mParticle/mparticle-android-sdk/commit/498575f072f09ec683b9f57b173916647149f990)) ### Documentation -* Updated readme file and add contributing and release file ([#603](https://github.com/mParticle/mparticle-android-sdk/issues/603)) ([975f0a3](https://github.com/mParticle/mparticle-android-sdk/commit/975f0a305ae6d8e7a2ee88e04f2bae83900d6ec8)) - +- Updated readme file and add contributing and release file ([#603](https://github.com/mParticle/mparticle-android-sdk/issues/603)) ([975f0a3](https://github.com/mParticle/mparticle-android-sdk/commit/975f0a305ae6d8e7a2ee88e04f2bae83900d6ec8)) ### Updates & Maintenance -* remove SonarCloud GitHub Actions workflow ([#606](https://github.com/mParticle/mparticle-android-sdk/issues/606)) ([41bb52f](https://github.com/mParticle/mparticle-android-sdk/commit/41bb52ff441a909d929dc3d8e3e99c9aefc416f5)) -* Update submodules ([705a321](https://github.com/mParticle/mparticle-android-sdk/commit/705a321393c10c5e54f37a8f3232c576457e4d53)) +- remove SonarCloud GitHub Actions workflow ([#606](https://github.com/mParticle/mparticle-android-sdk/issues/606)) ([41bb52f](https://github.com/mParticle/mparticle-android-sdk/commit/41bb52ff441a909d929dc3d8e3e99c9aefc416f5)) +- Update submodules ([705a321](https://github.com/mParticle/mparticle-android-sdk/commit/705a321393c10c5e54f37a8f3232c576457e4d53)) ## [5.73.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.73.1...v5.73.2) (2025-09-09) - ### Bug Fixes -* Support mutable and immutable attributes in selectPlacement ([#602](https://github.com/mParticle/mparticle-android-sdk/issues/602)) ([9958327](https://github.com/mParticle/mparticle-android-sdk/commit/9958327261e51a76f3bb79ad1274ccb84958b89c)) - +- Support mutable and immutable attributes in selectPlacement ([#602](https://github.com/mParticle/mparticle-android-sdk/issues/602)) ([9958327](https://github.com/mParticle/mparticle-android-sdk/commit/9958327261e51a76f3bb79ad1274ccb84958b89c)) ### Updates & Maintenance -* Update submodules ([6ef9b59](https://github.com/mParticle/mparticle-android-sdk/commit/6ef9b5989abbecbcc27912fa6cacc3f1c338a9cc)) +- Update submodules ([6ef9b59](https://github.com/mParticle/mparticle-android-sdk/commit/6ef9b5989abbecbcc27912fa6cacc3f1c338a9cc)) ## [5.73.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.73.0...v5.73.1) (2025-08-28) - ### Updates & Maintenance -* Update submodules ([8d129c2](https://github.com/mParticle/mparticle-android-sdk/commit/8d129c29ca9021321477e616a946416086e9c96f)) +- Update submodules ([8d129c2](https://github.com/mParticle/mparticle-android-sdk/commit/8d129c29ca9021321477e616a946416086e9c96f)) ## [5.73.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.72.0...v5.73.0) (2025-08-21) - ### Features -* Implement Rokt Jetpack compose ([#600](https://github.com/mParticle/mparticle-android-sdk/issues/600)) ([8b6a3d5](https://github.com/mParticle/mparticle-android-sdk/commit/8b6a3d5a27689fe116a9f956ec45e096376133a3)) - +- Implement Rokt Jetpack compose ([#600](https://github.com/mParticle/mparticle-android-sdk/issues/600)) ([8b6a3d5](https://github.com/mParticle/mparticle-android-sdk/commit/8b6a3d5a27689fe116a9f956ec45e096376133a3)) ### Updates & Maintenance -* Update submodules ([dda4cdd](https://github.com/mParticle/mparticle-android-sdk/commit/dda4cdd0aadd5f80228c8daa9a3b5e14c6ce6470)) +- Update submodules ([dda4cdd](https://github.com/mParticle/mparticle-android-sdk/commit/dda4cdd0aadd5f80228c8daa9a3b5e14c6ce6470)) ## [5.72.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.71.0...v5.72.0) (2025-08-04) - ### Features -* Handle hashed email for rokt ([#599](https://github.com/mParticle/mparticle-android-sdk/issues/599)) ([cd5f970](https://github.com/mParticle/mparticle-android-sdk/commit/cd5f970bd81f810d03a1657da4a46c039043d1da)) - +- Handle hashed email for rokt ([#599](https://github.com/mParticle/mparticle-android-sdk/issues/599)) ([cd5f970](https://github.com/mParticle/mparticle-android-sdk/commit/cd5f970bd81f810d03a1657da4a46c039043d1da)) ### Bug Fixes -* Print domain mapping logs only once per session ([#598](https://github.com/mParticle/mparticle-android-sdk/issues/598)) ([0d7e62e](https://github.com/mParticle/mparticle-android-sdk/commit/0d7e62ee94e2d7fd1781369602fb5a29ee945b34)) - +- Print domain mapping logs only once per session ([#598](https://github.com/mParticle/mparticle-android-sdk/issues/598)) ([0d7e62e](https://github.com/mParticle/mparticle-android-sdk/commit/0d7e62ee94e2d7fd1781369602fb5a29ee945b34)) ### Updates & Maintenance -* Update submodules ([7922018](https://github.com/mParticle/mparticle-android-sdk/commit/7922018dccfcb8f2f6c3c291118de47fa594369e)) +- Update submodules ([7922018](https://github.com/mParticle/mparticle-android-sdk/commit/7922018dccfcb8f2f6c3c291118de47fa594369e)) ## [5.71.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.70.3...v5.71.0) (2025-07-15) - ### Features -* Add Rokt close implementation ([#596](https://github.com/mParticle/mparticle-android-sdk/issues/596)) ([371d27a](https://github.com/mParticle/mparticle-android-sdk/commit/371d27aa8c6ac13d604b68fb241bb5701f6f44ad)) - +- Add Rokt close implementation ([#596](https://github.com/mParticle/mparticle-android-sdk/issues/596)) ([371d27a](https://github.com/mParticle/mparticle-android-sdk/commit/371d27aa8c6ac13d604b68fb241bb5701f6f44ad)) ### Updates & Maintenance -* Update submodules ([f2dfad0](https://github.com/mParticle/mparticle-android-sdk/commit/f2dfad0252e3e3a4112fde7d6fd30421192bed3a)) +- Update submodules ([f2dfad0](https://github.com/mParticle/mparticle-android-sdk/commit/f2dfad0252e3e3a4112fde7d6fd30421192bed3a)) ## [5.70.3](https://github.com/mParticle/mparticle-android-sdk/compare/v5.70.2...v5.70.3) (2025-07-09) - ### Bug Fixes -* Refactor InstallReferrerClient to use reflection ([#592](https://github.com/mParticle/mparticle-android-sdk/issues/592)) ([2d00a6d](https://github.com/mParticle/mparticle-android-sdk/commit/2d00a6d6f29255c759115fa3baa605daa656ff94)) - +- Refactor InstallReferrerClient to use reflection ([#592](https://github.com/mParticle/mparticle-android-sdk/issues/592)) ([2d00a6d](https://github.com/mParticle/mparticle-android-sdk/commit/2d00a6d6f29255c759115fa3baa605daa656ff94)) ### Updates & Maintenance -* 5.70.3 (release) ([a7ad111](https://github.com/mParticle/mparticle-android-sdk/commit/a7ad111932a673e211e82441d5c3df5d54179b2a)), closes [#592](https://github.com/mParticle/mparticle-android-sdk/issues/592) [#594](https://github.com/mParticle/mparticle-android-sdk/issues/594) [#593](https://github.com/mParticle/mparticle-android-sdk/issues/593) [#595](https://github.com/mParticle/mparticle-android-sdk/issues/595) -* Migrate from OSSRH to Central Publishing Portal ([#594](https://github.com/mParticle/mparticle-android-sdk/issues/594)) ([c3eb8bf](https://github.com/mParticle/mparticle-android-sdk/commit/c3eb8bfecf333b9a18fad315ad058e5575407723)) -* Update GitHub Actions workflow ([#593](https://github.com/mParticle/mparticle-android-sdk/issues/593)) ([48b546b](https://github.com/mParticle/mparticle-android-sdk/commit/48b546ba22a0bbbd3420321a887f0bf7aaa7f4b1)) -* Update kit plugin publishing URL from OSSRH to CPP ([#595](https://github.com/mParticle/mparticle-android-sdk/issues/595)) ([bc546ea](https://github.com/mParticle/mparticle-android-sdk/commit/bc546ea072a4abe215d54cf90b648e1aafee567f)) -* Update submodules ([8a7c97c](https://github.com/mParticle/mparticle-android-sdk/commit/8a7c97ce2d74a74f0f436e07d27360a923b253e8)) +- 5.70.3 (release) ([a7ad111](https://github.com/mParticle/mparticle-android-sdk/commit/a7ad111932a673e211e82441d5c3df5d54179b2a)), closes [#592](https://github.com/mParticle/mparticle-android-sdk/issues/592) [#594](https://github.com/mParticle/mparticle-android-sdk/issues/594) [#593](https://github.com/mParticle/mparticle-android-sdk/issues/593) [#595](https://github.com/mParticle/mparticle-android-sdk/issues/595) +- Migrate from OSSRH to Central Publishing Portal ([#594](https://github.com/mParticle/mparticle-android-sdk/issues/594)) ([c3eb8bf](https://github.com/mParticle/mparticle-android-sdk/commit/c3eb8bfecf333b9a18fad315ad058e5575407723)) +- Update GitHub Actions workflow ([#593](https://github.com/mParticle/mparticle-android-sdk/issues/593)) ([48b546b](https://github.com/mParticle/mparticle-android-sdk/commit/48b546ba22a0bbbd3420321a887f0bf7aaa7f4b1)) +- Update kit plugin publishing URL from OSSRH to CPP ([#595](https://github.com/mParticle/mparticle-android-sdk/issues/595)) ([bc546ea](https://github.com/mParticle/mparticle-android-sdk/commit/bc546ea072a4abe215d54cf90b648e1aafee567f)) +- Update submodules ([8a7c97c](https://github.com/mParticle/mparticle-android-sdk/commit/8a7c97ce2d74a74f0f436e07d27360a923b253e8)) ## [5.70.3](https://github.com/mParticle/mparticle-android-sdk/compare/v5.70.2...v5.70.3) (2025-07-08) - ### Bug Fixes -* Refactor InstallReferrerClient to use reflection ([#592](https://github.com/mParticle/mparticle-android-sdk/issues/592)) ([2d00a6d](https://github.com/mParticle/mparticle-android-sdk/commit/2d00a6d6f29255c759115fa3baa605daa656ff94)) - +- Refactor InstallReferrerClient to use reflection ([#592](https://github.com/mParticle/mparticle-android-sdk/issues/592)) ([2d00a6d](https://github.com/mParticle/mparticle-android-sdk/commit/2d00a6d6f29255c759115fa3baa605daa656ff94)) ### Updates & Maintenance -* Migrate from OSSRH to Central Publishing Portal ([#594](https://github.com/mParticle/mparticle-android-sdk/issues/594)) ([c3eb8bf](https://github.com/mParticle/mparticle-android-sdk/commit/c3eb8bfecf333b9a18fad315ad058e5575407723)) -* Update GitHub Actions workflow ([#593](https://github.com/mParticle/mparticle-android-sdk/issues/593)) ([48b546b](https://github.com/mParticle/mparticle-android-sdk/commit/48b546ba22a0bbbd3420321a887f0bf7aaa7f4b1)) -* Update kit plugin publishing URL from OSSRH to CPP ([#595](https://github.com/mParticle/mparticle-android-sdk/issues/595)) ([bc546ea](https://github.com/mParticle/mparticle-android-sdk/commit/bc546ea072a4abe215d54cf90b648e1aafee567f)) +- Migrate from OSSRH to Central Publishing Portal ([#594](https://github.com/mParticle/mparticle-android-sdk/issues/594)) ([c3eb8bf](https://github.com/mParticle/mparticle-android-sdk/commit/c3eb8bfecf333b9a18fad315ad058e5575407723)) +- Update GitHub Actions workflow ([#593](https://github.com/mParticle/mparticle-android-sdk/issues/593)) ([48b546b](https://github.com/mParticle/mparticle-android-sdk/commit/48b546ba22a0bbbd3420321a887f0bf7aaa7f4b1)) +- Update kit plugin publishing URL from OSSRH to CPP ([#595](https://github.com/mParticle/mparticle-android-sdk/issues/595)) ([bc546ea](https://github.com/mParticle/mparticle-android-sdk/commit/bc546ea072a4abe215d54cf90b648e1aafee567f)) ## [5.70.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.70.1...v5.70.2) (2025-06-25) - ### Updates & Maintenance -* Update submodules ([9ae94fa](https://github.com/mParticle/mparticle-android-sdk/commit/9ae94fa1731b3de321f41178736afbbbef39f63e)) +- Update submodules ([9ae94fa](https://github.com/mParticle/mparticle-android-sdk/commit/9ae94fa1731b3de321f41178736afbbbef39f63e)) ## [5.70.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.70.0...v5.70.1) (2025-06-24) - ### Bug Fixes -* Restore ProGuard rules to preserve Rokt class members ([#590](https://github.com/mParticle/mparticle-android-sdk/issues/590)) ([219b1d0](https://github.com/mParticle/mparticle-android-sdk/commit/219b1d006fbf5c678371dbac92d5161ae4bd207e)) - +- Restore ProGuard rules to preserve Rokt class members ([#590](https://github.com/mParticle/mparticle-android-sdk/issues/590)) ([219b1d0](https://github.com/mParticle/mparticle-android-sdk/commit/219b1d006fbf5c678371dbac92d5161ae4bd207e)) ### Updates & Maintenance -* Create CODEOWNERS ([#591](https://github.com/mParticle/mparticle-android-sdk/issues/591)) ([eee1e27](https://github.com/mParticle/mparticle-android-sdk/commit/eee1e2774ddc779521622bd43936675236a8cd79)) +- Create CODEOWNERS ([#591](https://github.com/mParticle/mparticle-android-sdk/issues/591)) ([eee1e27](https://github.com/mParticle/mparticle-android-sdk/commit/eee1e2774ddc779521622bd43936675236a8cd79)) ## [5.70.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.69.0...v5.70.0) (2025-06-23) - ### Features -* Add support for the fontFilePathMap ([#589](https://github.com/mParticle/mparticle-android-sdk/issues/589)) ([71cd132](https://github.com/mParticle/mparticle-android-sdk/commit/71cd1323a2903c90a7f72aef40d49389cbda85bb)) -* SQDSDKS-7420 update select placements ([#586](https://github.com/mParticle/mparticle-android-sdk/issues/586)) ([e583057](https://github.com/mParticle/mparticle-android-sdk/commit/e583057a1cfd1f6da29bf9fc5e99f1c91ac02233)) -* SQDSDKS-7422 - Add all Rokt events ([#587](https://github.com/mParticle/mparticle-android-sdk/issues/587)) ([2487f70](https://github.com/mParticle/mparticle-android-sdk/commit/2487f703b1b110266d82db933dbd19384588cc7f)) - +- Add support for the fontFilePathMap ([#589](https://github.com/mParticle/mparticle-android-sdk/issues/589)) ([71cd132](https://github.com/mParticle/mparticle-android-sdk/commit/71cd1323a2903c90a7f72aef40d49389cbda85bb)) +- SQDSDKS-7420 update select placements ([#586](https://github.com/mParticle/mparticle-android-sdk/issues/586)) ([e583057](https://github.com/mParticle/mparticle-android-sdk/commit/e583057a1cfd1f6da29bf9fc5e99f1c91ac02233)) +- SQDSDKS-7422 - Add all Rokt events ([#587](https://github.com/mParticle/mparticle-android-sdk/issues/587)) ([2487f70](https://github.com/mParticle/mparticle-android-sdk/commit/2487f703b1b110266d82db933dbd19384588cc7f)) ### Bug Fixes -* Include missing overridesSubdirectory flag in networkOptions for domain mapping ([#588](https://github.com/mParticle/mparticle-android-sdk/issues/588)) ([88c73b8](https://github.com/mParticle/mparticle-android-sdk/commit/88c73b83c1fb8f72e88f289f00b9d038a9359fad)) - +- Include missing overridesSubdirectory flag in networkOptions for domain mapping ([#588](https://github.com/mParticle/mparticle-android-sdk/issues/588)) ([88c73b8](https://github.com/mParticle/mparticle-android-sdk/commit/88c73b83c1fb8f72e88f289f00b9d038a9359fad)) ### Updates & Maintenance -* Update submodules ([4429471](https://github.com/mParticle/mparticle-android-sdk/commit/4429471610d522b937c983f4478b5e3fa6b110e5)) +- Update submodules ([4429471](https://github.com/mParticle/mparticle-android-sdk/commit/4429471610d522b937c983f4478b5e3fa6b110e5)) ## [5.69.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.68.0...v5.69.0) (2025-06-17) - ### Features -* Always set the wrapperSdkVersion in KitManager ([#584](https://github.com/mParticle/mparticle-android-sdk/issues/584)) ([a473157](https://github.com/mParticle/mparticle-android-sdk/commit/a4731572656dccc0dc6e3511539bbe8db38792e1)) - +- Always set the wrapperSdkVersion in KitManager ([#584](https://github.com/mParticle/mparticle-android-sdk/issues/584)) ([a473157](https://github.com/mParticle/mparticle-android-sdk/commit/a4731572656dccc0dc6e3511539bbe8db38792e1)) ### Bug Fixes -* ensure user attributes are applied before proceeding with Rokt execution ([#585](https://github.com/mParticle/mparticle-android-sdk/issues/585)) ([df0450e](https://github.com/mParticle/mparticle-android-sdk/commit/df0450e724e9d5b2945739fc3304d87cb0b3a567)) +- ensure user attributes are applied before proceeding with Rokt execution ([#585](https://github.com/mParticle/mparticle-android-sdk/issues/585)) ([df0450e](https://github.com/mParticle/mparticle-android-sdk/commit/df0450e724e9d5b2945739fc3304d87cb0b3a567)) ## [5.68.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.67.0...v5.68.0) (2025-06-14) - ### Features -* Passthrough SDK type to Rokt Kit ([#582](https://github.com/mParticle/mparticle-android-sdk/issues/582)) ([8114d84](https://github.com/mParticle/mparticle-android-sdk/commit/8114d847165b0f429ad367dd7a3cf1e6f5a2cd11)) - +- Passthrough SDK type to Rokt Kit ([#582](https://github.com/mParticle/mparticle-android-sdk/issues/582)) ([8114d84](https://github.com/mParticle/mparticle-android-sdk/commit/8114d847165b0f429ad367dd7a3cf1e6f5a2cd11)) ### Updates & Maintenance -* Update submodules ([5b7bb9e](https://github.com/mParticle/mparticle-android-sdk/commit/5b7bb9e4728bd1ef44a53fa2699ed68ab372cbce)) +- Update submodules ([5b7bb9e](https://github.com/mParticle/mparticle-android-sdk/commit/5b7bb9e4728bd1ef44a53fa2699ed68ab372cbce)) ## [5.67.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.66.0...v5.67.0) (2025-06-13) - ### Features -* Add support purchaseFinalized API in android core ([#583](https://github.com/mParticle/mparticle-android-sdk/issues/583)) ([c041ddb](https://github.com/mParticle/mparticle-android-sdk/commit/c041ddb09ddb2bbe2d2640fc44ac9e64d1b2b795)) - +- Add support purchaseFinalized API in android core ([#583](https://github.com/mParticle/mparticle-android-sdk/issues/583)) ([c041ddb](https://github.com/mParticle/mparticle-android-sdk/commit/c041ddb09ddb2bbe2d2640fc44ac9e64d1b2b795)) ### Updates & Maintenance -* Update submodules ([9f98440](https://github.com/mParticle/mparticle-android-sdk/commit/9f98440b59ae75100fd9cedd90e7d47a3329a5bf)) +- Update submodules ([9f98440](https://github.com/mParticle/mparticle-android-sdk/commit/9f98440b59ae75100fd9cedd90e7d47a3329a5bf)) ## [5.66.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.65.0...v5.66.0) (2025-06-11) - ### Features -* Add RoktConfig in MP layer ([#581](https://github.com/mParticle/mparticle-android-sdk/issues/581)) ([6a71621](https://github.com/mParticle/mparticle-android-sdk/commit/6a71621c506a5212e151ae30981aa04c2c2ce6b3)) - +- Add RoktConfig in MP layer ([#581](https://github.com/mParticle/mparticle-android-sdk/issues/581)) ([6a71621](https://github.com/mParticle/mparticle-android-sdk/commit/6a71621c506a5212e151ae30981aa04c2c2ce6b3)) ### Updates & Maintenance -* Update submodules ([a05d1dd](https://github.com/mParticle/mparticle-android-sdk/commit/a05d1ddacc1c92613df108f04d33065ea866f60c)) +- Update submodules ([a05d1dd](https://github.com/mParticle/mparticle-android-sdk/commit/a05d1ddacc1c92613df108f04d33065ea866f60c)) ## [5.65.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.64.0...v5.65.0) (2025-06-09) - ### Features -* Add sandbox mode to attributes ([#559](https://github.com/mParticle/mparticle-android-sdk/issues/559)) ([cbccd13](https://github.com/mParticle/mparticle-android-sdk/commit/cbccd1322857c5c972ba236f7aaca6debc73fd98)) - +- Add sandbox mode to attributes ([#559](https://github.com/mParticle/mparticle-android-sdk/issues/559)) ([cbccd13](https://github.com/mParticle/mparticle-android-sdk/commit/cbccd1322857c5c972ba236f7aaca6debc73fd98)) ### Bug Fixes -* Add @NonNull and @Nullable annotations to execute method parameters ([#579](https://github.com/mParticle/mparticle-android-sdk/issues/579)) ([9089098](https://github.com/mParticle/mparticle-android-sdk/commit/908909886eecbc0dcefc95838c50d3851715d123)) -* add Rokt dimensions layout to show embedded placements correctly ([#580](https://github.com/mParticle/mparticle-android-sdk/issues/580)) ([9d6813c](https://github.com/mParticle/mparticle-android-sdk/commit/9d6813c66aee6d8dc38740ee6366d7881de623c2)) - +- Add @NonNull and @Nullable annotations to execute method parameters ([#579](https://github.com/mParticle/mparticle-android-sdk/issues/579)) ([9089098](https://github.com/mParticle/mparticle-android-sdk/commit/908909886eecbc0dcefc95838c50d3851715d123)) +- add Rokt dimensions layout to show embedded placements correctly ([#580](https://github.com/mParticle/mparticle-android-sdk/issues/580)) ([9d6813c](https://github.com/mParticle/mparticle-android-sdk/commit/9d6813c66aee6d8dc38740ee6366d7881de623c2)) ### Updates & Maintenance -* Update submodules ([4ed38b5](https://github.com/mParticle/mparticle-android-sdk/commit/4ed38b55e5c6bbcdbe9025994ca669e601b31fe8)) +- Update submodules ([4ed38b5](https://github.com/mParticle/mparticle-android-sdk/commit/4ed38b55e5c6bbcdbe9025994ca669e601b31fe8)) ## [5.64.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.63.0...v5.64.0) (2025-05-30) - ### Features -* Fire Identify if Provided Email in Rokt SelectPlacements ([#578](https://github.com/mParticle/mparticle-android-sdk/issues/578)) ([8325080](https://github.com/mParticle/mparticle-android-sdk/commit/8325080ea251daf7e3f380db83c031b5ea91a960)) - +- Fire Identify if Provided Email in Rokt SelectPlacements ([#578](https://github.com/mParticle/mparticle-android-sdk/issues/578)) ([8325080](https://github.com/mParticle/mparticle-android-sdk/commit/8325080ea251daf7e3f380db83c031b5ea91a960)) ### Bug Fixes -* Removes `messageQueue` since produces memory leaks ([#576](https://github.com/mParticle/mparticle-android-sdk/issues/576)) ([5a2c35a](https://github.com/mParticle/mparticle-android-sdk/commit/5a2c35a791c2063942df73766129344f075ac59c)) - +- Removes `messageQueue` since produces memory leaks ([#576](https://github.com/mParticle/mparticle-android-sdk/issues/576)) ([5a2c35a](https://github.com/mParticle/mparticle-android-sdk/commit/5a2c35a791c2063942df73766129344f075ac59c)) ### Updates & Maintenance -* Migrate Internal listeners class to kotlin ([#548](https://github.com/mParticle/mparticle-android-sdk/issues/548)) ([de96056](https://github.com/mParticle/mparticle-android-sdk/commit/de96056f03c0d812e492aff2cb1d8c83650df720)) -* Update submodules ([5ffd95f](https://github.com/mParticle/mparticle-android-sdk/commit/5ffd95f67f4ee25d114ac9be4dfa57d7e77d03d1)) +- Migrate Internal listeners class to kotlin ([#548](https://github.com/mParticle/mparticle-android-sdk/issues/548)) ([de96056](https://github.com/mParticle/mparticle-android-sdk/commit/de96056f03c0d812e492aff2cb1d8c83650df720)) +- Update submodules ([5ffd95f](https://github.com/mParticle/mparticle-android-sdk/commit/5ffd95f67f4ee25d114ac9be4dfa57d7e77d03d1)) ## [5.63.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.62.2...v5.63.0) (2025-05-12) - ### Features -* Add user attributes mapping logic in Rokt execute flow ([#574](https://github.com/mParticle/mparticle-android-sdk/issues/574)) ([37666be](https://github.com/mParticle/mparticle-android-sdk/commit/37666be14d665addf769ff2059b4a94e944bd5c2)) -* Added Callback Support ([#569](https://github.com/mParticle/mparticle-android-sdk/issues/569)) ([9976373](https://github.com/mParticle/mparticle-android-sdk/commit/99763736dd369d0a98042815b25821420d949e2d)) - +- Add user attributes mapping logic in Rokt execute flow ([#574](https://github.com/mParticle/mparticle-android-sdk/issues/574)) ([37666be](https://github.com/mParticle/mparticle-android-sdk/commit/37666be14d665addf769ff2059b4a94e944bd5c2)) +- Added Callback Support ([#569](https://github.com/mParticle/mparticle-android-sdk/issues/569)) ([9976373](https://github.com/mParticle/mparticle-android-sdk/commit/99763736dd369d0a98042815b25821420d949e2d)) ### Updates & Maintenance -* Update submodules ([4470ad1](https://github.com/mParticle/mparticle-android-sdk/commit/4470ad10ee710080de7078a98b6d88760862eedd)) +- Update submodules ([4470ad1](https://github.com/mParticle/mparticle-android-sdk/commit/4470ad10ee710080de7078a98b6d88760862eedd)) ## [5.62.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.62.1...v5.62.2) (2025-04-23) - ### Updates & Maintenance -* Update submodules ([d2cebb2](https://github.com/mParticle/mparticle-android-sdk/commit/d2cebb2c8bac094f0512ee6142b59b469b58e81f)) +- Update submodules ([d2cebb2](https://github.com/mParticle/mparticle-android-sdk/commit/d2cebb2c8bac094f0512ee6142b59b469b58e81f)) ## [5.62.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.62.0...v5.62.1) (2025-04-23) - ### Bug Fixes -* Rename disabled kit method name ([#573](https://github.com/mParticle/mparticle-android-sdk/issues/573)) ([86f1558](https://github.com/mParticle/mparticle-android-sdk/commit/86f155877d8567336180a790784341d9b32e64ce)) +- Rename disabled kit method name ([#573](https://github.com/mParticle/mparticle-android-sdk/issues/573)) ([86f1558](https://github.com/mParticle/mparticle-android-sdk/commit/86f155877d8567336180a790784341d9b32e64ce)) ## [5.62.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.61.2...v5.62.0) (2025-04-18) - ### Features -* Add option to disable kits in MParticleOptions ([#570](https://github.com/mParticle/mparticle-android-sdk/issues/570)) ([d7e4154](https://github.com/mParticle/mparticle-android-sdk/commit/d7e4154466d5286f9febe420b561b6fb74073556)) - +- Add option to disable kits in MParticleOptions ([#570](https://github.com/mParticle/mparticle-android-sdk/issues/570)) ([d7e4154](https://github.com/mParticle/mparticle-android-sdk/commit/d7e4154466d5286f9febe420b561b6fb74073556)) ### Bug Fixes -* Add ProGuard rule to preserve method visibility ([#571](https://github.com/mParticle/mparticle-android-sdk/issues/571)) ([f01e404](https://github.com/mParticle/mparticle-android-sdk/commit/f01e4042a969e6bc4b9a4b8bfae4c8e077e1839a)) - +- Add ProGuard rule to preserve method visibility ([#571](https://github.com/mParticle/mparticle-android-sdk/issues/571)) ([f01e404](https://github.com/mParticle/mparticle-android-sdk/commit/f01e4042a969e6bc4b9a4b8bfae4c8e077e1839a)) ### Updates & Maintenance -* Add Test Kits step to GitHub workflow ([#568](https://github.com/mParticle/mparticle-android-sdk/issues/568)) ([9415ded](https://github.com/mParticle/mparticle-android-sdk/commit/9415ded3be826e7ca7d6900be96eb5029709b98c)) +- Add Test Kits step to GitHub workflow ([#568](https://github.com/mParticle/mparticle-android-sdk/issues/568)) ([9415ded](https://github.com/mParticle/mparticle-android-sdk/commit/9415ded3be826e7ca7d6900be96eb5029709b98c)) ## [5.61.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.61.1...v5.61.2) (2025-04-14) - ### Bug Fixes -* Add a rule to make sure RoktEmbeddedView and related classes are not removed in release builds ([#566](https://github.com/mParticle/mparticle-android-sdk/issues/566)) ([1a78039](https://github.com/mParticle/mparticle-android-sdk/commit/1a78039dd3cb4383a82f74861254e995eca60c0c)) -* Align Kotlin files with correct package structure ([#565](https://github.com/mParticle/mparticle-android-sdk/issues/565)) ([9b4bd7b](https://github.com/mParticle/mparticle-android-sdk/commit/9b4bd7b0000eed7eb1f2fbd10187cafb52ee30c6)) -* Rokt Submodule link ([#564](https://github.com/mParticle/mparticle-android-sdk/issues/564)) ([e06bf8a](https://github.com/mParticle/mparticle-android-sdk/commit/e06bf8a0f403c571d76b5268305858b21387897c)) - +- Add a rule to make sure RoktEmbeddedView and related classes are not removed in release builds ([#566](https://github.com/mParticle/mparticle-android-sdk/issues/566)) ([1a78039](https://github.com/mParticle/mparticle-android-sdk/commit/1a78039dd3cb4383a82f74861254e995eca60c0c)) +- Align Kotlin files with correct package structure ([#565](https://github.com/mParticle/mparticle-android-sdk/issues/565)) ([9b4bd7b](https://github.com/mParticle/mparticle-android-sdk/commit/9b4bd7b0000eed7eb1f2fbd10187cafb52ee30c6)) +- Rokt Submodule link ([#564](https://github.com/mParticle/mparticle-android-sdk/issues/564)) ([e06bf8a](https://github.com/mParticle/mparticle-android-sdk/commit/e06bf8a0f403c571d76b5268305858b21387897c)) ### Updates & Maintenance -* add rokt-kit as a new submodule ([b897439](https://github.com/mParticle/mparticle-android-sdk/commit/b897439ea06e3989a31a25ed1a014e82f1774856)) -* set rokt-kit submodule to track main branch ([75b72f6](https://github.com/mParticle/mparticle-android-sdk/commit/75b72f67a521d2ac278bac26ce2a6f28c87de6a2)) -* Update submodules ([735fc1f](https://github.com/mParticle/mparticle-android-sdk/commit/735fc1f1beb52fdaac7efbb65d3c66240ce625ed)) +- add rokt-kit as a new submodule ([b897439](https://github.com/mParticle/mparticle-android-sdk/commit/b897439ea06e3989a31a25ed1a014e82f1774856)) +- set rokt-kit submodule to track main branch ([75b72f6](https://github.com/mParticle/mparticle-android-sdk/commit/75b72f67a521d2ac278bac26ce2a6f28c87de6a2)) +- Update submodules ([735fc1f](https://github.com/mParticle/mparticle-android-sdk/commit/735fc1f1beb52fdaac7efbb65d3c66240ce625ed)) ## [5.61.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.61.0...v5.61.1) (2025-04-11) - ### Updates & Maintenance -* Update submodules ([f75499b](https://github.com/mParticle/mparticle-android-sdk/commit/f75499b62144c3d1bc442f2cbe257b54bf204998)) +- Update submodules ([f75499b](https://github.com/mParticle/mparticle-android-sdk/commit/f75499b62144c3d1bc442f2cbe257b54bf204998)) ## [5.61.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.60.0...v5.61.0) (2025-04-11) - ### Features -* Add support for Rokt first-party kit ([#550](https://github.com/mParticle/mparticle-android-sdk/issues/550)) ([8229921](https://github.com/mParticle/mparticle-android-sdk/commit/82299213847d89873b7ade46dbf6a59f0137c534)) - +- Add support for Rokt first-party kit ([#550](https://github.com/mParticle/mparticle-android-sdk/issues/550)) ([8229921](https://github.com/mParticle/mparticle-android-sdk/commit/82299213847d89873b7ade46dbf6a59f0137c534)) ### Bug Fixes -* changed rokt widget namespace ([#558](https://github.com/mParticle/mparticle-android-sdk/issues/558)) ([5910509](https://github.com/mParticle/mparticle-android-sdk/commit/5910509f5200cf290c7d66600403697309c75de5)) -* Disable instrumentation tests temporarily ([#561](https://github.com/mParticle/mparticle-android-sdk/issues/561)) ([372b117](https://github.com/mParticle/mparticle-android-sdk/commit/372b1174a141fb96910a6d04097196bfaf46ee36)) -* Remove broken job dependencies after disabling instrumentation t… ([#562](https://github.com/mParticle/mparticle-android-sdk/issues/562)) ([296582f](https://github.com/mParticle/mparticle-android-sdk/commit/296582f9d36ba3d21438a48bd655b8476a54ef9f)) - +- changed rokt widget namespace ([#558](https://github.com/mParticle/mparticle-android-sdk/issues/558)) ([5910509](https://github.com/mParticle/mparticle-android-sdk/commit/5910509f5200cf290c7d66600403697309c75de5)) +- Disable instrumentation tests temporarily ([#561](https://github.com/mParticle/mparticle-android-sdk/issues/561)) ([372b117](https://github.com/mParticle/mparticle-android-sdk/commit/372b1174a141fb96910a6d04097196bfaf46ee36)) +- Remove broken job dependencies after disabling instrumentation t… ([#562](https://github.com/mParticle/mparticle-android-sdk/issues/562)) ([296582f](https://github.com/mParticle/mparticle-android-sdk/commit/296582f9d36ba3d21438a48bd655b8476a54ef9f)) ### Updates & Maintenance -* Add rokt submodule ([#557](https://github.com/mParticle/mparticle-android-sdk/issues/557)) ([6a4cfda](https://github.com/mParticle/mparticle-android-sdk/commit/6a4cfda900351bacb160772f079a5146bcd6bc89)) +- Add rokt submodule ([#557](https://github.com/mParticle/mparticle-android-sdk/issues/557)) ([6a4cfda](https://github.com/mParticle/mparticle-android-sdk/commit/6a4cfda900351bacb160772f079a5146bcd6bc89)) ## [5.60.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.59.0...v5.60.0) (2025-04-07) - ### Features -* Remove the existing code and added new method 'getUserAudience' ([#542](https://github.com/mParticle/mparticle-android-sdk/issues/542)) ([cf8328a](https://github.com/mParticle/mparticle-android-sdk/commit/cf8328ab70dd7c92021dd31181d296519aebd135)) - +- Remove the existing code and added new method 'getUserAudience' ([#542](https://github.com/mParticle/mparticle-android-sdk/issues/542)) ([cf8328a](https://github.com/mParticle/mparticle-android-sdk/commit/cf8328ab70dd7c92021dd31181d296519aebd135)) ### Updates & Maintenance -* Remove manual build variant detection via isRelease flag ([#554](https://github.com/mParticle/mparticle-android-sdk/issues/554)) ([85f8c5c](https://github.com/mParticle/mparticle-android-sdk/commit/85f8c5c4f895717a31d399f4950f72cdb30eb14a)) -* Remove need for -PisRelease=true flag in Gradle command ([#555](https://github.com/mParticle/mparticle-android-sdk/issues/555)) ([185b621](https://github.com/mParticle/mparticle-android-sdk/commit/185b62131da180d6ee91268f9da703bd1769160d)) -* Update GitHub workflow to remove Test Kits step ([#556](https://github.com/mParticle/mparticle-android-sdk/issues/556)) ([6873903](https://github.com/mParticle/mparticle-android-sdk/commit/6873903e527154352b88e98e38fc8145b131431d)) -* Update submodules ([3274ce7](https://github.com/mParticle/mparticle-android-sdk/commit/3274ce7c3ce87f1558ac057888c4633cc9d55897)) +- Remove manual build variant detection via isRelease flag ([#554](https://github.com/mParticle/mparticle-android-sdk/issues/554)) ([85f8c5c](https://github.com/mParticle/mparticle-android-sdk/commit/85f8c5c4f895717a31d399f4950f72cdb30eb14a)) +- Remove need for -PisRelease=true flag in Gradle command ([#555](https://github.com/mParticle/mparticle-android-sdk/issues/555)) ([185b621](https://github.com/mParticle/mparticle-android-sdk/commit/185b62131da180d6ee91268f9da703bd1769160d)) +- Update GitHub workflow to remove Test Kits step ([#556](https://github.com/mParticle/mparticle-android-sdk/issues/556)) ([6873903](https://github.com/mParticle/mparticle-android-sdk/commit/6873903e527154352b88e98e38fc8145b131431d)) +- Update submodules ([3274ce7](https://github.com/mParticle/mparticle-android-sdk/commit/3274ce7c3ce87f1558ac057888c4633cc9d55897)) ## [5.59.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.58.12...v5.59.0) (2025-04-03) - ### Features -* Add Workspace Switching feature ([#551](https://github.com/mParticle/mparticle-android-sdk/issues/551)) ([de72f0a](https://github.com/mParticle/mparticle-android-sdk/commit/de72f0a0afe0917e1550ea9a31e212a9682fc4f4)) - +- Add Workspace Switching feature ([#551](https://github.com/mParticle/mparticle-android-sdk/issues/551)) ([de72f0a](https://github.com/mParticle/mparticle-android-sdk/commit/de72f0a0afe0917e1550ea9a31e212a9682fc4f4)) ### Updates & Maintenance -* Downgrade API level to 28 for both instrument test and instrument… ([#552](https://github.com/mParticle/mparticle-android-sdk/issues/552)) ([ddf8f4f](https://github.com/mParticle/mparticle-android-sdk/commit/ddf8f4f19dd159193e9c80a764270f4eadc1973f)) -* Downgrade API level to 28 for daily yml file ([#553](https://github.com/mParticle/mparticle-android-sdk/issues/553)) ([12eef85](https://github.com/mParticle/mparticle-android-sdk/commit/12eef852fe8329d46631206f158ec5c77bbacf2c)) +- Downgrade API level to 28 for both instrument test and instrument… ([#552](https://github.com/mParticle/mparticle-android-sdk/issues/552)) ([ddf8f4f](https://github.com/mParticle/mparticle-android-sdk/commit/ddf8f4f19dd159193e9c80a764270f4eadc1973f)) +- Downgrade API level to 28 for daily yml file ([#553](https://github.com/mParticle/mparticle-android-sdk/issues/553)) ([12eef85](https://github.com/mParticle/mparticle-android-sdk/commit/12eef852fe8329d46631206f158ec5c77bbacf2c)) ## [5.58.12](https://github.com/mParticle/mparticle-android-sdk/compare/v5.58.11...v5.58.12) (2025-03-18) - ### Updates & Maintenance -* Update submodules ([01c5f37](https://github.com/mParticle/mparticle-android-sdk/commit/01c5f37367fc928f8e3c42105f8af5b755bfb113)) +- Update submodules ([01c5f37](https://github.com/mParticle/mparticle-android-sdk/commit/01c5f37367fc928f8e3c42105f8af5b755bfb113)) ## [5.58.11](https://github.com/mParticle/mparticle-android-sdk/compare/v5.58.10...v5.58.11) (2025-03-05) - ### Bug Fixes -* Update Kotlin version to be compatible with Braze ([#547](https://github.com/mParticle/mparticle-android-sdk/issues/547)) ([50d73b3](https://github.com/mParticle/mparticle-android-sdk/commit/50d73b3168db250626afe6641bc691173c2024f4)) - +- Update Kotlin version to be compatible with Braze ([#547](https://github.com/mParticle/mparticle-android-sdk/issues/547)) ([50d73b3](https://github.com/mParticle/mparticle-android-sdk/commit/50d73b3168db250626afe6641bc691173c2024f4)) ### Updates & Maintenance -* Update submodules ([b9ccc6c](https://github.com/mParticle/mparticle-android-sdk/commit/b9ccc6c68001267d0a962fdcbf9f58298f01ce0f)) +- Update submodules ([b9ccc6c](https://github.com/mParticle/mparticle-android-sdk/commit/b9ccc6c68001267d0a962fdcbf9f58298f01ce0f)) ## [5.58.10](https://github.com/mParticle/mparticle-android-sdk/compare/v5.58.9...v5.58.10) (2025-02-27) - ### Bug Fixes -* previous Google ad Id from being null on cold launch ([#546](https://github.com/mParticle/mparticle-android-sdk/issues/546)) ([3051a82](https://github.com/mParticle/mparticle-android-sdk/commit/3051a823c48720c4810ace37f8a5241768ede0fc)) - +- previous Google ad Id from being null on cold launch ([#546](https://github.com/mParticle/mparticle-android-sdk/issues/546)) ([3051a82](https://github.com/mParticle/mparticle-android-sdk/commit/3051a823c48720c4810ace37f8a5241768ede0fc)) ### Updates & Maintenance -* Migrate Internal Application context class to kotlin ([#545](https://github.com/mParticle/mparticle-android-sdk/issues/545)) ([ecd2833](https://github.com/mParticle/mparticle-android-sdk/commit/ecd2833a505059b95654b684b771595c92a146eb)) -* Update submodules ([e9cb498](https://github.com/mParticle/mparticle-android-sdk/commit/e9cb49839ad7c77beff5ef8e6d3db60073b7ec21)) +- Migrate Internal Application context class to kotlin ([#545](https://github.com/mParticle/mparticle-android-sdk/issues/545)) ([ecd2833](https://github.com/mParticle/mparticle-android-sdk/commit/ecd2833a505059b95654b684b771595c92a146eb)) +- Update submodules ([e9cb498](https://github.com/mParticle/mparticle-android-sdk/commit/e9cb49839ad7c77beff5ef8e6d3db60073b7ec21)) ## [5.58.9](https://github.com/mParticle/mparticle-android-sdk/compare/v5.58.8...v5.58.9) (2025-02-13) - ### Updates & Maintenance -* Update submodules ([9686aed](https://github.com/mParticle/mparticle-android-sdk/commit/9686aed591a7998f9edd539ecdf1d10e68b419d9)) +- Update submodules ([9686aed](https://github.com/mParticle/mparticle-android-sdk/commit/9686aed591a7998f9edd539ecdf1d10e68b419d9)) ## [5.58.8](https://github.com/mParticle/mparticle-android-sdk/compare/v5.58.7...v5.58.8) (2025-02-13) - ### Updates & Maintenance -* Migrate Internal CoreCallback class to kotlin ([#543](https://github.com/mParticle/mparticle-android-sdk/issues/543)) ([c9c8cfb](https://github.com/mParticle/mparticle-android-sdk/commit/c9c8cfba4b9a9d8676c4d6bccd7910ff27527016)) -* Remove Pilgrim-kit from cross-platform testing ([#544](https://github.com/mParticle/mparticle-android-sdk/issues/544)) ([08401bc](https://github.com/mParticle/mparticle-android-sdk/commit/08401bcd20212473a7ac8fd33580cd3b169f1ac6)) -* Update submodules ([2386eba](https://github.com/mParticle/mparticle-android-sdk/commit/2386eba0bf094ace8ea002cfd6697e5a88ccdca0)) +- Migrate Internal CoreCallback class to kotlin ([#543](https://github.com/mParticle/mparticle-android-sdk/issues/543)) ([c9c8cfb](https://github.com/mParticle/mparticle-android-sdk/commit/c9c8cfba4b9a9d8676c4d6bccd7910ff27527016)) +- Remove Pilgrim-kit from cross-platform testing ([#544](https://github.com/mParticle/mparticle-android-sdk/issues/544)) ([08401bc](https://github.com/mParticle/mparticle-android-sdk/commit/08401bcd20212473a7ac8fd33580cd3b169f1ac6)) +- Update submodules ([2386eba](https://github.com/mParticle/mparticle-android-sdk/commit/2386eba0bf094ace8ea002cfd6697e5a88ccdca0)) ## [5.58.7](https://github.com/mParticle/mparticle-android-sdk/compare/v5.58.6...v5.58.7) (2025-02-07) - ### Bug Fixes -* Disable location tracking to stop setting location updates ([#540](https://github.com/mParticle/mparticle-android-sdk/issues/540)) ([8f68edb](https://github.com/mParticle/mparticle-android-sdk/commit/8f68edb2dd06a9e606bd099a2334fdc389f01907)) - +- Disable location tracking to stop setting location updates ([#540](https://github.com/mParticle/mparticle-android-sdk/issues/540)) ([8f68edb](https://github.com/mParticle/mparticle-android-sdk/commit/8f68edb2dd06a9e606bd099a2334fdc389f01907)) ### Updates & Maintenance -* Update submodules ([a9ca8d9](https://github.com/mParticle/mparticle-android-sdk/commit/a9ca8d90e93996936ebc57a46b2c7e5efc32f4e7)) +- Update submodules ([a9ca8d9](https://github.com/mParticle/mparticle-android-sdk/commit/a9ca8d90e93996936ebc57a46b2c7e5efc32f4e7)) ## [5.58.6](https://github.com/mParticle/mparticle-android-sdk/compare/v5.58.5...v5.58.6) (2025-01-30) - ### Updates & Maintenance -* Migrate Internal OS Helper class to kotlin ([#515](https://github.com/mParticle/mparticle-android-sdk/issues/515)) ([#536](https://github.com/mParticle/mparticle-android-sdk/issues/536)) ([6ce2e7d](https://github.com/mParticle/mparticle-android-sdk/commit/6ce2e7d08642e3b64c2c3251a44aca5967975d66)) -* Migrate Internal user storage class to kotlin ([#516](https://github.com/mParticle/mparticle-android-sdk/issues/516)) ([#539](https://github.com/mParticle/mparticle-android-sdk/issues/539)) ([fab4925](https://github.com/mParticle/mparticle-android-sdk/commit/fab49257dd28495250ffca9ce8383ad60c0b728a)) +- Migrate Internal OS Helper class to kotlin ([#515](https://github.com/mParticle/mparticle-android-sdk/issues/515)) ([#536](https://github.com/mParticle/mparticle-android-sdk/issues/536)) ([6ce2e7d](https://github.com/mParticle/mparticle-android-sdk/commit/6ce2e7d08642e3b64c2c3251a44aca5967975d66)) +- Migrate Internal user storage class to kotlin ([#516](https://github.com/mParticle/mparticle-android-sdk/issues/516)) ([#539](https://github.com/mParticle/mparticle-android-sdk/issues/539)) ([fab4925](https://github.com/mParticle/mparticle-android-sdk/commit/fab49257dd28495250ffca9ce8383ad60c0b728a)) ## [5.58.5](https://github.com/mParticle/mparticle-android-sdk/compare/v5.58.4...v5.58.5) (2025-01-24) - ### Updates & Maintenance -* Add issue autorespond and close workflow ([#526](https://github.com/mParticle/mparticle-android-sdk/issues/526)) ([28ccb97](https://github.com/mParticle/mparticle-android-sdk/commit/28ccb97f1dc709d25ed686dae241f8462c62b9cf)) -* Update cross-platform-tests.yml ([#530](https://github.com/mParticle/mparticle-android-sdk/issues/530)) ([0924e88](https://github.com/mParticle/mparticle-android-sdk/commit/0924e88331d3f92fb7bdd774fd33e162c4fc0aa2)) -* update emulator version tag ([#537](https://github.com/mParticle/mparticle-android-sdk/issues/537)) ([4f2fea6](https://github.com/mParticle/mparticle-android-sdk/commit/4f2fea6290e497e32d6045fb2d1d32f44538f1f2)) -* Update submodules ([ab53cb1](https://github.com/mParticle/mparticle-android-sdk/commit/ab53cb1f54e5251980045b8f754fca14966d95fa)) +- Add issue autorespond and close workflow ([#526](https://github.com/mParticle/mparticle-android-sdk/issues/526)) ([28ccb97](https://github.com/mParticle/mparticle-android-sdk/commit/28ccb97f1dc709d25ed686dae241f8462c62b9cf)) +- Update cross-platform-tests.yml ([#530](https://github.com/mParticle/mparticle-android-sdk/issues/530)) ([0924e88](https://github.com/mParticle/mparticle-android-sdk/commit/0924e88331d3f92fb7bdd774fd33e162c4fc0aa2)) +- update emulator version tag ([#537](https://github.com/mParticle/mparticle-android-sdk/issues/537)) ([4f2fea6](https://github.com/mParticle/mparticle-android-sdk/commit/4f2fea6290e497e32d6045fb2d1d32f44538f1f2)) +- Update submodules ([ab53cb1](https://github.com/mParticle/mparticle-android-sdk/commit/ab53cb1f54e5251980045b8f754fca14966d95fa)) ## [5.58.4](https://github.com/mParticle/mparticle-android-sdk/compare/v5.58.3...v5.58.4) (2024-12-12) - ### Updates & Maintenance -* Fix release action trying to push to old internal repo ([09101f2](https://github.com/mParticle/mparticle-android-sdk/commit/09101f2bd6e529b857bfb66c8196f7754d0e26e6)) -* Update submodules ([36a6396](https://github.com/mParticle/mparticle-android-sdk/commit/36a6396a3f91293d74b77318ca06e3e44cd8c6ad)) +- Fix release action trying to push to old internal repo ([09101f2](https://github.com/mParticle/mparticle-android-sdk/commit/09101f2bd6e529b857bfb66c8196f7754d0e26e6)) +- Update submodules ([36a6396](https://github.com/mParticle/mparticle-android-sdk/commit/36a6396a3f91293d74b77318ca06e3e44cd8c6ad)) ## [5.58.3](https://github.com/mParticle/mparticle-android-sdk/compare/v5.58.2...v5.58.3) (2024-10-24) - ### Updates & Maintenance -* Migrate Internal Constants class to kotlin ([#510](https://github.com/mParticle/mparticle-android-sdk/issues/510)) ([2fd32f6](https://github.com/mParticle/mparticle-android-sdk/commit/2fd32f6d068975b0c57bde1a50e25c3a1c5617bb)) -* Migrate MPLifecycleCallbackDelegate and MPLocationListener class to Kotlin ([#506](https://github.com/mParticle/mparticle-android-sdk/issues/506)) ([687e623](https://github.com/mParticle/mparticle-android-sdk/commit/687e6234bdfc6b24680e92f348422f4a5c298529)) -* Remove unused session history upload code ([#507](https://github.com/mParticle/mparticle-android-sdk/issues/507)) ([a86cd3b](https://github.com/mParticle/mparticle-android-sdk/commit/a86cd3b7bdc923a152ae9f5503244aadb50065de)) -* Update submodules ([81e50ca](https://github.com/mParticle/mparticle-android-sdk/commit/81e50ca7f9f185c143dbc3567772e331588f72cd)) +- Migrate Internal Constants class to kotlin ([#510](https://github.com/mParticle/mparticle-android-sdk/issues/510)) ([2fd32f6](https://github.com/mParticle/mparticle-android-sdk/commit/2fd32f6d068975b0c57bde1a50e25c3a1c5617bb)) +- Migrate MPLifecycleCallbackDelegate and MPLocationListener class to Kotlin ([#506](https://github.com/mParticle/mparticle-android-sdk/issues/506)) ([687e623](https://github.com/mParticle/mparticle-android-sdk/commit/687e6234bdfc6b24680e92f348422f4a5c298529)) +- Remove unused session history upload code ([#507](https://github.com/mParticle/mparticle-android-sdk/issues/507)) ([a86cd3b](https://github.com/mParticle/mparticle-android-sdk/commit/a86cd3b7bdc923a152ae9f5503244aadb50065de)) +- Update submodules ([81e50ca](https://github.com/mParticle/mparticle-android-sdk/commit/81e50ca7f9f185c143dbc3567772e331588f72cd)) ## [5.58.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.58.1...v5.58.2) (2024-09-11) - ### Updates & Maintenance -* Update submodules ([ae9f719](https://github.com/mParticle/mparticle-android-sdk/commit/ae9f719f71e59f3b0c85a87f6083a053dfb7b348)) +- Update submodules ([ae9f719](https://github.com/mParticle/mparticle-android-sdk/commit/ae9f719f71e59f3b0c85a87f6083a053dfb7b348)) ## [5.58.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.58.0...v5.58.1) (2024-08-29) - ### Updates & Maintenance -* Update submodules ([3d79f75](https://github.com/mParticle/mparticle-android-sdk/commit/3d79f75fcc9baa7ed5631eac1e982e2160c1475b)) +- Update submodules ([3d79f75](https://github.com/mParticle/mparticle-android-sdk/commit/3d79f75fcc9baa7ed5631eac1e982e2160c1475b)) ## [5.58.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.57.0...v5.58.0) (2024-08-21) - ### Features -* Certificate pinning update ([#504](https://github.com/mParticle/mparticle-android-sdk/issues/504)) ([85b38cd](https://github.com/mParticle/mparticle-android-sdk/commit/85b38cd4703a92fc5ea692eab6660361f793dfed)) - +- Certificate pinning update ([#504](https://github.com/mParticle/mparticle-android-sdk/issues/504)) ([85b38cd](https://github.com/mParticle/mparticle-android-sdk/commit/85b38cd4703a92fc5ea692eab6660361f793dfed)) ### Updates & Maintenance -* Update submodules ([2c359eb](https://github.com/mParticle/mparticle-android-sdk/commit/2c359eb7bcf5ed53a6cc3db0a6e39e9a2a0330c5)) +- Update submodules ([2c359eb](https://github.com/mParticle/mparticle-android-sdk/commit/2c359eb7bcf5ed53a6cc3db0a6e39e9a2a0330c5)) ## [5.57.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.56.5...v5.57.0) (2024-08-13) - ### Features -* Support direct URL routing ([#499](https://github.com/mParticle/mparticle-android-sdk/issues/499)) ([d7aa30c](https://github.com/mParticle/mparticle-android-sdk/commit/d7aa30c8c5ed53b72ac4d9914ef07915f4c374e4)) - +- Support direct URL routing ([#499](https://github.com/mParticle/mparticle-android-sdk/issues/499)) ([d7aa30c](https://github.com/mParticle/mparticle-android-sdk/commit/d7aa30c8c5ed53b72ac4d9914ef07915f4c374e4)) ### Bug Fixes -* Crash in KitConfiguration due to NumberFormatException ([#503](https://github.com/mParticle/mparticle-android-sdk/issues/503)) ([e1a23e7](https://github.com/mParticle/mparticle-android-sdk/commit/e1a23e786f22068da004084e363986cd2e377981)) +- Crash in KitConfiguration due to NumberFormatException ([#503](https://github.com/mParticle/mparticle-android-sdk/issues/503)) ([e1a23e7](https://github.com/mParticle/mparticle-android-sdk/commit/e1a23e786f22068da004084e363986cd2e377981)) ## [5.56.5](https://github.com/mParticle/mparticle-android-sdk/compare/v5.56.4...v5.56.5) (2024-08-06) - ### Bug Fixes -* Remove Code for Handling Google AdId on a Separate Thread ([#502](https://github.com/mParticle/mparticle-android-sdk/issues/502)) ([17928b9](https://github.com/mParticle/mparticle-android-sdk/commit/17928b99fc1ba69b8aba33a8f497095e8bbab1b3)) +- Remove Code for Handling Google AdId on a Separate Thread ([#502](https://github.com/mParticle/mparticle-android-sdk/issues/502)) ([17928b9](https://github.com/mParticle/mparticle-android-sdk/commit/17928b99fc1ba69b8aba33a8f497095e8bbab1b3)) ## [5.56.4](https://github.com/mParticle/mparticle-android-sdk/compare/v5.56.3...v5.56.4) (2024-07-31) - ### Updates & Maintenance -* Update submodules ([8c59ab1](https://github.com/mParticle/mparticle-android-sdk/commit/8c59ab1c35d114313e61bf5a5ffd368a8451491f)) +- Update submodules ([8c59ab1](https://github.com/mParticle/mparticle-android-sdk/commit/8c59ab1c35d114313e61bf5a5ffd368a8451491f)) ## [5.56.3](https://github.com/mParticle/mparticle-android-sdk/compare/v5.56.2...v5.56.3) (2024-07-25) - ### Updates & Maintenance -* Update submodules ([e682c04](https://github.com/mParticle/mparticle-android-sdk/commit/e682c0499594e32a0ea43743ec386f2e6583fb8e)) +- Update submodules ([e682c04](https://github.com/mParticle/mparticle-android-sdk/commit/e682c0499594e32a0ea43743ec386f2e6583fb8e)) ## [5.56.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.56.1...v5.56.2) (2024-07-09) - ### Updates & Maintenance -* Update submodules ([68ecba7](https://github.com/mParticle/mparticle-android-sdk/commit/68ecba79ed8b17e1db0cffa79c871b8d55fdeaa7)) +- Update submodules ([68ecba7](https://github.com/mParticle/mparticle-android-sdk/commit/68ecba79ed8b17e1db0cffa79c871b8d55fdeaa7)) ## [5.56.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.56.0...v5.56.1) (2024-07-09) - ### Bug Fixes -* Add enum value for event types ([#496](https://github.com/mParticle/mparticle-android-sdk/issues/496)) ([b6ecb8a](https://github.com/mParticle/mparticle-android-sdk/commit/b6ecb8ad1436cd703574e94c236c12882ab9908b)) +- Add enum value for event types ([#496](https://github.com/mParticle/mparticle-android-sdk/issues/496)) ([b6ecb8a](https://github.com/mParticle/mparticle-android-sdk/commit/b6ecb8ad1436cd703574e94c236c12882ab9908b)) ## [5.56.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.55.9...v5.56.0) (2024-06-25) - ### Features -* Add option to disable certificate pinning ([#495](https://github.com/mParticle/mparticle-android-sdk/issues/495)) ([7c53bad](https://github.com/mParticle/mparticle-android-sdk/commit/7c53badb8e7dcffb0210c63de5af6c9323814c7f)) +- Add option to disable certificate pinning ([#495](https://github.com/mParticle/mparticle-android-sdk/issues/495)) ([7c53bad](https://github.com/mParticle/mparticle-android-sdk/commit/7c53badb8e7dcffb0210c63de5af6c9323814c7f)) ## [5.55.9](https://github.com/mParticle/mparticle-android-sdk/compare/v5.55.8...v5.55.9) (2024-06-25) - ### Bug Fixes -* Refactor code for accessing Google Ad info ([#491](https://github.com/mParticle/mparticle-android-sdk/issues/491)) ([ee1525c](https://github.com/mParticle/mparticle-android-sdk/commit/ee1525c5eae2ca88277a1f2ac6115b028b981a4f)) - +- Refactor code for accessing Google Ad info ([#491](https://github.com/mParticle/mparticle-android-sdk/issues/491)) ([ee1525c](https://github.com/mParticle/mparticle-android-sdk/commit/ee1525c5eae2ca88277a1f2ac6115b028b981a4f)) ### Updates & Maintenance -* Update submodules ([d6a2ba5](https://github.com/mParticle/mparticle-android-sdk/commit/d6a2ba59462668cbf4b4dda5bb8c7b82696e5214)) +- Update submodules ([d6a2ba5](https://github.com/mParticle/mparticle-android-sdk/commit/d6a2ba59462668cbf4b4dda5bb8c7b82696e5214)) ## [5.55.8](https://github.com/mParticle/mparticle-android-sdk/compare/v5.55.7...v5.55.8) (2024-05-31) - ### Bug Fixes -* Use DisplayMetrics instead of WindowManager for StrictMode Error ([#483](https://github.com/mParticle/mparticle-android-sdk/issues/483)) ([648c079](https://github.com/mParticle/mparticle-android-sdk/commit/648c079d26608314f117d3e96433d289b522228d)) - +- Use DisplayMetrics instead of WindowManager for StrictMode Error ([#483](https://github.com/mParticle/mparticle-android-sdk/issues/483)) ([648c079](https://github.com/mParticle/mparticle-android-sdk/commit/648c079d26608314f117d3e96433d289b522228d)) ### Updates & Maintenance -* Update submodules ([fa40e06](https://github.com/mParticle/mparticle-android-sdk/commit/fa40e06f8acd64d33f1f81e3ddbe0da8a01203da)) +- Update submodules ([fa40e06](https://github.com/mParticle/mparticle-android-sdk/commit/fa40e06f8acd64d33f1f81e3ddbe0da8a01203da)) ## [5.55.7](https://github.com/mParticle/mparticle-android-sdk/compare/v5.55.6...v5.55.7) (2024-05-29) - ### Bug Fixes -* Update Java version, pin conventional commits ([#490](https://github.com/mParticle/mparticle-android-sdk/issues/490)) ([a4f1979](https://github.com/mParticle/mparticle-android-sdk/commit/a4f19790b2123d17a25692b00e0c638793d64672)) -* Update mac version and JDK version into yml file ([#482](https://github.com/mParticle/mparticle-android-sdk/issues/482)) ([b67c108](https://github.com/mParticle/mparticle-android-sdk/commit/b67c108367e6e86f8a9c431f2e59afdea4ef5768)) - +- Update Java version, pin conventional commits ([#490](https://github.com/mParticle/mparticle-android-sdk/issues/490)) ([a4f1979](https://github.com/mParticle/mparticle-android-sdk/commit/a4f19790b2123d17a25692b00e0c638793d64672)) +- Update mac version and JDK version into yml file ([#482](https://github.com/mParticle/mparticle-android-sdk/issues/482)) ([b67c108](https://github.com/mParticle/mparticle-android-sdk/commit/b67c108367e6e86f8a9c431f2e59afdea4ef5768)) ### Updates & Maintenance -* Update submodules ([f4ce2a4](https://github.com/mParticle/mparticle-android-sdk/commit/f4ce2a4284f3ac7e32c34d7ee2858dba75daf8bc)) +- Update submodules ([f4ce2a4](https://github.com/mParticle/mparticle-android-sdk/commit/f4ce2a4284f3ac7e32c34d7ee2858dba75daf8bc)) ## [5.55.6](https://github.com/mParticle/mparticle-android-sdk/compare/v5.55.5...v5.55.6) (2024-04-24) - ### Updates & Maintenance -* Update submodules ([72d925b](https://github.com/mParticle/mparticle-android-sdk/commit/72d925b1834f9dfa91b96f5e794c56c0efb1800f)) +- Update submodules ([72d925b](https://github.com/mParticle/mparticle-android-sdk/commit/72d925b1834f9dfa91b96f5e794c56c0efb1800f)) ## [5.55.5](https://github.com/mParticle/mparticle-android-sdk/compare/v5.55.4...v5.55.5) (2024-04-19) - ### Updates & Maintenance -* Update submodules ([e5f48b9](https://github.com/mParticle/mparticle-android-sdk/commit/e5f48b9b143c96f6bfee8f066bc0ab790f5f71a6)) +- Update submodules ([e5f48b9](https://github.com/mParticle/mparticle-android-sdk/commit/e5f48b9b143c96f6bfee8f066bc0ab790f5f71a6)) ## [5.55.4](https://github.com/mParticle/mparticle-android-sdk/compare/v5.55.3...v5.55.4) (2024-04-12) - ### Updates & Maintenance -* Update submodules ([4ecd3de](https://github.com/mParticle/mparticle-android-sdk/commit/4ecd3de8db824ebe94ccbe55d46de0069fd5f1d9)) +- Update submodules ([4ecd3de](https://github.com/mParticle/mparticle-android-sdk/commit/4ecd3de8db824ebe94ccbe55d46de0069fd5f1d9)) ## [5.55.3](https://github.com/mParticle/mparticle-android-sdk/compare/v5.55.2...v5.55.3) (2024-04-12) - ### Bug Fixes -* ANRs in android app due to multiple installReferrer API calls ([#479](https://github.com/mParticle/mparticle-android-sdk/issues/479)) ([353eac7](https://github.com/mParticle/mparticle-android-sdk/commit/353eac72ea53f78d620e2e0be3e3883675ec8df0)) - +- ANRs in android app due to multiple installReferrer API calls ([#479](https://github.com/mParticle/mparticle-android-sdk/issues/479)) ([353eac7](https://github.com/mParticle/mparticle-android-sdk/commit/353eac72ea53f78d620e2e0be3e3883675ec8df0)) ### Updates & Maintenance -* Update submodules ([2e75a6d](https://github.com/mParticle/mparticle-android-sdk/commit/2e75a6db592a31db47c8599753a3e290483c4a5e)) +- Update submodules ([2e75a6d](https://github.com/mParticle/mparticle-android-sdk/commit/2e75a6db592a31db47c8599753a3e290483c4a5e)) ## [5.55.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.55.1...v5.55.2) (2024-03-02) - ### Bug Fixes -* make number parsing more strict ([a831780](https://github.com/mParticle/mparticle-android-sdk/commit/a8317807e60a6239181b44496b5707104421a96f)) - +- make number parsing more strict ([a831780](https://github.com/mParticle/mparticle-android-sdk/commit/a8317807e60a6239181b44496b5707104421a96f)) ### Updates & Maintenance -* Update submodules ([d8a2903](https://github.com/mParticle/mparticle-android-sdk/commit/d8a2903e249cfa8070687a482d3317fd67a295f2)) +- Update submodules ([d8a2903](https://github.com/mParticle/mparticle-android-sdk/commit/d8a2903e249cfa8070687a482d3317fd67a295f2)) ## [5.55.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.55.0...v5.55.1) (2024-02-06) - ### Bug Fixes -* SQDSDK-5597 - Get ad id in background thread ([#463](https://github.com/mParticle/mparticle-android-sdk/issues/463)) ([679d987](https://github.com/mParticle/mparticle-android-sdk/commit/679d9875ba56d421e5d6f2d1d9dbb5cc2189f533)) - +- SQDSDK-5597 - Get ad id in background thread ([#463](https://github.com/mParticle/mparticle-android-sdk/issues/463)) ([679d987](https://github.com/mParticle/mparticle-android-sdk/commit/679d9875ba56d421e5d6f2d1d9dbb5cc2189f533)) ### Updates & Maintenance -* Update submodules ([d4f2512](https://github.com/mParticle/mparticle-android-sdk/commit/d4f2512daaacf1c5d33545f13aae9e369fb9f02c)) +- Update submodules ([d4f2512](https://github.com/mParticle/mparticle-android-sdk/commit/d4f2512daaacf1c5d33545f13aae9e369fb9f02c)) ## [5.55.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.54.0...v5.55.0) (2023-12-13) - ### Features -* SQDSDKS-5723 - Remove custom attributes limit to MPEvents. ([#456](https://github.com/mParticle/mparticle-android-sdk/issues/456)) ([32c788e](https://github.com/mParticle/mparticle-android-sdk/commit/32c788ee15d532c2e93a9b50ab996b240341a1f8)) - +- SQDSDKS-5723 - Remove custom attributes limit to MPEvents. ([#456](https://github.com/mParticle/mparticle-android-sdk/issues/456)) ([32c788e](https://github.com/mParticle/mparticle-android-sdk/commit/32c788ee15d532c2e93a9b50ab996b240341a1f8)) ### Bug Fixes -* only delete branch if all succeeds ([f239ba8](https://github.com/mParticle/mparticle-android-sdk/commit/f239ba87fe32fb8fb86d2454b2495fb3890d0653)) +- only delete branch if all succeeds ([f239ba8](https://github.com/mParticle/mparticle-android-sdk/commit/f239ba87fe32fb8fb86d2454b2495fb3890d0653)) ## [5.54.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.53.2...v5.54.0) (2023-11-03) - ### Features -* update CI in kits ([5b12dbc](https://github.com/mParticle/mparticle-android-sdk/commit/5b12dbc9b3bf1f72651d1d96882bab104fa434b1)) - +- update CI in kits ([5b12dbc](https://github.com/mParticle/mparticle-android-sdk/commit/5b12dbc9b3bf1f72651d1d96882bab104fa434b1)) ### Bug Fixes -* kit syntax for lint ([fc63aa1](https://github.com/mParticle/mparticle-android-sdk/commit/fc63aa11683bd8b95fb8300fadcb9a9753fe0eec)) -* remove daily cron and fix branch deletion ([57fda36](https://github.com/mParticle/mparticle-android-sdk/commit/57fda36576e5967e5fc2b0cbb7a3f1f1f4c7c902)) - +- kit syntax for lint ([fc63aa1](https://github.com/mParticle/mparticle-android-sdk/commit/fc63aa11683bd8b95fb8300fadcb9a9753fe0eec)) +- remove daily cron and fix branch deletion ([57fda36](https://github.com/mParticle/mparticle-android-sdk/commit/57fda36576e5967e5fc2b0cbb7a3f1f1f4c7c902)) ### Updates & Maintenance -* pin all third party github actions ([74bcca8](https://github.com/mParticle/mparticle-android-sdk/commit/74bcca86215539a7d452588feb481f1c39554262)) +- pin all third party github actions ([74bcca8](https://github.com/mParticle/mparticle-android-sdk/commit/74bcca86215539a7d452588feb481f1c39554262)) ## [5.53.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.53.1...v5.53.2) (2023-10-16) - ### Updates & Maintenance -* Update submodules ([49a682d](https://github.com/mParticle/mparticle-android-sdk/commit/49a682daf437d3496253a1cf6bd5c73db739ecfa)) +- Update submodules ([49a682d](https://github.com/mParticle/mparticle-android-sdk/commit/49a682daf437d3496253a1cf6bd5c73db739ecfa)) ## [5.53.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.53.0...v5.53.1) (2023-09-07) - ### Updates & Maintenance -* Update submodules ([4c8a106](https://github.com/mParticle/mparticle-android-sdk/commit/4c8a106316590850bd463e5492cae4d959767a57)) +- Update submodules ([4c8a106](https://github.com/mParticle/mparticle-android-sdk/commit/4c8a106316590850bd463e5492cae4d959767a57)) ## [5.53.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.52.1...v5.53.0) (2023-08-01) - ### Features -* SQDSDKS-5543 formatting, clean-up and reorganizing imports ([#406](https://github.com/mParticle/mparticle-android-sdk/issues/406)) ([341118c](https://github.com/mParticle/mparticle-android-sdk/commit/341118ca1817d389e05a08e5c79e3c076267e112)) - +- SQDSDKS-5543 formatting, clean-up and reorganizing imports ([#406](https://github.com/mParticle/mparticle-android-sdk/issues/406)) ([341118c](https://github.com/mParticle/mparticle-android-sdk/commit/341118ca1817d389e05a08e5c79e3c076267e112)) ### Updates & Maintenance -* Update submodules ([13594c5](https://github.com/mParticle/mparticle-android-sdk/commit/13594c56cf77f62785302cfa17632ace3732e683)) +- Update submodules ([13594c5](https://github.com/mParticle/mparticle-android-sdk/commit/13594c56cf77f62785302cfa17632ace3732e683)) ## [5.52.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.52.0...v5.52.1) (2023-07-24) - ### Updates & Maintenance -* Update submodules ([11b4378](https://github.com/mParticle/mparticle-android-sdk/commit/11b437899c9a9549d30e2412557bff37f1b53317)) +- Update submodules ([11b4378](https://github.com/mParticle/mparticle-android-sdk/commit/11b437899c9a9549d30e2412557bff37f1b53317)) ## [5.52.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.51.6...v5.52.0) (2023-07-24) - ### Features -* sideloading kits ([#401](https://github.com/mParticle/mparticle-android-sdk/issues/401)) ([80de8ea](https://github.com/mParticle/mparticle-android-sdk/commit/80de8ea51253f73b04947c388d887b3ec4a05f6d)), closes [#378](https://github.com/mParticle/mparticle-android-sdk/issues/378) - +- sideloading kits ([#401](https://github.com/mParticle/mparticle-android-sdk/issues/401)) ([80de8ea](https://github.com/mParticle/mparticle-android-sdk/commit/80de8ea51253f73b04947c388d887b3ec4a05f6d)), closes [#378](https://github.com/mParticle/mparticle-android-sdk/issues/378) ### Updates & Maintenance -* Update submodules ([7d555ce](https://github.com/mParticle/mparticle-android-sdk/commit/7d555ce6e032d00a17b7c45a088c901a0ccb5592)) +- Update submodules ([7d555ce](https://github.com/mParticle/mparticle-android-sdk/commit/7d555ce6e032d00a17b7c45a088c901a0ccb5592)) ## [5.51.6](https://github.com/mParticle/mparticle-android-sdk/compare/v5.51.5...v5.51.6) (2023-07-20) - ### Updates & Maintenance -* Update submodules ([a2bcc3a](https://github.com/mParticle/mparticle-android-sdk/commit/a2bcc3a9415ad56e2f7bfcae89ae3d75f9d2916c)) +- Update submodules ([a2bcc3a](https://github.com/mParticle/mparticle-android-sdk/commit/a2bcc3a9415ad56e2f7bfcae89ae3d75f9d2916c)) ## [5.51.5](https://github.com/mParticle/mparticle-android-sdk/compare/v5.51.4...v5.51.5) (2023-07-11) - ### Updates & Maintenance -* Update submodules ([4465359](https://github.com/mParticle/mparticle-android-sdk/commit/4465359deb062530fe513963deead6cc99c0426d)) +- Update submodules ([4465359](https://github.com/mParticle/mparticle-android-sdk/commit/4465359deb062530fe513963deead6cc99c0426d)) ## [5.51.4](https://github.com/mParticle/mparticle-android-sdk/compare/v5.51.3...v5.51.4) (2023-07-05) - ### Bug Fixes -* Kit Initialization & De-Initialization. ([#398](https://github.com/mParticle/mparticle-android-sdk/issues/398)) ([42560f1](https://github.com/mParticle/mparticle-android-sdk/commit/42560f153b7d5636dbbb5a8ef01040514ddccc8d)) +- Kit Initialization & De-Initialization. ([#398](https://github.com/mParticle/mparticle-android-sdk/issues/398)) ([42560f1](https://github.com/mParticle/mparticle-android-sdk/commit/42560f153b7d5636dbbb5a8ef01040514ddccc8d)) ## [5.51.3](https://github.com/mParticle/mparticle-android-sdk/compare/v5.51.2...v5.51.3) (2023-06-28) - ### Bug Fixes -* Fixing initialization & de-initialization issue on kits. ([#393](https://github.com/mParticle/mparticle-android-sdk/issues/393)) ([d02b5b3](https://github.com/mParticle/mparticle-android-sdk/commit/d02b5b37eb4863aa7b475c4117a4db691a324614)) -* Kit integration forwarding unplanned/blocked events when fired early on app run ([#394](https://github.com/mParticle/mparticle-android-sdk/issues/394)) ([b99a1c6](https://github.com/mParticle/mparticle-android-sdk/commit/b99a1c6b961e18693808a18368c01572b3b4831e)) - +- Fixing initialization & de-initialization issue on kits. ([#393](https://github.com/mParticle/mparticle-android-sdk/issues/393)) ([d02b5b3](https://github.com/mParticle/mparticle-android-sdk/commit/d02b5b37eb4863aa7b475c4117a4db691a324614)) +- Kit integration forwarding unplanned/blocked events when fired early on app run ([#394](https://github.com/mParticle/mparticle-android-sdk/issues/394)) ([b99a1c6](https://github.com/mParticle/mparticle-android-sdk/commit/b99a1c6b961e18693808a18368c01572b3b4831e)) ### Updates & Maintenance -* Update submodules ([1ba89e3](https://github.com/mParticle/mparticle-android-sdk/commit/1ba89e3006c35ea259c338fde022235fa2db4846)) +- Update submodules ([1ba89e3](https://github.com/mParticle/mparticle-android-sdk/commit/1ba89e3006c35ea259c338fde022235fa2db4846)) ## [5.51.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.51.1...v5.51.2) (2023-06-21) - ### Updates & Maintenance -* Update submodules ([bfd28bc](https://github.com/mParticle/mparticle-android-sdk/commit/bfd28bc245af308e05bf28a046de7f979de889ae)) +- Update submodules ([bfd28bc](https://github.com/mParticle/mparticle-android-sdk/commit/bfd28bc245af308e05bf28a046de7f979de889ae)) ## [5.51.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.51.0...v5.51.1) (2023-06-13) - ### Updates & Maintenance -* Update submodules ([3aabaae](https://github.com/mParticle/mparticle-android-sdk/commit/3aabaae963030555440d40272e22e09a290fb963)) +- Update submodules ([3aabaae](https://github.com/mParticle/mparticle-android-sdk/commit/3aabaae963030555440d40272e22e09a290fb963)) ## [5.51.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.50.4...v5.51.0) (2023-06-05) - ### Features -* cache AVD for faster connected test runs ([#319](https://github.com/mParticle/mparticle-android-sdk/issues/319)) ([c24d38d](https://github.com/mParticle/mparticle-android-sdk/commit/c24d38d766b34421bf42d90105c5064521857183)) - +- cache AVD for faster connected test runs ([#319](https://github.com/mParticle/mparticle-android-sdk/issues/319)) ([c24d38d](https://github.com/mParticle/mparticle-android-sdk/commit/c24d38d766b34421bf42d90105c5064521857183)) ### Bug Fixes -* SQDSDKS-5287 unable to drop batches nullability ([#379](https://github.com/mParticle/mparticle-android-sdk/issues/379)) ([04af4e9](https://github.com/mParticle/mparticle-android-sdk/commit/04af4e932ea0b575df745d36c64a7fb0305dc2a8)) - +- SQDSDKS-5287 unable to drop batches nullability ([#379](https://github.com/mParticle/mparticle-android-sdk/issues/379)) ([04af4e9](https://github.com/mParticle/mparticle-android-sdk/commit/04af4e932ea0b575df745d36c64a7fb0305dc2a8)) ### Updates & Maintenance -* Update submodules ([03289e1](https://github.com/mParticle/mparticle-android-sdk/commit/03289e14e72b87f1e57b192152ad1dfcc1bf8608)) +- Update submodules ([03289e1](https://github.com/mParticle/mparticle-android-sdk/commit/03289e14e72b87f1e57b192152ad1dfcc1bf8608)) ## [5.50.4](https://github.com/mParticle/mparticle-android-sdk/compare/v5.50.3...v5.50.4) (2023-05-03) - ### Updates & Maintenance -* Update submodules ([9ed4e70](https://github.com/mParticle/mparticle-android-sdk/commit/9ed4e70d77aba4ada08d9a8b715b2115b75a7341)) +- Update submodules ([9ed4e70](https://github.com/mParticle/mparticle-android-sdk/commit/9ed4e70d77aba4ada08d9a8b715b2115b75a7341)) ## [5.50.3](https://github.com/mParticle/mparticle-android-sdk/compare/v5.50.2...v5.50.3) (2023-03-31) - ### Updates & Maintenance -* Update submodules ([4e5e921](https://github.com/mParticle/mparticle-android-sdk/commit/4e5e921ff9a80dd2a1f0ad9615ebbf052029ecb4)) +- Update submodules ([4e5e921](https://github.com/mParticle/mparticle-android-sdk/commit/4e5e921ff9a80dd2a1f0ad9615ebbf052029ecb4)) ## [5.50.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.50.1...v5.50.2) (2023-03-30) - ### Updates & Maintenance -* Update submodules ([d036eb8](https://github.com/mParticle/mparticle-android-sdk/commit/d036eb821519d2afd60eadede46cc3a6a6abbbbe)) +- Update submodules ([d036eb8](https://github.com/mParticle/mparticle-android-sdk/commit/d036eb821519d2afd60eadede46cc3a6a6abbbbe)) ## [5.50.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.50.0...v5.50.1) (2023-03-24) - ### Updates & Maintenance -* Update submodules ([474b192](https://github.com/mParticle/mparticle-android-sdk/commit/474b1924162433ec8d3a48102688b131b0268dd9)) +- Update submodules ([474b192](https://github.com/mParticle/mparticle-android-sdk/commit/474b1924162433ec8d3a48102688b131b0268dd9)) ## [5.50.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.49.2...v5.50.0) (2023-02-28) - ### Features -* Fixing dependabot automerged dependencies ([#331](https://github.com/mParticle/mparticle-android-sdk/issues/331)) ([#334](https://github.com/mParticle/mparticle-android-sdk/issues/334)) ([33f29a6](https://github.com/mParticle/mparticle-android-sdk/commit/33f29a6056a3b9954a42ea068c786ae6aac9cdd5)) - +- Fixing dependabot automerged dependencies ([#331](https://github.com/mParticle/mparticle-android-sdk/issues/331)) ([#334](https://github.com/mParticle/mparticle-android-sdk/issues/334)) ([33f29a6](https://github.com/mParticle/mparticle-android-sdk/commit/33f29a6056a3b9954a42ea068c786ae6aac9cdd5)) ### Updates & Maintenance -* Update submodules ([312800e](https://github.com/mParticle/mparticle-android-sdk/commit/312800edd6a7587f017dd73f4242031ea53b6b80)) +- Update submodules ([312800e](https://github.com/mParticle/mparticle-android-sdk/commit/312800edd6a7587f017dd73f4242031ea53b6b80)) ## [5.49.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.49.1...v5.49.2) (2023-02-14) - ### Updates & Maintenance -* Update submodules ([598dd69](https://github.com/mParticle/mparticle-android-sdk/commit/598dd69af7c546a790c6155d3731626d56f9e260)) +- Update submodules ([598dd69](https://github.com/mParticle/mparticle-android-sdk/commit/598dd69af7c546a790c6155d3731626d56f9e260)) ## [5.49.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.49.0...v5.49.1) (2023-02-10) - ### Bug Fixes -* Removing flaky tests ([#317](https://github.com/mParticle/mparticle-android-sdk/issues/317)) ([b937fbb](https://github.com/mParticle/mparticle-android-sdk/commit/b937fbb890691974356879ae9ee39e717cd1e67e)), closes [#311](https://github.com/mParticle/mparticle-android-sdk/issues/311) - +- Removing flaky tests ([#317](https://github.com/mParticle/mparticle-android-sdk/issues/317)) ([b937fbb](https://github.com/mParticle/mparticle-android-sdk/commit/b937fbb890691974356879ae9ee39e717cd1e67e)), closes [#311](https://github.com/mParticle/mparticle-android-sdk/issues/311) ### Updates & Maintenance -* Update submodules ([6d51f18](https://github.com/mParticle/mparticle-android-sdk/commit/6d51f18d27cd13d1cb3131c39821cc1c293262c4)) +- Update submodules ([6d51f18](https://github.com/mParticle/mparticle-android-sdk/commit/6d51f18d27cd13d1cb3131c39821cc1c293262c4)) ## [5.49.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.48.4...v5.49.0) (2023-01-05) - ### Features -* Adding method to change update interval after initialization ([#301](https://github.com/mParticle/mparticle-android-sdk/issues/301)) ([e23ad37](https://github.com/mParticle/mparticle-android-sdk/commit/e23ad37a70e175ad574dc1391377478e0a5a9408)) -* Adding WrapperSdk, WrapperSdkVersion - adding this values to MParticleOptions and MParticle ([#295](https://github.com/mParticle/mparticle-android-sdk/issues/295)) ([fe27e48](https://github.com/mParticle/mparticle-android-sdk/commit/fe27e4872adca4ff4766e1a2372a9259a8ed0b3c)) - +- Adding method to change update interval after initialization ([#301](https://github.com/mParticle/mparticle-android-sdk/issues/301)) ([e23ad37](https://github.com/mParticle/mparticle-android-sdk/commit/e23ad37a70e175ad574dc1391377478e0a5a9408)) +- Adding WrapperSdk, WrapperSdkVersion - adding this values to MParticleOptions and MParticle ([#295](https://github.com/mParticle/mparticle-android-sdk/issues/295)) ([fe27e48](https://github.com/mParticle/mparticle-android-sdk/commit/fe27e4872adca4ff4766e1a2372a9259a8ed0b3c)) ### Updates & Maintenance -* Add semgrep, mobsf static analysis ([#289](https://github.com/mParticle/mparticle-android-sdk/issues/289)) ([aab45d0](https://github.com/mParticle/mparticle-android-sdk/commit/aab45d0c33f8c47324f4d472d2aad16b917611fc)) -* Update PULL_REQUEST_TEMPLATE.md ([#293](https://github.com/mParticle/mparticle-android-sdk/issues/293)) ([b54c6bd](https://github.com/mParticle/mparticle-android-sdk/commit/b54c6bd5e466063515187a73c8c16a95efc0a11c)) -* Update submodules ([f682db7](https://github.com/mParticle/mparticle-android-sdk/commit/f682db7377a6f1ff117748f48c0979a930c669f9)) +- Add semgrep, mobsf static analysis ([#289](https://github.com/mParticle/mparticle-android-sdk/issues/289)) ([aab45d0](https://github.com/mParticle/mparticle-android-sdk/commit/aab45d0c33f8c47324f4d472d2aad16b917611fc)) +- Update PULL_REQUEST_TEMPLATE.md ([#293](https://github.com/mParticle/mparticle-android-sdk/issues/293)) ([b54c6bd](https://github.com/mParticle/mparticle-android-sdk/commit/b54c6bd5e466063515187a73c8c16a95efc0a11c)) +- Update submodules ([f682db7](https://github.com/mParticle/mparticle-android-sdk/commit/f682db7377a6f1ff117748f48c0979a930c669f9)) ## [5.48.4](https://github.com/mParticle/mparticle-android-sdk/compare/v5.48.3...v5.48.4) (2022-12-08) - ### Updates & Maintenance -* Update submodules ([28cbb35](https://github.com/mParticle/mparticle-android-sdk/commit/28cbb350b2df8d4e04592e1f3997ab83b5078d8a)) +- Update submodules ([28cbb35](https://github.com/mParticle/mparticle-android-sdk/commit/28cbb350b2df8d4e04592e1f3997ab83b5078d8a)) ## [5.48.3](https://github.com/mParticle/mparticle-android-sdk/compare/v5.48.2...v5.48.3) (2022-12-02) - ### Bug Fixes -* Error handle null user attribute better and add use case to test file ([#290](https://github.com/mParticle/mparticle-android-sdk/issues/290)) ([8412478](https://github.com/mParticle/mparticle-android-sdk/commit/8412478cd8d701c8056ad7f39b346534e6da4dc2)) -* Error handle null user attribute value ([#288](https://github.com/mParticle/mparticle-android-sdk/issues/288)) ([73872df](https://github.com/mParticle/mparticle-android-sdk/commit/73872dff61c6994d233ce40cb362af1c7a049c7a)) - +- Error handle null user attribute better and add use case to test file ([#290](https://github.com/mParticle/mparticle-android-sdk/issues/290)) ([8412478](https://github.com/mParticle/mparticle-android-sdk/commit/8412478cd8d701c8056ad7f39b346534e6da4dc2)) +- Error handle null user attribute value ([#288](https://github.com/mParticle/mparticle-android-sdk/issues/288)) ([73872df](https://github.com/mParticle/mparticle-android-sdk/commit/73872dff61c6994d233ce40cb362af1c7a049c7a)) ### Updates & Maintenance -* Add in ktlintCheck to daily cron job ([#284](https://github.com/mParticle/mparticle-android-sdk/issues/284)) ([1d23a5f](https://github.com/mParticle/mparticle-android-sdk/commit/1d23a5fa75a1aa8410260faf9f1cb9b6d6041f57)) -* Update submodules ([375b0d3](https://github.com/mParticle/mparticle-android-sdk/commit/375b0d364d3b739b22d0ce1dd0d3322f9b5e0fcd)) +- Add in ktlintCheck to daily cron job ([#284](https://github.com/mParticle/mparticle-android-sdk/issues/284)) ([1d23a5f](https://github.com/mParticle/mparticle-android-sdk/commit/1d23a5fa75a1aa8410260faf9f1cb9b6d6041f57)) +- Update submodules ([375b0d3](https://github.com/mParticle/mparticle-android-sdk/commit/375b0d364d3b739b22d0ce1dd0d3322f9b5e0fcd)) ## [5.48.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.48.1...v5.48.2) (2022-11-18) - ### Updates & Maintenance -* Update submodules ([bc03c8e](https://github.com/mParticle/mparticle-android-sdk/commit/bc03c8e656973404ebe353e9bbdc2de57309dd10)) +- Update submodules ([bc03c8e](https://github.com/mParticle/mparticle-android-sdk/commit/bc03c8e656973404ebe353e9bbdc2de57309dd10)) ## [5.48.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.48.0...v5.48.1) (2022-11-10) - ### Updates & Maintenance -* Fix sonarcloud job for forked repos ([#268](https://github.com/mParticle/mparticle-android-sdk/issues/268)) ([cf79eb7](https://github.com/mParticle/mparticle-android-sdk/commit/cf79eb7592c289ab724135b130b70157295cda7f)) -* Update submodules ([1eff17c](https://github.com/mParticle/mparticle-android-sdk/commit/1eff17c3940aeabb28e51d67493069267db9d978)) +- Fix sonarcloud job for forked repos ([#268](https://github.com/mParticle/mparticle-android-sdk/issues/268)) ([cf79eb7](https://github.com/mParticle/mparticle-android-sdk/commit/cf79eb7592c289ab724135b130b70157295cda7f)) +- Update submodules ([1eff17c](https://github.com/mParticle/mparticle-android-sdk/commit/1eff17c3940aeabb28e51d67493069267db9d978)) ## [5.48.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.47.4...v5.48.0) (2022-11-03) - ### Features -* Investigate dependabot automerge Mockito library upgrade. ([#264](https://github.com/mParticle/mparticle-android-sdk/issues/264)) ([982bf29](https://github.com/mParticle/mparticle-android-sdk/commit/982bf299283608f5c7987bea28d5b9da2844d1d5)) - +- Investigate dependabot automerge Mockito library upgrade. ([#264](https://github.com/mParticle/mparticle-android-sdk/issues/264)) ([982bf29](https://github.com/mParticle/mparticle-android-sdk/commit/982bf299283608f5c7987bea28d5b9da2844d1d5)) ### Bug Fixes -* mParticle crashing on push notifications for android 12 and above ([#266](https://github.com/mParticle/mparticle-android-sdk/issues/266)) ([88ddb94](https://github.com/mParticle/mparticle-android-sdk/commit/88ddb9415d5f240482540c0c0b3e26b818838d96)) - +- mParticle crashing on push notifications for android 12 and above ([#266](https://github.com/mParticle/mparticle-android-sdk/issues/266)) ([88ddb94](https://github.com/mParticle/mparticle-android-sdk/commit/88ddb9415d5f240482540c0c0b3e26b818838d96)) ### Updates & Maintenance -* Update submodules ([4ffafcf](https://github.com/mParticle/mparticle-android-sdk/commit/4ffafcf4fa1c94811fd4f498bb3c0237363f61a8)) +- Update submodules ([4ffafcf](https://github.com/mParticle/mparticle-android-sdk/commit/4ffafcf4fa1c94811fd4f498bb3c0237363f61a8)) ## [5.47.4](https://github.com/mParticle/mparticle-android-sdk/compare/v5.47.3...v5.47.4) (2022-11-02) - ### Updates & Maintenance -* Update submodules ([268e611](https://github.com/mParticle/mparticle-android-sdk/commit/268e611eaa1f8648617a6495bc385d52ff8db7b3)) +- Update submodules ([268e611](https://github.com/mParticle/mparticle-android-sdk/commit/268e611eaa1f8648617a6495bc385d52ff8db7b3)) ## [5.47.3](https://github.com/mParticle/mparticle-android-sdk/compare/v5.47.2...v5.47.3) (2022-10-26) - ### Updates & Maintenance -* Update submodules ([5dffb61](https://github.com/mParticle/mparticle-android-sdk/commit/5dffb613a4e690fbd7f649c075c7f49c8fc77641)) +- Update submodules ([5dffb61](https://github.com/mParticle/mparticle-android-sdk/commit/5dffb613a4e690fbd7f649c075c7f49c8fc77641)) ## [5.47.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.47.1...v5.47.2) (2022-10-24) - ### Updates & Maintenance -* Update submodules ([9b98f0b](https://github.com/mParticle/mparticle-android-sdk/commit/9b98f0b93224e624bfe8df773cf19b9a2914f76f)) +- Update submodules ([9b98f0b](https://github.com/mParticle/mparticle-android-sdk/commit/9b98f0b93224e624bfe8df773cf19b9a2914f76f)) ## [5.47.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.47.0...v5.47.1) (2022-10-19) - ### Updates & Maintenance -* add security-hardcoded-secrets job ([#260](https://github.com/mParticle/mparticle-android-sdk/issues/260)) ([c8ec3fe](https://github.com/mParticle/mparticle-android-sdk/commit/c8ec3fe2deeed99ddc09d3e2dfdd041b93c5965b)) +- add security-hardcoded-secrets job ([#260](https://github.com/mParticle/mparticle-android-sdk/issues/260)) ([c8ec3fe](https://github.com/mParticle/mparticle-android-sdk/commit/c8ec3fe2deeed99ddc09d3e2dfdd041b93c5965b)) ## [5.47.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.46.0...v5.47.0) (2022-10-18) - ### Features -* Port android core module java instrumented and unit tests to kotlin (phase 3) ([#257](https://github.com/mParticle/mparticle-android-sdk/issues/257)) ([e8cb3db](https://github.com/mParticle/mparticle-android-sdk/commit/e8cb3db906b3b38c52a9533eecd6b20c3672fd2c)) - +- Port android core module java instrumented and unit tests to kotlin (phase 3) ([#257](https://github.com/mParticle/mparticle-android-sdk/issues/257)) ([e8cb3db](https://github.com/mParticle/mparticle-android-sdk/commit/e8cb3db906b3b38c52a9533eecd6b20c3672fd2c)) ### Updates & Maintenance -* Update github actions that are deprecated ([#258](https://github.com/mParticle/mparticle-android-sdk/issues/258)) ([db13ae0](https://github.com/mParticle/mparticle-android-sdk/commit/db13ae02dbbd971c781cc1a40cdaba06486e3799)) -* Update submodules ([9f0524f](https://github.com/mParticle/mparticle-android-sdk/commit/9f0524f988674c4b781c9b0f80d04d2f129ee1be)) +- Update github actions that are deprecated ([#258](https://github.com/mParticle/mparticle-android-sdk/issues/258)) ([db13ae0](https://github.com/mParticle/mparticle-android-sdk/commit/db13ae02dbbd971c781cc1a40cdaba06486e3799)) +- Update submodules ([9f0524f](https://github.com/mParticle/mparticle-android-sdk/commit/9f0524f988674c4b781c9b0f80d04d2f129ee1be)) ## [5.46.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.45.2...v5.46.0) (2022-10-14) - ### Features -* Bump up compile SDK to 33 and ktlint version ([#245](https://github.com/mParticle/mparticle-android-sdk/issues/245)) ([67dc378](https://github.com/mParticle/mparticle-android-sdk/commit/67dc378ae98a97a6b9c8cf5545125c14ceffcdb5)) -* Port android core module java instrumented and unit tests to kotlin - phase1 ([#249](https://github.com/mParticle/mparticle-android-sdk/issues/249)) ([62e4254](https://github.com/mParticle/mparticle-android-sdk/commit/62e42545d73ae2c9b8e50d54f3dbedfd9dd1b431)) -* Port android core module java instrumented and unit tests to kotlin (p2) ([#250](https://github.com/mParticle/mparticle-android-sdk/issues/250)) ([23434d2](https://github.com/mParticle/mparticle-android-sdk/commit/23434d2a4918ef58a7872401f8602c84b177610d)) -* Ported Android Kit Base tests to Kotlin ([#253](https://github.com/mParticle/mparticle-android-sdk/issues/253)) ([c21dd71](https://github.com/mParticle/mparticle-android-sdk/commit/c21dd71405e56ff48ac6db3455899588243133c6)) -* update isLimitAdTracking logic for Android 13 ([#233](https://github.com/mParticle/mparticle-android-sdk/issues/233)) ([f7b9284](https://github.com/mParticle/mparticle-android-sdk/commit/f7b92845dd0eebe236d1aa836d50161f8bce82f8)) - +- Bump up compile SDK to 33 and ktlint version ([#245](https://github.com/mParticle/mparticle-android-sdk/issues/245)) ([67dc378](https://github.com/mParticle/mparticle-android-sdk/commit/67dc378ae98a97a6b9c8cf5545125c14ceffcdb5)) +- Port android core module java instrumented and unit tests to kotlin - phase1 ([#249](https://github.com/mParticle/mparticle-android-sdk/issues/249)) ([62e4254](https://github.com/mParticle/mparticle-android-sdk/commit/62e42545d73ae2c9b8e50d54f3dbedfd9dd1b431)) +- Port android core module java instrumented and unit tests to kotlin (p2) ([#250](https://github.com/mParticle/mparticle-android-sdk/issues/250)) ([23434d2](https://github.com/mParticle/mparticle-android-sdk/commit/23434d2a4918ef58a7872401f8602c84b177610d)) +- Ported Android Kit Base tests to Kotlin ([#253](https://github.com/mParticle/mparticle-android-sdk/issues/253)) ([c21dd71](https://github.com/mParticle/mparticle-android-sdk/commit/c21dd71405e56ff48ac6db3455899588243133c6)) +- update isLimitAdTracking logic for Android 13 ([#233](https://github.com/mParticle/mparticle-android-sdk/issues/233)) ([f7b9284](https://github.com/mParticle/mparticle-android-sdk/commit/f7b92845dd0eebe236d1aa836d50161f8bce82f8)) ### Bug Fixes -* Convert MParticleTest.java file to kotlin and fix failing test ([#251](https://github.com/mParticle/mparticle-android-sdk/issues/251)) ([604c1b9](https://github.com/mParticle/mparticle-android-sdk/commit/604c1b976e753a282bf0173b559f0427c144fe47)) - +- Convert MParticleTest.java file to kotlin and fix failing test ([#251](https://github.com/mParticle/mparticle-android-sdk/issues/251)) ([604c1b9](https://github.com/mParticle/mparticle-android-sdk/commit/604c1b976e753a282bf0173b559f0427c144fe47)) ### Documentation -* Update copy in readme for android 13 ([#255](https://github.com/mParticle/mparticle-android-sdk/issues/255)) ([c9a648d](https://github.com/mParticle/mparticle-android-sdk/commit/c9a648d87eb5b6586a6693b75ffa54fe711b02f2)) - +- Update copy in readme for android 13 ([#255](https://github.com/mParticle/mparticle-android-sdk/issues/255)) ([c9a648d](https://github.com/mParticle/mparticle-android-sdk/commit/c9a648d87eb5b6586a6693b75ffa54fe711b02f2)) ### Updates & Maintenance -* add in missing inherit in rebase job ([2197610](https://github.com/mParticle/mparticle-android-sdk/commit/2197610fe1381d941f3f6b5f99afc64965decc52)) -* Update submodules ([7bdaf63](https://github.com/mParticle/mparticle-android-sdk/commit/7bdaf63c9444c78ed1063b7039179cfdd645a506)) -* Update to kotlin 1.7.20 ([#247](https://github.com/mParticle/mparticle-android-sdk/issues/247)) ([c9e1729](https://github.com/mParticle/mparticle-android-sdk/commit/c9e1729b6ab8817e4c7b0661ae25b3ffb6df4404)) +- add in missing inherit in rebase job ([2197610](https://github.com/mParticle/mparticle-android-sdk/commit/2197610fe1381d941f3f6b5f99afc64965decc52)) +- Update submodules ([7bdaf63](https://github.com/mParticle/mparticle-android-sdk/commit/7bdaf63c9444c78ed1063b7039179cfdd645a506)) +- Update to kotlin 1.7.20 ([#247](https://github.com/mParticle/mparticle-android-sdk/issues/247)) ([c9e1729](https://github.com/mParticle/mparticle-android-sdk/commit/c9e1729b6ab8817e4c7b0661ae25b3ffb6df4404)) ## [5.45.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.45.1...v5.45.2) (2022-09-26) - ### Updates & Maintenance -* add in missing GPG step for updating submodules ([#238](https://github.com/mParticle/mparticle-android-sdk/issues/238)) ([ac9ee19](https://github.com/mParticle/mparticle-android-sdk/commit/ac9ee19a1f29a56f974ecce060a189be3a8f1d2e)) -* Update submodules ([cf4d2e0](https://github.com/mParticle/mparticle-android-sdk/commit/cf4d2e0903445db4481f3489e8936dee933ea72c)) +- add in missing GPG step for updating submodules ([#238](https://github.com/mParticle/mparticle-android-sdk/issues/238)) ([ac9ee19](https://github.com/mParticle/mparticle-android-sdk/commit/ac9ee19a1f29a56f974ecce060a189be3a8f1d2e)) +- Update submodules ([cf4d2e0](https://github.com/mParticle/mparticle-android-sdk/commit/cf4d2e0903445db4481f3489e8936dee933ea72c)) ## [5.45.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.45.0...v5.45.1) (2022-09-14) - ### Updates & Maintenance -* Update Submodules ([ad2f423](https://github.com/mParticle/mparticle-android-sdk/commit/ad2f42377a2db2b302f2d72ea6f73c7166b577bc)) +- Update Submodules ([ad2f423](https://github.com/mParticle/mparticle-android-sdk/commit/ad2f42377a2db2b302f2d72ea6f73c7166b577bc)) ## [5.45.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.44.2...v5.45.0) (2022-09-08) - ### Features -* update dependencies for Android 13 (from dependabot) ([#234](https://github.com/mParticle/mparticle-android-sdk/issues/234)) ([4416a2d](https://github.com/mParticle/mparticle-android-sdk/commit/4416a2d898d06079f5553f91aae64bbbadfba158)) - +- update dependencies for Android 13 (from dependabot) ([#234](https://github.com/mParticle/mparticle-android-sdk/issues/234)) ([4416a2d](https://github.com/mParticle/mparticle-android-sdk/commit/4416a2d898d06079f5553f91aae64bbbadfba158)) ### Updates & Maintenance -* Update Submodules ([690f555](https://github.com/mParticle/mparticle-android-sdk/commit/690f555a0e8c0e332a62cdfd7b2987308f165fa8)) +- Update Submodules ([690f555](https://github.com/mParticle/mparticle-android-sdk/commit/690f555a0e8c0e332a62cdfd7b2987308f165fa8)) ## [5.44.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.44.1...v5.44.2) (2022-08-19) - ### Updates & Maintenance -* Update Submodules ([187bdc0](https://github.com/mParticle/mparticle-android-sdk/commit/187bdc01d0e9446e7c1eecc49dc951000a7c8602)) +- Update Submodules ([187bdc0](https://github.com/mParticle/mparticle-android-sdk/commit/187bdc01d0e9446e7c1eecc49dc951000a7c8602)) ## [5.44.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.44.0...v5.44.1) (2022-08-10) - ### Bug Fixes -* add needs statement and upgrade VMs ([#214](https://github.com/mParticle/mparticle-android-sdk/issues/214)) ([4c0c0db](https://github.com/mParticle/mparticle-android-sdk/commit/4c0c0db401e0dba40e04e99222fdd23e5fe64d1d)) - +- add needs statement and upgrade VMs ([#214](https://github.com/mParticle/mparticle-android-sdk/issues/214)) ([4c0c0db](https://github.com/mParticle/mparticle-android-sdk/commit/4c0c0db401e0dba40e04e99222fdd23e5fe64d1d)) ### Updates & Maintenance -* Update Submodules ([765a711](https://github.com/mParticle/mparticle-android-sdk/commit/765a7112d92ff122f29666a36e62a96dd7b120c1)) +- Update Submodules ([765a711](https://github.com/mParticle/mparticle-android-sdk/commit/765a7112d92ff122f29666a36e62a96dd7b120c1)) ## [5.44.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.43.0...v5.44.0) (2022-08-01) - ### Features -* update sonarcloud check to new format ([#209](https://github.com/mParticle/mparticle-android-sdk/issues/209)) ([821d61e](https://github.com/mParticle/mparticle-android-sdk/commit/821d61e9be81d1645a044ba9c0c63da070643104)) - +- update sonarcloud check to new format ([#209](https://github.com/mParticle/mparticle-android-sdk/issues/209)) ([821d61e](https://github.com/mParticle/mparticle-android-sdk/commit/821d61e9be81d1645a044ba9c0c63da070643104)) ### Bug Fixes -* reset logic, fixing orchestrator ([#213](https://github.com/mParticle/mparticle-android-sdk/issues/213)) ([f9379e9](https://github.com/mParticle/mparticle-android-sdk/commit/f9379e9597b0dc0ff5fc570f066c293675b511c6)) - +- reset logic, fixing orchestrator ([#213](https://github.com/mParticle/mparticle-android-sdk/issues/213)) ([f9379e9](https://github.com/mParticle/mparticle-android-sdk/commit/f9379e9597b0dc0ff5fc570f066c293675b511c6)) ### Updates & Maintenance -* Update Submodules ([7c9be34](https://github.com/mParticle/mparticle-android-sdk/commit/7c9be34f702f5ab96685fa2fc34454bcb0bac8db)) -* update visibility for crossplatform testing ([#211](https://github.com/mParticle/mparticle-android-sdk/issues/211)) ([b03f210](https://github.com/mParticle/mparticle-android-sdk/commit/b03f210c81f6b38a1b8cc3999d180d38b54857cd)) +- Update Submodules ([7c9be34](https://github.com/mParticle/mparticle-android-sdk/commit/7c9be34f702f5ab96685fa2fc34454bcb0bac8db)) +- update visibility for crossplatform testing ([#211](https://github.com/mParticle/mparticle-android-sdk/issues/211)) ([b03f210](https://github.com/mParticle/mparticle-android-sdk/commit/b03f210c81f6b38a1b8cc3999d180d38b54857cd)) ## [5.43.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.42.0...v5.43.0) (2022-07-21) - ### Features -* update MParticleUser.incrementUserAttribute to accept Number ([#188](https://github.com/mParticle/mparticle-android-sdk/issues/188)) ([670bdd6](https://github.com/mParticle/mparticle-android-sdk/commit/670bdd60084b7b1fa2652d4bdb4f492f928f91a9)) +- update MParticleUser.incrementUserAttribute to accept Number ([#188](https://github.com/mParticle/mparticle-android-sdk/issues/188)) ([670bdd6](https://github.com/mParticle/mparticle-android-sdk/commit/670bdd60084b7b1fa2652d4bdb4f492f928f91a9)) ## [5.42.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.41.3...v5.42.0) (2022-07-18) - ### Features -* upgrade sonarqube to 3.4 and kotlin to 1.7.10 ([#203](https://github.com/mParticle/mparticle-android-sdk/issues/203)) ([699ae9e](https://github.com/mParticle/mparticle-android-sdk/commit/699ae9e310ce9b033fc9bee0f1583d083ab60e40)) - +- upgrade sonarqube to 3.4 and kotlin to 1.7.10 ([#203](https://github.com/mParticle/mparticle-android-sdk/issues/203)) ([699ae9e](https://github.com/mParticle/mparticle-android-sdk/commit/699ae9e310ce9b033fc9bee0f1583d083ab60e40)) ### Updates & Maintenance -* Update Submodules ([27a68d1](https://github.com/mParticle/mparticle-android-sdk/commit/27a68d18f80d83a7a975a021585a47959aa552b8)) +- Update Submodules ([27a68d1](https://github.com/mParticle/mparticle-android-sdk/commit/27a68d18f80d83a7a975a021585a47959aa552b8)) ## [5.41.3](https://github.com/mParticle/mparticle-android-sdk/compare/v5.41.2...v5.41.3) (2022-07-01) - ### Bug Fixes -* config migration logic causes kits to deinit on re-upgrade ([#196](https://github.com/mParticle/mparticle-android-sdk/issues/196)) ([ae210c4](https://github.com/mParticle/mparticle-android-sdk/commit/ae210c48cae363fc1d5c3ee2a4e132795e3b333c)) -* modify() call throws an exception when user is not present ([#195](https://github.com/mParticle/mparticle-android-sdk/issues/195)) ([72731d5](https://github.com/mParticle/mparticle-android-sdk/commit/72731d5da3597a3298d113a5ecc427cd773f51cd)) - +- config migration logic causes kits to deinit on re-upgrade ([#196](https://github.com/mParticle/mparticle-android-sdk/issues/196)) ([ae210c4](https://github.com/mParticle/mparticle-android-sdk/commit/ae210c48cae363fc1d5c3ee2a4e132795e3b333c)) +- modify() call throws an exception when user is not present ([#195](https://github.com/mParticle/mparticle-android-sdk/issues/195)) ([72731d5](https://github.com/mParticle/mparticle-android-sdk/commit/72731d5da3597a3298d113a5ecc427cd773f51cd)) ### Updates & Maintenance -* Update Submodules ([99fed27](https://github.com/mParticle/mparticle-android-sdk/commit/99fed275ce272535a8891e179996c305c6999dc2)) +- Update Submodules ([99fed27](https://github.com/mParticle/mparticle-android-sdk/commit/99fed275ce272535a8891e179996c305c6999dc2)) ## [5.41.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.41.1...v5.41.2) (2022-06-27) - ### Bug Fixes -* clean up dependabot step ([#186](https://github.com/mParticle/mparticle-android-sdk/issues/186)) ([e9d5c30](https://github.com/mParticle/mparticle-android-sdk/commit/e9d5c30a4ef4f383c603bf05ceab8bafb6f3dd6e)) -* retain the original attribute value type when forwarded to kits ([#189](https://github.com/mParticle/mparticle-android-sdk/issues/189)) ([acb6ec4](https://github.com/mParticle/mparticle-android-sdk/commit/acb6ec48b03f1bb8630d23b4473376877d6eb17e)) -* update dependabot token for pull_request ([#181](https://github.com/mParticle/mparticle-android-sdk/issues/181)) ([96b76b5](https://github.com/mParticle/mparticle-android-sdk/commit/96b76b5bc3e7a69360e4949a1f211259c7964e90)) - +- clean up dependabot step ([#186](https://github.com/mParticle/mparticle-android-sdk/issues/186)) ([e9d5c30](https://github.com/mParticle/mparticle-android-sdk/commit/e9d5c30a4ef4f383c603bf05ceab8bafb6f3dd6e)) +- retain the original attribute value type when forwarded to kits ([#189](https://github.com/mParticle/mparticle-android-sdk/issues/189)) ([acb6ec4](https://github.com/mParticle/mparticle-android-sdk/commit/acb6ec48b03f1bb8630d23b4473376877d6eb17e)) +- update dependabot token for pull_request ([#181](https://github.com/mParticle/mparticle-android-sdk/issues/181)) ([96b76b5](https://github.com/mParticle/mparticle-android-sdk/commit/96b76b5bc3e7a69360e4949a1f211259c7964e90)) ### Documentation -* Create onboarding.md file in android sdk repo ([#180](https://github.com/mParticle/mparticle-android-sdk/issues/180)) ([1a6f715](https://github.com/mParticle/mparticle-android-sdk/commit/1a6f715f076603c75f30f45c5792ab4613715672)) - +- Create onboarding.md file in android sdk repo ([#180](https://github.com/mParticle/mparticle-android-sdk/issues/180)) ([1a6f715](https://github.com/mParticle/mparticle-android-sdk/commit/1a6f715f076603c75f30f45c5792ab4613715672)) ### Updates & Maintenance -* Update Submodules ([874f6ee](https://github.com/mParticle/mparticle-android-sdk/commit/874f6ee0eec33e41a33bb7cb9ce2c53134f04345)) +- Update Submodules ([874f6ee](https://github.com/mParticle/mparticle-android-sdk/commit/874f6ee0eec33e41a33bb7cb9ce2c53134f04345)) ## [5.41.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.41.0...v5.41.1) (2022-06-13) - ### Bug Fixes -* forward foreground push messages to kit ([#178](https://github.com/mParticle/mparticle-android-sdk/issues/178)) ([b0bebe7](https://github.com/mParticle/mparticle-android-sdk/commit/b0bebe79f4cee67da1b258a740ca4a20b8f3bb9d)) - +- forward foreground push messages to kit ([#178](https://github.com/mParticle/mparticle-android-sdk/issues/178)) ([b0bebe7](https://github.com/mParticle/mparticle-android-sdk/commit/b0bebe79f4cee67da1b258a740ca4a20b8f3bb9d)) ### Updates & Maintenance -* Update Submodules ([d279ef3](https://github.com/mParticle/mparticle-android-sdk/commit/d279ef3e16984f9e835f08dc889518a23cd26adf)) +- Update Submodules ([d279ef3](https://github.com/mParticle/mparticle-android-sdk/commit/d279ef3e16984f9e835f08dc889518a23cd26adf)) ## [5.41.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.40.4...v5.41.0) (2022-06-06) - ### Features -* update dependabot job ([#172](https://github.com/mParticle/mparticle-android-sdk/issues/172)) ([fbe44b2](https://github.com/mParticle/mparticle-android-sdk/commit/fbe44b2fcec1716238273d33b1a088401def5bd0)) - +- update dependabot job ([#172](https://github.com/mParticle/mparticle-android-sdk/issues/172)) ([fbe44b2](https://github.com/mParticle/mparticle-android-sdk/commit/fbe44b2fcec1716238273d33b1a088401def5bd0)) ### Updates & Maintenance -* Update Submodules ([d42983c](https://github.com/mParticle/mparticle-android-sdk/commit/d42983cb469e76c37960367d103c481e118da96c)) +- Update Submodules ([d42983c](https://github.com/mParticle/mparticle-android-sdk/commit/d42983cb469e76c37960367d103c481e118da96c)) ## [5.40.4](https://github.com/mParticle/mparticle-android-sdk/compare/v5.40.3...v5.40.4) (2022-06-02) - ### Updates & Maintenance -* Update Submodules ([f516c2a](https://github.com/mParticle/mparticle-android-sdk/commit/f516c2a4784da5f4d21cfd9d2847eb6ca928008a)) +- Update Submodules ([f516c2a](https://github.com/mParticle/mparticle-android-sdk/commit/f516c2a4784da5f4d21cfd9d2847eb6ca928008a)) ### [5.40.3](https://github.com/mParticle/mparticle-android-sdk/compare/v5.40.2...v5.40.3) (2022-05-26) - ### Updates & Maintenance -* update lint dependencies, add version field ([#146](https://github.com/mParticle/mparticle-android-sdk/issues/146)) ([f5009b0](https://github.com/mParticle/mparticle-android-sdk/commit/f5009b03c4b94c21bc1a5525cd6ec5095657f324)) -* Update Submodules ([f334a97](https://github.com/mParticle/mparticle-android-sdk/commit/f334a97b468fe75ba68b49a8295066c2d1dcba5c)) +- update lint dependencies, add version field ([#146](https://github.com/mParticle/mparticle-android-sdk/issues/146)) ([f5009b0](https://github.com/mParticle/mparticle-android-sdk/commit/f5009b03c4b94c21bc1a5525cd6ec5095657f324)) +- Update Submodules ([f334a97](https://github.com/mParticle/mparticle-android-sdk/commit/f334a97b468fe75ba68b49a8295066c2d1dcba5c)) ### [5.40.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.40.1...v5.40.2) (2022-05-20) - ### Bug Fixes -* change default batch creation error logic ([#145](https://github.com/mParticle/mparticle-android-sdk/issues/145)) ([d0cf645](https://github.com/mParticle/mparticle-android-sdk/commit/d0cf6458fc1b296beb5289f4d3a3c91505f77adc)) +- change default batch creation error logic ([#145](https://github.com/mParticle/mparticle-android-sdk/issues/145)) ([d0cf645](https://github.com/mParticle/mparticle-android-sdk/commit/d0cf6458fc1b296beb5289f4d3a3c91505f77adc)) ### [5.40.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.40.0...v5.40.1) (2022-05-20) - ### Bug Fixes -* rollback removal of MPEvent's info() methods ([#144](https://github.com/mParticle/mparticle-android-sdk/issues/144)) ([854b3a0](https://github.com/mParticle/mparticle-android-sdk/commit/854b3a021142e4bb9a96635ec14928f20f1f5d83)) +- rollback removal of MPEvent's info() methods ([#144](https://github.com/mParticle/mparticle-android-sdk/issues/144)) ([854b3a0](https://github.com/mParticle/mparticle-android-sdk/commit/854b3a021142e4bb9a96635ec14928f20f1f5d83)) ## [5.40.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.39.0...v5.40.0) (2022-05-19) - ### Features -* add client side rules ([#141](https://github.com/mParticle/mparticle-android-sdk/issues/141)) ([033ec68](https://github.com/mParticle/mparticle-android-sdk/commit/033ec689ede873f4686af940f7bdd69d58ff3efc)) - +- add client side rules ([#141](https://github.com/mParticle/mparticle-android-sdk/issues/141)) ([033ec68](https://github.com/mParticle/mparticle-android-sdk/commit/033ec689ede873f4686af940f7bdd69d58ff3efc)) ### Updates & Maintenance -* add BatchCreationListener integration tests ([#143](https://github.com/mParticle/mparticle-android-sdk/issues/143)) ([7642acc](https://github.com/mParticle/mparticle-android-sdk/commit/7642accebf3340afffe11edf43736f07a73afd2d)) -* Update Submodules ([94dd501](https://github.com/mParticle/mparticle-android-sdk/commit/94dd5016d4997579d83cca671737bd8a8a7d0ff5)) +- add BatchCreationListener integration tests ([#143](https://github.com/mParticle/mparticle-android-sdk/issues/143)) ([7642acc](https://github.com/mParticle/mparticle-android-sdk/commit/7642accebf3340afffe11edf43736f07a73afd2d)) +- Update Submodules ([94dd501](https://github.com/mParticle/mparticle-android-sdk/commit/94dd5016d4997579d83cca671737bd8a8a7d0ff5)) ## [5.39.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.38.2...v5.39.0) (2022-05-17) - ### Features -* update customAttributes to accept Object/Any ([#134](https://github.com/mParticle/mparticle-android-sdk/issues/134)) ([44e7c4c](https://github.com/mParticle/mparticle-android-sdk/commit/44e7c4c8bcae20062dd6e74368a17a14496bd371)) - +- update customAttributes to accept Object/Any ([#134](https://github.com/mParticle/mparticle-android-sdk/issues/134)) ([44e7c4c](https://github.com/mParticle/mparticle-android-sdk/commit/44e7c4c8bcae20062dd6e74368a17a14496bd371)) ### Bug Fixes -* update semantic release job in daily check ([#139](https://github.com/mParticle/mparticle-android-sdk/issues/139)) ([01921c4](https://github.com/mParticle/mparticle-android-sdk/commit/01921c41d7139ce31816b757a042d50caf4048f3)) - +- update semantic release job in daily check ([#139](https://github.com/mParticle/mparticle-android-sdk/issues/139)) ([01921c4](https://github.com/mParticle/mparticle-android-sdk/commit/01921c41d7139ce31816b757a042d50caf4048f3)) ### Updates & Maintenance -* add in release notes generator updates ([#138](https://github.com/mParticle/mparticle-android-sdk/issues/138)) ([127f0a5](https://github.com/mParticle/mparticle-android-sdk/commit/127f0a53208f89824f48900ea306e29095cae3da)) -* Update Submodules ([1e8c6e3](https://github.com/mParticle/mparticle-android-sdk/commit/1e8c6e3f7e0f077b74270478e226cc68687187a6)) +- add in release notes generator updates ([#138](https://github.com/mParticle/mparticle-android-sdk/issues/138)) ([127f0a5](https://github.com/mParticle/mparticle-android-sdk/commit/127f0a53208f89824f48900ea306e29095cae3da)) +- Update Submodules ([1e8c6e3](https://github.com/mParticle/mparticle-android-sdk/commit/1e8c6e3f7e0f077b74270478e226cc68687187a6)) ## [5.38.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.38.1...v5.38.2) (2022-05-13) - ### Bug Fixes -* add in environment token in daily job ([#135](https://github.com/mParticle/mparticle-android-sdk/issues/135)) ([8c60184](https://github.com/mParticle/mparticle-android-sdk/commit/8c60184bbd663a30dd28e19fb278eccb85254f93)) -* add value for api in custom lint IssueRegistry ([#129](https://github.com/mParticle/mparticle-android-sdk/issues/129)) ([5b9c520](https://github.com/mParticle/mparticle-android-sdk/commit/5b9c520a43d4aa85675eb8fa1af7032dd05364bf)) -* change dependence from stable tag to branch ([#133](https://github.com/mParticle/mparticle-android-sdk/issues/133)) ([9a99b1d](https://github.com/mParticle/mparticle-android-sdk/commit/9a99b1dde404d0fba1e94ea4ff3d40805dceccfd)) -* dry run param ([#137](https://github.com/mParticle/mparticle-android-sdk/issues/137)) ([e308449](https://github.com/mParticle/mparticle-android-sdk/commit/e308449d0c52fcb06761de143e61dfdc6d46334a)) -* pass in secret to release regression job ([#136](https://github.com/mParticle/mparticle-android-sdk/issues/136)) ([92cccea](https://github.com/mParticle/mparticle-android-sdk/commit/92cccea2b52f244ac11df1d8c689106282140c9f)) +- add in environment token in daily job ([#135](https://github.com/mParticle/mparticle-android-sdk/issues/135)) ([8c60184](https://github.com/mParticle/mparticle-android-sdk/commit/8c60184bbd663a30dd28e19fb278eccb85254f93)) +- add value for api in custom lint IssueRegistry ([#129](https://github.com/mParticle/mparticle-android-sdk/issues/129)) ([5b9c520](https://github.com/mParticle/mparticle-android-sdk/commit/5b9c520a43d4aa85675eb8fa1af7032dd05364bf)) +- change dependence from stable tag to branch ([#133](https://github.com/mParticle/mparticle-android-sdk/issues/133)) ([9a99b1d](https://github.com/mParticle/mparticle-android-sdk/commit/9a99b1dde404d0fba1e94ea4ff3d40805dceccfd)) +- dry run param ([#137](https://github.com/mParticle/mparticle-android-sdk/issues/137)) ([e308449](https://github.com/mParticle/mparticle-android-sdk/commit/e308449d0c52fcb06761de143e61dfdc6d46334a)) +- pass in secret to release regression job ([#136](https://github.com/mParticle/mparticle-android-sdk/issues/136)) ([92cccea](https://github.com/mParticle/mparticle-android-sdk/commit/92cccea2b52f244ac11df1d8c689106282140c9f)) ## [5.38.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.38.0...v5.38.1) (2022-05-02) - ### Bug Fixes -* include stopped kits in active-kits header ([#126](https://github.com/mParticle/mparticle-android-sdk/issues/126)) ([4aaa619](https://github.com/mParticle/mparticle-android-sdk/commit/4aaa619900dd077a7f5cd1adeb0a1b9e83d060a9)) +- include stopped kits in active-kits header ([#126](https://github.com/mParticle/mparticle-android-sdk/issues/126)) ([4aaa619](https://github.com/mParticle/mparticle-android-sdk/commit/4aaa619900dd077a7f5cd1adeb0a1b9e83d060a9)) # [5.38.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.37.0...v5.38.0) (2022-04-19) - ### Bug Fixes -* add in missing project fields ([#122](https://github.com/mParticle/mparticle-android-sdk/issues/122)) ([db8dd19](https://github.com/mParticle/mparticle-android-sdk/commit/db8dd1913f06d3134f1caf74db509d219ab05f80)) -* update test kit command in release.yml ([#123](https://github.com/mParticle/mparticle-android-sdk/issues/123)) ([e33663e](https://github.com/mParticle/mparticle-android-sdk/commit/e33663e0a3d1bd3682f90a47ec161553c2889351)) - +- add in missing project fields ([#122](https://github.com/mParticle/mparticle-android-sdk/issues/122)) ([db8dd19](https://github.com/mParticle/mparticle-android-sdk/commit/db8dd1913f06d3134f1caf74db509d219ab05f80)) +- update test kit command in release.yml ([#123](https://github.com/mParticle/mparticle-android-sdk/issues/123)) ([e33663e](https://github.com/mParticle/mparticle-android-sdk/commit/e33663e0a3d1bd3682f90a47ec161553c2889351)) ### Features -* add gpg signing to mparticle-automation commits ([#120](https://github.com/mParticle/mparticle-android-sdk/issues/120)) ([1b146d7](https://github.com/mParticle/mparticle-android-sdk/commit/1b146d7e8e2ecbf59e758dd703cc31d1219ee0e5)) -* update Target SDK, Kotlin version, and AGP ([#121](https://github.com/mParticle/mparticle-android-sdk/issues/121)) ([bc7b377](https://github.com/mParticle/mparticle-android-sdk/commit/bc7b37751cca7bec2346cde806d7f1e45116afae)) +- add gpg signing to mparticle-automation commits ([#120](https://github.com/mParticle/mparticle-android-sdk/issues/120)) ([1b146d7](https://github.com/mParticle/mparticle-android-sdk/commit/1b146d7e8e2ecbf59e758dd703cc31d1219ee0e5)) +- update Target SDK, Kotlin version, and AGP ([#121](https://github.com/mParticle/mparticle-android-sdk/issues/121)) ([bc7b377](https://github.com/mParticle/mparticle-android-sdk/commit/bc7b37751cca7bec2346cde806d7f1e45116afae)) # [5.37.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.36.2...v5.37.0) (2022-03-24) - ### Bug Fixes -* Proguard keeps KitsLoadedCallback ([#119](https://github.com/mParticle/mparticle-android-sdk/issues/119)) ([e8cfd97](https://github.com/mParticle/mparticle-android-sdk/commit/e8cfd973145649cdff617e6d72e94948fd807426)) - +- Proguard keeps KitsLoadedCallback ([#119](https://github.com/mParticle/mparticle-android-sdk/issues/119)) ([e8cfd97](https://github.com/mParticle/mparticle-android-sdk/commit/e8cfd973145649cdff617e6d72e94948fd807426)) ### Features -* improve kit loading performance ([#118](https://github.com/mParticle/mparticle-android-sdk/issues/118)) ([cb9e321](https://github.com/mParticle/mparticle-android-sdk/commit/cb9e32119aff42862caa7419c0ed3e42874c9f37)) +- improve kit loading performance ([#118](https://github.com/mParticle/mparticle-android-sdk/issues/118)) ([cb9e321](https://github.com/mParticle/mparticle-android-sdk/commit/cb9e32119aff42862caa7419c0ed3e42874c9f37)) ## [5.36.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.36.1...v5.36.2) (2022-03-09) - ### Bug Fixes -* add etag to batch upload payload ([#114](https://github.com/mParticle/mparticle-android-sdk/issues/114)) ([6ce43aa](https://github.com/mParticle/mparticle-android-sdk/commit/6ce43aa3a791c246bf9aae2973e6533618f56281)) +- add etag to batch upload payload ([#114](https://github.com/mParticle/mparticle-android-sdk/issues/114)) ([6ce43aa](https://github.com/mParticle/mparticle-android-sdk/commit/6ce43aa3a791c246bf9aae2973e6533618f56281)) ## [5.36.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.36.0...v5.36.1) (2022-03-08) - ### Bug Fixes -* typo in GA4 kit name ([#112](https://github.com/mParticle/mparticle-android-sdk/issues/112)) ([45f9770](https://github.com/mParticle/mparticle-android-sdk/commit/45f97707b3abbf2082354f0fb647de4ff363490d)) -* update with proper kit configuration ([#113](https://github.com/mParticle/mparticle-android-sdk/issues/113)) ([7496077](https://github.com/mParticle/mparticle-android-sdk/commit/7496077b198f26ea0799fcd2a35b230fdab6cdf8)) +- typo in GA4 kit name ([#112](https://github.com/mParticle/mparticle-android-sdk/issues/112)) ([45f9770](https://github.com/mParticle/mparticle-android-sdk/commit/45f97707b3abbf2082354f0fb647de4ff363490d)) +- update with proper kit configuration ([#113](https://github.com/mParticle/mparticle-android-sdk/issues/113)) ([7496077](https://github.com/mParticle/mparticle-android-sdk/commit/7496077b198f26ea0799fcd2a35b230fdab6cdf8)) # [5.36.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.35.4...v5.36.0) (2022-03-03) - ### Bug Fixes -* downgrade error log to debug ([#102](https://github.com/mParticle/mparticle-android-sdk/issues/102)) ([293ce35](https://github.com/mParticle/mparticle-android-sdk/commit/293ce35f9364dd96e3082934ea48500eb4c70963)) -* keep package names in proguard to prevent collisions ([#109](https://github.com/mParticle/mparticle-android-sdk/issues/109)) ([a8df4fe](https://github.com/mParticle/mparticle-android-sdk/commit/a8df4fe7de883c48312da1a3e09407aaa867a9ae)) - +- downgrade error log to debug ([#102](https://github.com/mParticle/mparticle-android-sdk/issues/102)) ([293ce35](https://github.com/mParticle/mparticle-android-sdk/commit/293ce35f9364dd96e3082934ea48500eb4c70963)) +- keep package names in proguard to prevent collisions ([#109](https://github.com/mParticle/mparticle-android-sdk/issues/109)) ([a8df4fe](https://github.com/mParticle/mparticle-android-sdk/commit/a8df4fe7de883c48312da1a3e09407aaa867a9ae)) ### Features -* add in ktlintcheck ([#108](https://github.com/mParticle/mparticle-android-sdk/issues/108)) ([f75c5b6](https://github.com/mParticle/mparticle-android-sdk/commit/f75c5b63374e270979a80df0038b2e1977372633)) -* remove deprecated methods, AppConfig ([#100](https://github.com/mParticle/mparticle-android-sdk/issues/100)) ([a5a934a](https://github.com/mParticle/mparticle-android-sdk/commit/a5a934adec9ca931a15e53c54233cfe3b1d52b3f)) -* split configuration into core and kits ([#103](https://github.com/mParticle/mparticle-android-sdk/issues/103)) ([766e0d3](https://github.com/mParticle/mparticle-android-sdk/commit/766e0d3f8743e1077f797b9417181cdf30ac6df7)) +- add in ktlintcheck ([#108](https://github.com/mParticle/mparticle-android-sdk/issues/108)) ([f75c5b6](https://github.com/mParticle/mparticle-android-sdk/commit/f75c5b63374e270979a80df0038b2e1977372633)) +- remove deprecated methods, AppConfig ([#100](https://github.com/mParticle/mparticle-android-sdk/issues/100)) ([a5a934a](https://github.com/mParticle/mparticle-android-sdk/commit/a5a934adec9ca931a15e53c54233cfe3b1d52b3f)) +- split configuration into core and kits ([#103](https://github.com/mParticle/mparticle-android-sdk/issues/103)) ([766e0d3](https://github.com/mParticle/mparticle-android-sdk/commit/766e0d3f8743e1077f797b9417181cdf30ac6df7)) ## [5.35.4](https://github.com/mParticle/mparticle-android-sdk/compare/v5.35.3...v5.35.4) (2022-02-18) @@ -1229,29 +1043,25 @@ ## [5.35.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.35.0...v5.35.1) (2022-01-20) - ### Bug Fixes -* update java docs syntax after gradle upgrade ([#98](https://github.com/mParticle/mparticle-android-sdk/issues/98)) ([9a8e22e](https://github.com/mParticle/mparticle-android-sdk/commit/9a8e22e2f43e801c7f9594122e7996e0b9b81c65)) +- update java docs syntax after gradle upgrade ([#98](https://github.com/mParticle/mparticle-android-sdk/issues/98)) ([9a8e22e](https://github.com/mParticle/mparticle-android-sdk/commit/9a8e22e2f43e801c7f9594122e7996e0b9b81c65)) # [5.35.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.34.3...v5.35.0) (2022-01-13) - ### Bug Fixes -* Fix cross platforms for Android forked PRs when checking out code ([#97](https://github.com/mParticle/mparticle-android-sdk/issues/97)) ([90b2760](https://github.com/mParticle/mparticle-android-sdk/commit/90b276009b05575a7b339dbce7631687fa26a0af)) - +- Fix cross platforms for Android forked PRs when checking out code ([#97](https://github.com/mParticle/mparticle-android-sdk/issues/97)) ([90b2760](https://github.com/mParticle/mparticle-android-sdk/commit/90b276009b05575a7b339dbce7631687fa26a0af)) ### Features -* Android id disabled default true ([#89](https://github.com/mParticle/mparticle-android-sdk/issues/89)) ([7fc0217](https://github.com/mParticle/mparticle-android-sdk/commit/7fc02173f2fe81b55817d1f502e30b1d0c5026f0)) +- Android id disabled default true ([#89](https://github.com/mParticle/mparticle-android-sdk/issues/89)) ([7fc0217](https://github.com/mParticle/mparticle-android-sdk/commit/7fc02173f2fe81b55817d1f502e30b1d0c5026f0)) ## [5.34.3](https://github.com/mParticle/mparticle-android-sdk/compare/v5.34.2...v5.34.3) (2022-01-11) - ### Bug Fixes -* add dry run to fix daily cron health check job ([#95](https://github.com/mParticle/mparticle-android-sdk/issues/95)) ([92c443f](https://github.com/mParticle/mparticle-android-sdk/commit/92c443f0c9913860a25d474dfb57e70c4e549847)) +- add dry run to fix daily cron health check job ([#95](https://github.com/mParticle/mparticle-android-sdk/issues/95)) ([92c443f](https://github.com/mParticle/mparticle-android-sdk/commit/92c443f0c9913860a25d474dfb57e70c4e549847)) ## [5.34.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.34.1...v5.34.2) (2022-01-07) @@ -1259,177 +1069,152 @@ # [5.34.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.33.2...v5.34.0) (2022-01-06) - ### Bug Fixes -* Add additional checks for AndroidId ([#87](https://github.com/mParticle/mparticle-android-sdk/issues/87)) ([1eceea3](https://github.com/mParticle/mparticle-android-sdk/commit/1eceea3c80d54648916d6d2d1170a7afc97c7c2f)) -* Change configMaxAge type from Long to int ([#91](https://github.com/mParticle/mparticle-android-sdk/issues/91)) ([14ad4b5](https://github.com/mParticle/mparticle-android-sdk/commit/14ad4b5cd93573287866554c2ec3b3df9d33b94a)) - +- Add additional checks for AndroidId ([#87](https://github.com/mParticle/mparticle-android-sdk/issues/87)) ([1eceea3](https://github.com/mParticle/mparticle-android-sdk/commit/1eceea3c80d54648916d6d2d1170a7afc97c7c2f)) +- Change configMaxAge type from Long to int ([#91](https://github.com/mParticle/mparticle-android-sdk/issues/91)) ([14ad4b5](https://github.com/mParticle/mparticle-android-sdk/commit/14ad4b5cd93573287866554c2ec3b3df9d33b94a)) ### Features -* Add configMaxAge to MParticleOptions ([#85](https://github.com/mParticle/mparticle-android-sdk/issues/85)) ([eaadccd](https://github.com/mParticle/mparticle-android-sdk/commit/eaadccd25c9fec33178aa214fbb6525335797def)) +- Add configMaxAge to MParticleOptions ([#85](https://github.com/mParticle/mparticle-android-sdk/issues/85)) ([eaadccd](https://github.com/mParticle/mparticle-android-sdk/commit/eaadccd25c9fec33178aa214fbb6525335797def)) ## [5.33.2](https://github.com/mParticle/mparticle-android-sdk/compare/v5.33.1...v5.33.2) (2022-01-04) - ### Bug Fixes -* remove bintray url from kits ([323d57d](https://github.com/mParticle/mparticle-android-sdk/commit/323d57d2d12e65cb539f6a9c90dc8870d56fb7c0)) -* Remove broken Sonatype plugin dependency ([41e86a1](https://github.com/mParticle/mparticle-android-sdk/commit/41e86a1ca36ba0a37740200129672da2ba1e9ed5)) -* Transitive dependency, remove version range for localbroadcastmanager ([5f94984](https://github.com/mParticle/mparticle-android-sdk/commit/5f94984632ce5020916129eb03e1e1c835620081)) +- remove bintray url from kits ([323d57d](https://github.com/mParticle/mparticle-android-sdk/commit/323d57d2d12e65cb539f6a9c90dc8870d56fb7c0)) +- Remove broken Sonatype plugin dependency ([41e86a1](https://github.com/mParticle/mparticle-android-sdk/commit/41e86a1ca36ba0a37740200129672da2ba1e9ed5)) +- Transitive dependency, remove version range for localbroadcastmanager ([5f94984](https://github.com/mParticle/mparticle-android-sdk/commit/5f94984632ce5020916129eb03e1e1c835620081)) ## [5.33.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.33.0...v5.33.1) (2021-11-18) - ### Bug Fixes -* bad formatting in release.config.js ([#75](https://github.com/mParticle/mparticle-android-sdk/issues/75)) ([253c9a3](https://github.com/mParticle/mparticle-android-sdk/commit/253c9a32aea894bfa1c975c546965a3c75aa900a)) -* typo in release.config.js ([#76](https://github.com/mParticle/mparticle-android-sdk/issues/76)) ([cf30ab8](https://github.com/mParticle/mparticle-android-sdk/commit/cf30ab85326448bb2f4c84b797f3b5a4adae2ed1)) +- bad formatting in release.config.js ([#75](https://github.com/mParticle/mparticle-android-sdk/issues/75)) ([253c9a3](https://github.com/mParticle/mparticle-android-sdk/commit/253c9a32aea894bfa1c975c546965a3c75aa900a)) +- typo in release.config.js ([#76](https://github.com/mParticle/mparticle-android-sdk/issues/76)) ([cf30ab8](https://github.com/mParticle/mparticle-android-sdk/commit/cf30ab85326448bb2f4c84b797f3b5a4adae2ed1)) # [5.33.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.32.0...v5.33.0) (2021-11-18) - ### Features -* Update Submodules ([b634d90](https://github.com/mParticle/mparticle-android-sdk/commit/b634d905d9b8c614ecba7d1f0d6f0eafcaee30d6)) +- Update Submodules ([b634d90](https://github.com/mParticle/mparticle-android-sdk/commit/b634d905d9b8c614ecba7d1f0d6f0eafcaee30d6)) # [5.32.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.31.0...v5.32.0) (2021-11-01) - ### Features -* Update Submodules ([eb4573f](https://github.com/mParticle/mparticle-android-sdk/commit/eb4573fc76f6ce271b83288140a611c05c84b3b0)) +- Update Submodules ([eb4573f](https://github.com/mParticle/mparticle-android-sdk/commit/eb4573fc76f6ce271b83288140a611c05c84b3b0)) # [5.31.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.30.0...v5.31.0) (2021-10-27) - ### Bug Fixes -* remove Appsee submodule ([8a172b4](https://github.com/mParticle/mparticle-android-sdk/commit/8a172b4a1784260d65149ef5af2bda5dfa2b27cd)) - +- remove Appsee submodule ([8a172b4](https://github.com/mParticle/mparticle-android-sdk/commit/8a172b4a1784260d65149ef5af2bda5dfa2b27cd)) ### Features -* add upload bypass support to logscreen ([177a5d5](https://github.com/mParticle/mparticle-android-sdk/commit/177a5d5ca0cc2df8482db232c2dee35e3b7dee2d)) -* Update Submodules ([45bfd95](https://github.com/mParticle/mparticle-android-sdk/commit/45bfd954d81762919a581b43f93b5fd1289e78e3)) +- add upload bypass support to logscreen ([177a5d5](https://github.com/mParticle/mparticle-android-sdk/commit/177a5d5ca0cc2df8482db232c2dee35e3b7dee2d)) +- Update Submodules ([45bfd95](https://github.com/mParticle/mparticle-android-sdk/commit/45bfd954d81762919a581b43f93b5fd1289e78e3)) # [5.30.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.29.0...v5.30.0) (2021-10-14) - ### Features -* Update Submodules ([9aa5077](https://github.com/mParticle/mparticle-android-sdk/commit/9aa5077374643eb819cd61575aa429c8de744f21)) -* upgrade to AGP 7.X ([267bf36](https://github.com/mParticle/mparticle-android-sdk/commit/267bf3648eed988c7e171d3dbab2bda46f89b989)) +- Update Submodules ([9aa5077](https://github.com/mParticle/mparticle-android-sdk/commit/9aa5077374643eb819cd61575aa429c8de744f21)) +- upgrade to AGP 7.X ([267bf36](https://github.com/mParticle/mparticle-android-sdk/commit/267bf3648eed988c7e171d3dbab2bda46f89b989)) # [5.29.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.28.0...v5.29.0) (2021-10-14) - ### Features -* Update Submodules ([d584a3b](https://github.com/mParticle/mparticle-android-sdk/commit/d584a3b0c86dcf9f0d5ea7aec85c81e30e5c2dbb)) +- Update Submodules ([d584a3b](https://github.com/mParticle/mparticle-android-sdk/commit/d584a3b0c86dcf9f0d5ea7aec85c81e30e5c2dbb)) # [5.28.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.27.0...v5.28.0) (2021-10-05) - ### Features -* Update Submodules ([055c896](https://github.com/mParticle/mparticle-android-sdk/commit/055c89634175d1606208ea851fdcaf8d3f3b8d8f)) +- Update Submodules ([055c896](https://github.com/mParticle/mparticle-android-sdk/commit/055c89634175d1606208ea851fdcaf8d3f3b8d8f)) # [5.27.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.26.0...v5.27.0) (2021-09-23) - ### Bug Fixes -* bugfix some lint issues ([3177500](https://github.com/mParticle/mparticle-android-sdk/commit/31775003a9f91c6999993d346933bf348c8d02a4)) - +- bugfix some lint issues ([3177500](https://github.com/mParticle/mparticle-android-sdk/commit/31775003a9f91c6999993d346933bf348c8d02a4)) ### Features -* Update Submodules ([6b2d6be](https://github.com/mParticle/mparticle-android-sdk/commit/6b2d6bede58a01319ae85e1c18d371f78fd65518)) +- Update Submodules ([6b2d6be](https://github.com/mParticle/mparticle-android-sdk/commit/6b2d6bede58a01319ae85e1c18d371f78fd65518)) # [5.26.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.25.0...v5.26.0) (2021-09-17) - ### Features -* add in lint error check for kits ([81307ae](https://github.com/mParticle/mparticle-android-sdk/commit/81307aea6bd88dcca22a3f74e229da9670147bf9)) +- add in lint error check for kits ([81307ae](https://github.com/mParticle/mparticle-android-sdk/commit/81307aea6bd88dcca22a3f74e229da9670147bf9)) # [5.25.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.24.0...v5.25.0) (2021-09-13) - ### Features -* switch crossplatform tests to run on target repo due to token permission scope ([b7e946a](https://github.com/mParticle/mparticle-android-sdk/commit/b7e946a669cdba632b221e29d8cb4b1ca94c9169)) -* turn on lint errors ([9c98535](https://github.com/mParticle/mparticle-android-sdk/commit/9c98535c22492ad637ca25f3bb86d3674085a41f)) -* Update Submodules ([ed75216](https://github.com/mParticle/mparticle-android-sdk/commit/ed75216de72f71eea75ded8186e41abb4ba4d521)) - +- switch crossplatform tests to run on target repo due to token permission scope ([b7e946a](https://github.com/mParticle/mparticle-android-sdk/commit/b7e946a669cdba632b221e29d8cb4b1ca94c9169)) +- turn on lint errors ([9c98535](https://github.com/mParticle/mparticle-android-sdk/commit/9c98535c22492ad637ca25f3bb86d3674085a41f)) +- Update Submodules ([ed75216](https://github.com/mParticle/mparticle-android-sdk/commit/ed75216de72f71eea75ded8186e41abb4ba4d521)) ### Reverts -* Rollback Kotlin upgrade ([7deee2e](https://github.com/mParticle/mparticle-android-sdk/commit/7deee2eaa36a7cb3899dd17572fb5817037abffc)) +- Rollback Kotlin upgrade ([7deee2e](https://github.com/mParticle/mparticle-android-sdk/commit/7deee2eaa36a7cb3899dd17572fb5817037abffc)) # [5.24.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.23.0...v5.24.0) (2021-09-01) - ### Features -* Update Submodules ([216c775](https://github.com/mParticle/mparticle-android-sdk/commit/216c775cbbe0b55f2b797d9776be92815ce44f0f)) +- Update Submodules ([216c775](https://github.com/mParticle/mparticle-android-sdk/commit/216c775cbbe0b55f2b797d9776be92815ce44f0f)) # [5.23.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.22.0...v5.23.0) (2021-08-26) - ### Features -* Update Submodules ([1826382](https://github.com/mParticle/mparticle-android-sdk/commit/18263821373de1c2ccfc066a2f51108fbf2b2e53)) +- Update Submodules ([1826382](https://github.com/mParticle/mparticle-android-sdk/commit/18263821373de1c2ccfc066a2f51108fbf2b2e53)) # [5.22.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.21.0...v5.22.0) (2021-08-18) - ### Features -* Update Submodules ([1cf5869](https://github.com/mParticle/mparticle-android-sdk/commit/1cf5869300f1a6490c91d8aca07a3a3c6491afb2)) +- Update Submodules ([1cf5869](https://github.com/mParticle/mparticle-android-sdk/commit/1cf5869300f1a6490c91d8aca07a3a3c6491afb2)) # [5.21.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.20.0...v5.21.0) (2021-08-05) - ### Features -* Implement event upload bypass option ([3d8a967](https://github.com/mParticle/mparticle-android-sdk/commit/3d8a9670f4b7f710c2759ab186d2f90abe3990bb)) -* Update Submodules ([e46a282](https://github.com/mParticle/mparticle-android-sdk/commit/e46a282d8b4e9406d9a17a9db77baafa1120bac1)) +- Implement event upload bypass option ([3d8a967](https://github.com/mParticle/mparticle-android-sdk/commit/3d8a9670f4b7f710c2759ab186d2f90abe3990bb)) +- Update Submodules ([e46a282](https://github.com/mParticle/mparticle-android-sdk/commit/e46a282d8b4e9406d9a17a9db77baafa1120bac1)) # [5.20.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.19.0...v5.20.0) (2021-07-22) - ### Features -* Update Submodules ([4a34f66](https://github.com/mParticle/mparticle-android-sdk/commit/4a34f663dbeb30ef36df8d76d72f31615e15719d)) +- Update Submodules ([4a34f66](https://github.com/mParticle/mparticle-android-sdk/commit/4a34f663dbeb30ef36df8d76d72f31615e15719d)) # [5.19.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.18.1...v5.19.0) (2021-07-19) - ### Features -* add support for firebase messaging v22.0.0 ([0facc42](https://github.com/mParticle/mparticle-android-sdk/commit/0facc42d4adb9ccae254185de3f3056a020a6a75)) -* Update Submodules ([4918847](https://github.com/mParticle/mparticle-android-sdk/commit/491884767f0d23e199c0c8881242d7038cc7c96c)) +- add support for firebase messaging v22.0.0 ([0facc42](https://github.com/mParticle/mparticle-android-sdk/commit/0facc42d4adb9ccae254185de3f3056a020a6a75)) +- Update Submodules ([4918847](https://github.com/mParticle/mparticle-android-sdk/commit/491884767f0d23e199c0c8881242d7038cc7c96c)) ## [5.18.1](https://github.com/mParticle/mparticle-android-sdk/compare/v5.18.0...v5.18.1) (2021-07-01) - ### Bug Fixes -* post new release versions to github ([707c9ec](https://github.com/mParticle/mparticle-android-sdk/commit/707c9ec15f005707d3ecc8a472e090689ec42282)) -* Treat duplicate Push tokens as background tokens if no current Session ([63eb698](https://github.com/mParticle/mparticle-android-sdk/commit/63eb698576a8305f697a851a23b2efafffcb620f)) +- post new release versions to github ([707c9ec](https://github.com/mParticle/mparticle-android-sdk/commit/707c9ec15f005707d3ecc8a472e090689ec42282)) +- Treat duplicate Push tokens as background tokens if no current Session ([63eb698](https://github.com/mParticle/mparticle-android-sdk/commit/63eb698576a8305f697a851a23b2efafffcb620f)) # [5.18.0](https://github.com/mParticle/mparticle-android-sdk/compare/v5.17.2...v5.18.0) (2021-06-30) - ### Bug Fixes -* Hardcode macos version for Github Actions ([de1f552](https://github.com/mParticle/mparticle-android-sdk/commit/de1f5523b4b74609870b774fa601f47f8e35fa9d)) - +- Hardcode macos version for Github Actions ([de1f552](https://github.com/mParticle/mparticle-android-sdk/commit/de1f5523b4b74609870b774fa601f47f8e35fa9d)) ### Features -* add in semantic release work ([8e26f79](https://github.com/mParticle/mparticle-android-sdk/commit/8e26f79e4c3b401b087bb64d1c84b8a9bf6bd9e3)) -* add in sonatype work ([6e73455](https://github.com/mParticle/mparticle-android-sdk/commit/6e73455d6ccdb72f7182a986fc39afff42c4e7ef)) +- add in semantic release work ([8e26f79](https://github.com/mParticle/mparticle-android-sdk/commit/8e26f79e4c3b401b087bb64d1c84b8a9bf6bd9e3)) +- add in sonatype work ([6e73455](https://github.com/mParticle/mparticle-android-sdk/commit/6e73455d6ccdb72f7182a986fc39afff42c4e7ef)) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6fdfe634a..aa8dd5b54 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,7 +2,6 @@ Thanks for contributing! Please read this document to follow our conventions for contributing to the mParticle SDK. - ## Setting Up 1. Fork the repository and then clone down your fork @@ -10,23 +9,21 @@ Thanks for contributing! Please read this document to follow our conventions for 3. Your PR title will be checked automatically against the below convention (view the commit history to see examples of a proper commit/PR title). If it fails, you must update your title 4. Our engineers will work with you to get your code change implemented once a PR is up - ## Development Process 1. Create your branch from `main` 2. Make your changes 3. Add tests for any new functionality 4. Run the test suite to ensure tests (both new and old) all pass -6. Update the documentation -7. Create a Pull Request - +5. Update the documentation +6. Create a Pull Request ### Pull Requests -* Fill in the required template -* Follow the [Android style guide](https://developer.android.com/kotlin/style-guide) -* Include screenshots and animated GIFs in your pull request whenever possible -* End all files with a newline +- Fill in the required template +- Follow the [Android style guide](https://developer.android.com/kotlin/style-guide) +- Include screenshots and animated GIFs in your pull request whenever possible +- End all files with a newline ### PR Title and Commit Convention @@ -61,23 +58,25 @@ The following lists the different types allowed in the commit message: We use JUnit and Mockito for our testing framework. Please write tests for new code you create. Before submitting your PR, ensure all tests pass by running: #### Lint Checks + ```bash ./gradlew lint ``` #### Unit Tests + ```bash ./gradlew test ``` #### Instrumented Tests + ```bash ./gradlew :android-core:cAT :android-kit-base:cAT --stacktrace ``` Make sure all tests pass successfully before submitting your PR. If you encounter any test failures, investigate and fix the issues before proceeding. - ### Reporting Bugs This section guides you through submitting a bug report for the mParticle Android SDK. Following these guidelines helps maintainers and the community understand your report, reproduce the behavior, and find related reports. @@ -86,14 +85,13 @@ To notify our team about an issue, please submit a ticket through our [mParticle **When you are creating a ticket, please include as many details as possible:** -* Use a clear and descriptive title -* Describe the exact steps which reproduce the problem -* Provide specific examples to demonstrate the steps -* Describe the behavior you observed after following the steps -* Explain which behavior you expected to see instead and why -* Include logcat output and stack traces if applicable -* Include your SDK version and Android OS version - +- Use a clear and descriptive title +- Describe the exact steps which reproduce the problem +- Provide specific examples to demonstrate the steps +- Describe the behavior you observed after following the steps +- Explain which behavior you expected to see instead and why +- Include logcat output and stack traces if applicable +- Include your SDK version and Android OS version ## License diff --git a/README.md b/README.md index 1ac5d8e95..f8892e1d6 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,5 @@ # mParticle Android SDK -# Android SDK ![mParticle logo](https://static.mparticle.com/sdk/mp_logo_black.svg) ## Overview @@ -215,11 +214,11 @@ provide an `mp.config` config file in the project-level directory ```json { - "dataPlanFile": "./mp-dataplan.json", //(required) accepts filename or path + "dataPlanFile": "./mp-dataplan.json", //(required) accepts filename or path - "resultsFile": "./mp-dp-results.json", //(optional) accepts filename or path - "disabled": "false", //(optional) defaults to "false" - "verbose": false //(optional) defaults to "false" + "resultsFile": "./mp-dp-results.json", //(optional) accepts filename or path + "disabled": "false", //(optional) defaults to "false" + "verbose": false //(optional) defaults to "false" } ``` diff --git a/RELEASE.md b/RELEASE.md index 878441cf2..2eafd710f 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -7,75 +7,77 @@ This document outlines the process for releasing the mParticle Android SDK and i The Android SDK and kits are released using GitHub Actions. The SDK and kits are currently coupled together in the release process. ### Pre-release Checklist + - Ensure all commits are in the public main branch - Review `release.yml` in the repo for specific workflow details - The release job deploys the most current snapshot of main branch release tag to main branch - ## Step 2: Release via GitHub Actions ### What the GitHub Release Job Does 1. **Initial Setup** - - Verifies job is running from public repo and on main branch - - Creates temporary `release/{run_number}` branch + - Verifies job is running from public repo and on main branch + - Creates temporary `release/{run_number}` branch 2. **Testing Phase** - - Runs unit and instrumented tests in parallel - - Instrumented tests require an emulator - - Unit tests run independently - - Updates kits and runs additional tests + - Runs unit and instrumented tests in parallel + - Instrumented tests require an emulator + - Unit tests run independently + - Updates kits and runs additional tests 3. **Version Management** - - Runs semantic version action - - Automatically bumps `build.gradle` version based on commit messages - - No version bump if no new commits (e.g., feat/fix) - - Generates release notes automatically - - Requires linear history between development and main branches + - Runs semantic version action + - Automatically bumps `build.gradle` version based on commit messages + - No version bump if no new commits (e.g., feat/fix) + - Generates release notes automatically + - Requires linear history between development and main branches 4. **Artifact Publishing** - - Uploads artifacts to Sonatype (core and kits) - - Builds and signs the core SDK and all kit artifacts - - Uploads to Sonatype Nexus (staging area) - - Syncs artifacts to Maven Central - > Note: This step will be moved before version bump during semantic release + - Uploads artifacts to Sonatype (core and kits) + - Builds and signs the core SDK and all kit artifacts + - Uploads to Sonatype Nexus (staging area) + - Syncs artifacts to Maven Central + > Note: This step will be moved before version bump during semantic release 5. **Branch Synchronization** - - Pushes release branch to: - - Public main branch - - Public development branch - - Internal repo main branch - - Deletes release branch on success (preserved on failure for debugging) + - Pushes release branch to: + - Public main branch + - Public development branch + - Internal repo main branch + - Deletes release branch on success (preserved on failure for debugging) ### How to Release 1. Navigate to the Actions tab 2. Select "release SDK" 3. Run the workflow from main branch with "true" first to perform a dry run - > Important: Always start with a dry run to validate the release process. This will perform all steps up to semantic release without actually publishing, helping catch potential issues early. + > Important: Always start with a dry run to validate the release process. This will perform all steps up to semantic release without actually publishing, helping catch potential issues early. 4. If the dry run succeeds, run the workflow again with "false" option to perform the actual release - > Note: Only proceed with the actual release after confirming a successful dry run + > Note: Only proceed with the actual release after confirming a successful dry run ### Important Notes - **Release Duration**: Expect ~20 minutes due to comprehensive test suite -- **Emulator Issues**: - - Sometimes GitHub Actions emulators fail - - We have a custom script to install and start the emulator `scripts/install-start-emulator.sh` - - OS version is hardcoded to avoid issues with new releases -- **Code Reusability**: - - Reusable GitHub Actions are defined in the [mparticle-workflows repo](https://github.com/mParticle/mparticle-workflows) - - This enables other platforms to reuse similar jobs +- **Emulator Issues**: + - Sometimes GitHub Actions emulators fail + - We have a custom script to install and start the emulator `scripts/install-start-emulator.sh` + - OS version is hardcoded to avoid issues with new releases +- **Code Reusability**: + - Reusable GitHub Actions are defined in the [mparticle-workflows repo](https://github.com/mParticle/mparticle-workflows) + - This enables other platforms to reuse similar jobs ## Post-Release Verification After a successful build through GitHub Actions, verify: + 1. Public repo has a new semantic release tag -2. New artifact is present in [Sonatype](https://central.sonatype.com/publishing) +2. New artifact is present in [Sonatype](https://central.sonatype.com/publishing) ## Troubleshooting If you encounter emulator issues during testing, check: + - [Emulator setup script](https://github.com/mParticle/mparticle-android-sdk/blob/main/scripts/install-start-emulator.sh) - Current OS version compatibility - GitHub Actions logs for specific error messages diff --git a/android-core/src/androidTest/kotlin/com.mparticle/MParticleTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/MParticleTest.kt index 71d0cf57c..c3ce58f58 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/MParticleTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/MParticleTest.kt @@ -30,8 +30,21 @@ import java.util.concurrent.CountDownLatch import kotlin.test.assertTrue class MParticleTest : BaseCleanStartedEachTest() { - private val configResponse = - "{\"dt\":\"ac\", \"id\":\"fddf1f96-560e-41f6-8f9b-ddd070be0765\", \"ct\":1434392412994, \"dbg\":false, \"cue\":\"appdefined\", \"pmk\":[\"mp_message\", \"com.urbanairship.push.ALERT\", \"alert\", \"a\", \"message\"], \"cnp\":\"appdefined\", \"soc\":0, \"oo\":false, \"eks\":[] }, \"pio\":30 }" + private val configResponse = """ + { + "dt": "ac", + "id": "fddf1f96-560e-41f6-8f9b-ddd070be0765", + "ct": 1434392412994, + "dbg": false, + "cue": "appdefined", + "pmk": ["mp_message", "com.urbanairship.push.ALERT", "alert", "a", "message"], + "cnp": "appdefined", + "soc": 0, + "oo": false, + "eks": [] + }, + "pio": 30 + """ @Test fun testEnsureSessionActive() { @@ -488,7 +501,7 @@ class MParticleTest : BaseCleanStartedEachTest() { .getConfigManager() .getMpids() ?.size ?: 0 - ), + ), ) // Set strict mode, so if we get any warning or error messages during the reset/restart phase, diff --git a/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleIdentityClientImplTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleIdentityClientImplTest.kt index 4c40ea358..1f9645ab8 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleIdentityClientImplTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleIdentityClientImplTest.kt @@ -236,7 +236,7 @@ class MParticleIdentityClientImplTest : BaseCleanStartedEachTest() { .getInstance() ?.Identity() ?.currentUser as MParticleUserImpl? - )?.userIdentities = oldUserIdentities + )?.userIdentities = oldUserIdentities val latch: CountDownLatch = MPLatch(1) val checked = MutableBoolean(false) setApiClient( @@ -248,8 +248,8 @@ class MParticleIdentityClientImplTest : BaseCleanStartedEachTest() { mparticle: Boolean, ) { if (connection.url - .toString() - .contains(MParticleIdentityClientImpl.MODIFY_PATH) + .toString() + .contains(MParticleIdentityClientImpl.MODIFY_PATH) ) { val jsonObject = payload?.let { JSONObject(it) } val changedIdentities = diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/AppStateManagerInstrumentedTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/AppStateManagerInstrumentedTest.kt index 9648a9dfb..6f348cc45 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/AppStateManagerInstrumentedTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/AppStateManagerInstrumentedTest.kt @@ -128,20 +128,20 @@ class AppStateManagerInstrumentedTest : BaseCleanStartedEachTest() { context: Context?, var latch: CountDownLatch, ) : KitFrameworkWrapper( - context, - object : ReportingManager { - override fun log(message: JsonReportingMessage) { - // do nothing - } + context, + object : ReportingManager { + override fun log(message: JsonReportingMessage) { + // do nothing + } - override fun logAll(messageList: List) { - // do nothing - } - }, - MParticle.getInstance()?.Internal()?.configManager, - MParticle.getInstance()?.Internal()?.appStateManager, - MParticleOptions.builder(mContext).credentials("some", "key").build(), - ) { + override fun logAll(messageList: List) { + // do nothing + } + }, + MParticle.getInstance()?.Internal()?.configManager, + MParticle.getInstance()?.Internal()?.appStateManager, + MParticleOptions.builder(mContext).credentials("some", "key").build(), + ) { var onApplicationBackgroundCalled = false var onApplicationForegroundCalled = false diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/TestSQLiteOpenHelper.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/TestSQLiteOpenHelper.kt index 3ea5dd384..e72da3432 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/TestSQLiteOpenHelper.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/TestSQLiteOpenHelper.kt @@ -8,50 +8,50 @@ import com.mparticle.testutils.MPLatch import java.util.concurrent.CountDownLatch class TestSQLiteOpenHelper - @JvmOverloads - constructor( - var helper: SQLiteOpenHelperWrapper, - databaseName: String?, - version: Int = 1, - ) : SQLiteOpenHelper( - InstrumentationRegistry.getInstrumentation().context, - databaseName, - null, - version, - ) { - @JvmField - var onCreateLatch: CountDownLatch = MPLatch(1) - - @JvmField - var onUpgradeLatch: CountDownLatch = MPLatch(1) - - @JvmField - var onDowngradeLatch: CountDownLatch = MPLatch(1) - - init { - writableDatabase - } - - override fun onCreate(db: SQLiteDatabase) { - helper.onCreate(db) - onCreateLatch.countDown() - } - - override fun onUpgrade( - db: SQLiteDatabase, - oldVersion: Int, - newVersion: Int, - ) { - helper.onUpgrade(db, oldVersion, newVersion) - onUpgradeLatch.countDown() - } - - override fun onDowngrade( - db: SQLiteDatabase, - oldVersion: Int, - newVersion: Int, - ) { - helper.onDowngrade(db, oldVersion, newVersion) - onDowngradeLatch.countDown() - } +@JvmOverloads +constructor( + var helper: SQLiteOpenHelperWrapper, + databaseName: String?, + version: Int = 1, +) : SQLiteOpenHelper( + InstrumentationRegistry.getInstrumentation().context, + databaseName, + null, + version, +) { + @JvmField + var onCreateLatch: CountDownLatch = MPLatch(1) + + @JvmField + var onUpgradeLatch: CountDownLatch = MPLatch(1) + + @JvmField + var onDowngradeLatch: CountDownLatch = MPLatch(1) + + init { + writableDatabase } + + override fun onCreate(db: SQLiteDatabase) { + helper.onCreate(db) + onCreateLatch.countDown() + } + + override fun onUpgrade( + db: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) { + helper.onUpgrade(db, oldVersion, newVersion) + onUpgradeLatch.countDown() + } + + override fun onDowngrade( + db: SQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) { + helper.onDowngrade(db, oldVersion, newVersion) + onDowngradeLatch.countDown() + } +} diff --git a/android-core/src/androidTest/kotlin/com.mparticle/networking/AccessUtils.kt b/android-core/src/androidTest/kotlin/com.mparticle/networking/AccessUtils.kt index b618fbbbe..93b799f03 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/networking/AccessUtils.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/networking/AccessUtils.kt @@ -50,6 +50,6 @@ object AccessUtils { return ( (certificate1.certificate === certificate2.certificate || certificate1.certificate == certificate2.certificate) && (certificate1.alias === certificate2.alias || certificate1.alias == certificate2.alias) - ) + ) } } diff --git a/android-core/src/test/kotlin/com/mparticle/internal/UploadHandlerTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/UploadHandlerTest.kt index 7e8bcad26..ff4640404 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/UploadHandlerTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/UploadHandlerTest.kt @@ -439,13 +439,13 @@ class UploadHandlerTest { configManager: ConfigManager?, appStateManager: AppStateManager?, ) : UploadHandler( - MockContext(), - configManager, - appStateManager, - Mockito.mock(MessageManager::class.java), - database, - Mockito.mock(KitFrameworkWrapper::class.java), - ) { + MockContext(), + configManager, + appStateManager, + Mockito.mock(MessageManager::class.java), + database, + Mockito.mock(KitFrameworkWrapper::class.java), + ) { var message: Message? = null var messageDelay: Long? = null var uploadCalledCount = 0 diff --git a/android-core/src/test/kotlin/com/mparticle/networking/NetworkOptionsTest.kt b/android-core/src/test/kotlin/com/mparticle/networking/NetworkOptionsTest.kt index 45938a5ad..5f0f688dd 100644 --- a/android-core/src/test/kotlin/com/mparticle/networking/NetworkOptionsTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/networking/NetworkOptionsTest.kt @@ -98,7 +98,7 @@ class NetworkOptionsTest { return ( (certificate1.certificate === certificate2.certificate || certificate1.certificate == certificate2.certificate) && (certificate1.alias === certificate2.alias || certificate1.alias == certificate2.alias) - ) + ) } } } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt index 3eebfc018..3f7bc928a 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt @@ -16,9 +16,10 @@ open class UserAttributeListenerTestKit : var onSetUserAttributeList: ((attributeKey: String?, attributeValueList: List?, user: FilteredMParticleUser?) -> Unit)? = null var onSetAllUserAttributes: ( - (userAttributes: Map?, userAttributeLists: Map?>?, user: FilteredMParticleUser?) -> Unit - )? = - null + userAttributes: Map?, + userAttributeLists: Map?>?, + user: FilteredMParticleUser?, + ) -> Unit? = null var supportsAttributeLists: (() -> Boolean)? = null var onConsentStateUpdated: ((oldState: ConsentState?, newState: ConsentState?, user: FilteredMParticleUser?) -> Unit)? = null diff --git a/android-kit-base/src/main/kotlin/com/mparticle/kits/DataplanFilter.kt b/android-kit-base/src/main/kotlin/com/mparticle/kits/DataplanFilter.kt index 319b3caa7..8de7308cf 100644 --- a/android-kit-base/src/main/kotlin/com/mparticle/kits/DataplanFilter.kt +++ b/android-kit-base/src/main/kotlin/com/mparticle/kits/DataplanFilter.kt @@ -48,9 +48,9 @@ Data Plan parsed for Kit Filtering: blockUserAttributes=$blockUserAttributes blockUserIdentities=$blockUserIdentities ${ - dataPoints.entries.joinToString("\n") { (key, value) -> - "$key\n\t${value?.joinToString("\n\t") { it }}" - } + dataPoints.entries.joinToString("\n") { (key, value) -> + "$key\n\t${value?.joinToString("\n\t") { it }}" + } } """, ) diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitConfigurationTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitConfigurationTest.kt index 0f4b952af..d00fb2694 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitConfigurationTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitConfigurationTest.kt @@ -38,8 +38,8 @@ class KitConfigurationTest { val attributeValueFilter = ekConfig.getJSONObject("avf") if (attributeValueFilter.has("i") && attributeValueFilter.has("a") && attributeValueFilter.has( - "v", - ) + "v", + ) ) { val shouldIncludeMatches = attributeValueFilter["i"] val hashedAttribute = attributeValueFilter["a"] diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerImplTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerImplTest.kt index 413a09a98..95cdf22de 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerImplTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerImplTest.kt @@ -1281,7 +1281,7 @@ class KitManagerImplTest { MParticleUser::class.java, IdentityApi::class.java, KitConfiguration::class.java, - Runnable::class.java + Runnable::class.java, ) method.isAccessible = true val result = method.invoke(manager, "Test@gmail.com", null, user, identityApi, mockedKitConfig, runnable) @@ -1335,7 +1335,7 @@ class KitManagerImplTest { MParticleUser::class.java, IdentityApi::class.java, KitConfiguration::class.java, - Runnable::class.java + Runnable::class.java, ) method.isAccessible = true val result = method.invoke(manager, null, null, user, identityApi, mockedKitConfig, runnable) @@ -1389,7 +1389,7 @@ class KitManagerImplTest { MParticleUser::class.java, IdentityApi::class.java, KitConfiguration::class.java, - Runnable::class.java + Runnable::class.java, ) method.isAccessible = true val result = method.invoke(manager, "", "", user, identityApi, mockedKitConfig, runnable) @@ -1443,7 +1443,7 @@ class KitManagerImplTest { MParticleUser::class.java, IdentityApi::class.java, KitConfiguration::class.java, - Runnable::class.java + Runnable::class.java, ) method.isAccessible = true val result = method.invoke(manager, "", "hashed_Test@gmail.com", user, identityApi, mockedKitConfig, runnable) @@ -1497,7 +1497,7 @@ class KitManagerImplTest { MParticleUser::class.java, IdentityApi::class.java, KitConfiguration::class.java, - Runnable::class.java + Runnable::class.java, ) method.isAccessible = true val result = method.invoke(manager, null, "hashed_Test@gmail.com", user, identityApi, mockedKitConfig, runnable) @@ -1551,7 +1551,7 @@ class KitManagerImplTest { MParticleUser::class.java, IdentityApi::class.java, KitConfiguration::class.java, - Runnable::class.java + Runnable::class.java, ) method.isAccessible = true val result = method.invoke(manager, null, null, user, identityApi, mockedKitConfig, runnable) @@ -1587,7 +1587,7 @@ class KitManagerImplTest { // add placement attributes here if needed ] """.trimIndent(), - "hashedEmailUserIdentityType" to "Other3" + "hashedEmailUserIdentityType" to "Other3", ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true @@ -1603,7 +1603,7 @@ class KitManagerImplTest { MParticleUser::class.java, IdentityApi::class.java, KitConfiguration::class.java, - Runnable::class.java + Runnable::class.java, ) method.isAccessible = true val result = method.invoke(manager, "", "hashed_Test@gmail.com", user, identityApi, mockedKitConfig, runnable) @@ -1639,7 +1639,7 @@ class KitManagerImplTest { // add placement attributes here if needed ] """.trimIndent(), - "hashedEmailUserIdentityType" to "Unknown" + "hashedEmailUserIdentityType" to "Unknown", ) val field = KitConfiguration::class.java.getDeclaredField("settings") field.isAccessible = true @@ -1655,7 +1655,7 @@ class KitManagerImplTest { MParticleUser::class.java, IdentityApi::class.java, KitConfiguration::class.java, - Runnable::class.java + Runnable::class.java, ) method.isAccessible = true val result = method.invoke(manager, "", "hashed_Test@gmail.com", user, identityApi, mockedKitConfig, runnable) diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt index 598c07ae7..5210cf429 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt @@ -107,8 +107,8 @@ class CustomMappingTest { val attProj = CustomMapping.AttributeMap(attribute) Assert.assertEquals(attribute.optBoolean("is_required"), attProj.mIsRequired) if (attribute - .getString("match_type") - .startsWith(CustomMapping.MATCH_TYPE_STATIC) + .getString("match_type") + .startsWith(CustomMapping.MATCH_TYPE_STATIC) ) { Assert.assertFalse(customMapping.mRequiredAttributeMapList.contains(attProj)) Assert.assertTrue(customMapping.mStaticAttributeMapList.contains(attProj)) diff --git a/build.gradle b/build.gradle index 0e5617934..ee2c11462 100644 --- a/build.gradle +++ b/build.gradle @@ -51,19 +51,7 @@ allprojects { } apply plugin: 'org.jlleitschuh.gradle.ktlint' - - ktlint { - // Disable problematic rules - disabledRules = [ - "trailing-comma", - "trailing-comma-on-call-site", - "trailing-comma-on-declaration-site", - "max-line-length", // Disable line length checks - "indent", // Disable indentation checks - "import-ordering" // Disable import ordering checks - ] - } - + // Apply shared signing configuration to all Android projects afterEvaluate { project -> if (project.hasProperty('android')) { diff --git a/release.config.js b/release.config.js index 184b791a1..de2aa3278 100644 --- a/release.config.js +++ b/release.config.js @@ -1,100 +1,100 @@ module.exports = { - branches: ["main"], - tagFormat: "v${version}", - plugins: [ - [ - "@semantic-release/commit-analyzer", - { - preset: "angular", - releaseRules: [ - { type: "feat", release: "minor" }, - { type: "ci", release: "patch" }, - { type: "fix", release: "patch" }, - { type: "docs", release: "patch" }, - { type: "test", release: "patch" }, - { type: "refactor", release: "patch" }, - { type: "style", release: "patch" }, - { type: "build", release: "patch" }, - { type: "chore", release: "patch" }, - { type: "revert", release: "patch" }, - ], - }, - ], - [ - "@semantic-release/release-notes-generator", - { - preset: "conventionalcommits", - presetConfig: { - types: [ - { - type: "feat", - section: "Features", - hidden: false, - }, - { - type: "fix", - section: "Bug Fixes", - hidden: false, - }, - { - type: "docs", - section: "Documentation", - hidden: false, - }, - { - type: "style", - section: "Updates & Maintenance", - hidden: false, - }, + branches: ["main"], + tagFormat: "v${version}", + plugins: [ + [ + "@semantic-release/commit-analyzer", { - type: "refactor", - section: "Updates & Maintenance", - hidden: false, + preset: "angular", + releaseRules: [ + { type: "feat", release: "minor" }, + { type: "ci", release: "patch" }, + { type: "fix", release: "patch" }, + { type: "docs", release: "patch" }, + { type: "test", release: "patch" }, + { type: "refactor", release: "patch" }, + { type: "style", release: "patch" }, + { type: "build", release: "patch" }, + { type: "chore", release: "patch" }, + { type: "revert", release: "patch" }, + ], }, + ], + [ + "@semantic-release/release-notes-generator", { - type: "perf", - section: "Updates & Maintenance", - hidden: false, + preset: "conventionalcommits", + presetConfig: { + types: [ + { + type: "feat", + section: "Features", + hidden: false, + }, + { + type: "fix", + section: "Bug Fixes", + hidden: false, + }, + { + type: "docs", + section: "Documentation", + hidden: false, + }, + { + type: "style", + section: "Updates & Maintenance", + hidden: false, + }, + { + type: "refactor", + section: "Updates & Maintenance", + hidden: false, + }, + { + type: "perf", + section: "Updates & Maintenance", + hidden: false, + }, + { + type: "test", + section: "Updates & Maintenance", + hidden: false, + }, + { + type: "ci", + section: "Updates & Maintenance", + hidden: false, + }, + { + type: "chore", + section: "Updates & Maintenance", + hidden: false, + }, + ], + }, }, + ], + [ + "@semantic-release/changelog", { - type: "test", - section: "Updates & Maintenance", - hidden: false, + changelogFile: "CHANGELOG.md", }, + ], + [ + "@semantic-release/exec", { - type: "ci", - section: "Updates & Maintenance", - hidden: false, + prepareCmd: "sh ./scripts/release.sh ${nextRelease.version}", }, + ], + ["@semantic-release/github"], + [ + "@semantic-release/git", { - type: "chore", - section: "Updates & Maintenance", - hidden: false, + assets: ["CHANGELOG.md", "build.gradle", "README.md"], + message: + "chore: ${nextRelease.version} (release) \n\n${nextRelease.notes}", }, - ], - }, - }, - ], - [ - "@semantic-release/changelog", - { - changelogFile: "CHANGELOG.md", - }, - ], - [ - "@semantic-release/exec", - { - prepareCmd: "sh ./scripts/release.sh ${nextRelease.version}", - }, - ], - ["@semantic-release/github"], - [ - "@semantic-release/git", - { - assets: ["CHANGELOG.md", "build.gradle", "README.md"], - message: - "chore: ${nextRelease.version} (release) \n\n${nextRelease.notes}", - }, + ], ], - ], }; diff --git a/tooling/common/src/main/java/com/mparticle/tooling/Utils.kt b/tooling/common/src/main/java/com/mparticle/tooling/Utils.kt index dd2630686..7debc0edd 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/Utils.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/Utils.kt @@ -22,13 +22,13 @@ object Utils { ): String { Logger.verbose( "command line operation: ${ - joinToString(" ") { - if (it.contains(" ")) { - "\"$it\"" - } else { - it - } + joinToString(" ") { + if (it.contains(" ")) { + "\"$it\"" + } else { + it } + } }", ) var error = "" diff --git a/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt b/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt index 1098b437f..8c1a2ee81 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt @@ -8,14 +8,14 @@ data class ValidationResult( val eventType: String? = null, val data: ValidationResultData? = null, val error: DataPlanError? = null, - val arguments: List + val arguments: List, ) { var originalString: String? = null companion object { fun from( json: String?, - arguments: List + arguments: List, ): List? = try { val jsonArray = JSONObject(json).getJSONArray("results") @@ -53,20 +53,20 @@ data class ValidationResult( "ValidationErrors", data?.validationErrors?.foldRight(JSONArray()) { item, arr -> arr.put(item) - } - ) + }, + ), ) .put("Event Type", eventType) return """ Arguments: ${arguments.indexOfFirst { it.startsWith("--dataPlan") }.let { index -> - arguments.toMutableList().apply { - if (index >= 0) { - val dataplan = removeAt(index + 1) - add(index + 1, "${dataplan.substring(0, dataplan.length.coerceAtMost(20))}...") - } + arguments.toMutableList().apply { + if (index >= 0) { + val dataplan = removeAt(index + 1) + add(index + 1, "${dataplan.substring(0, dataplan.length.coerceAtMost(20))}...") } - }.joinToString(" ")} + } + }.joinToString(" ")} Response: ${jsonResponse.toString(4)} """.trimIndent() @@ -147,7 +147,8 @@ enum class ValidationErrorType( Unplanned("unplanned"), MissingRequied("missing_required"), InvalidValue("invalid_value"), - Unknown("unknown"); + Unknown("unknown"), + ; companion object { fun forName(text: String): ValidationErrorType = values().first { it.text == text } diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/Extensions.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/Extensions.kt index 2b1b8bf34..2218bfdd5 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/Extensions.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/Extensions.kt @@ -252,7 +252,7 @@ internal fun Pair<*, *>.resolveToEnum(): Enum<*> { val className = when (first) { is ClassId -> "${(first as ClassId).packageFqName}.${ - (first as ClassId).relativeClassName.asString().replace(".", "$") + (first as ClassId).relativeClassName.asString().replace(".", "$") }" is String -> first as String else -> null diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt index b2a60c83c..38a4450e7 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt @@ -52,7 +52,11 @@ class DataplanDetector : CallScanner() { Issue.create( "DataPlanMissing", "Unable to read Data Plan", - "Retrieving the MParticle Data Plan is necessary to evaluate any violations. There may be a problem with locating your \"dataPlanVersionFile\". Please double check the values is correct in your \"mparticle\" block in build.gradle or your mp.config.json file", + """ + |Retrieving the MParticle Data Plan is necessary to evaluate any violations. + |There may be a problem with locating your "dataPlanVersionFile". + |Please double check the values is correct in your "mparticle" block in build.gradle or your mp.config.json file + """.trimMargin(), Category.USABILITY, 4, Severity.INFORMATIONAL, diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt index 1faa2ed80..cd5fe5225 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt @@ -209,7 +209,7 @@ class MpApiDetectorKt : val index = text.indexOf(name ?: "") if (index > 0 && " ${ - text.substring( + text.substring( 0, index, ) From cef04039a703a003addc9b79f8ff5c7a9810435f Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Mon, 29 Sep 2025 10:10:10 -0400 Subject: [PATCH 12/23] fix the test yml file test case error --- .github/workflows/pull-request.yml | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 32e408738..68cbe34bd 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -57,11 +57,12 @@ jobs: emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none disable-animations: true script: | - # Disable benchmark tests as they do not work on emulators - adb uninstall com.mparticle.kittests || true - adb uninstall com.mparticle.kits.test || true - adb uninstall com.mparticle.legacyTest || true - adb uninstall com.mparticle.test || true + # Safely uninstall old test packages if they exist + for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do + if adb shell pm list packages | grep -q "$pkg"; then + adb uninstall "$pkg" + fi + done ./gradlew connectedCheck --info --stacktrace @@ -112,10 +113,12 @@ jobs: disable-animations: true script: | # Disable benchmark tests as they do not work on emulators - adb uninstall com.mparticle.kittests || true - adb uninstall com.mparticle.kits.test || true - adb uninstall com.mparticle.legacyTest || true - adb uninstall com.mparticle.test || true + # Safely uninstall old test packages if they exist + for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do + if adb shell pm list packages | grep -q "$pkg"; then + adb uninstall "$pkg" + fi + done ./gradlew connectedCheck --stacktrace ./gradlew -Porchestrator=true :android-core:cAT -Pandroid.testInstrumentationRunnerArguments.androidx.benchmark.enabledRules=none From 2cac022f85bf27506ee898ad9db38e45845e3003 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Mon, 29 Sep 2025 10:34:11 -0400 Subject: [PATCH 13/23] fix the syntax issue --- .github/workflows/pull-request.yml | 38 +++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 68cbe34bd..9d1c51d16 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -57,12 +57,16 @@ jobs: emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none disable-animations: true script: | - # Safely uninstall old test packages if they exist - for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do - if adb shell pm list packages | grep -q "$pkg"; then - adb uninstall "$pkg" - fi - done + # Clean up any existing test packages before running tests + adb shell settings put global transition_animation_scale 0.0 + adb shell settings put global animator_duration_scale 0.0 + + for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test + do + if adb shell pm list packages | grep -q "$pkg"; then + adb uninstall "$pkg" + fi + done ./gradlew connectedCheck --info --stacktrace @@ -89,6 +93,14 @@ jobs: java-version: "17" - name: Gradle cache uses: gradle/gradle-build-action@842c587ad8aa4c68eeba24c396e15af4c2e9f30a #v2.9.0 + - name: AVD cache + uses: actions/cache@v4 + id: avd-cache + with: + path: | + ~/.android/avd/* + ~/.android/adb* + key: avd-29 - name: create AVD and generate snapshot for caching if: steps.avd-cache.outputs.cache-hit != 'true' @@ -113,11 +125,15 @@ jobs: disable-animations: true script: | # Disable benchmark tests as they do not work on emulators - # Safely uninstall old test packages if they exist - for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do - if adb shell pm list packages | grep -q "$pkg"; then - adb uninstall "$pkg" - fi + # Clean up any existing test packages before running tests + adb shell settings put global transition_animation_scale 0.0 + adb shell settings put global animator_duration_scale 0.0 + + for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test + do + if adb shell pm list packages | grep -q "$pkg"; then + adb uninstall "$pkg" + fi done ./gradlew connectedCheck --stacktrace From 4798823dd47b2892de6541e73bc78a00d410178f Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Mon, 29 Sep 2025 11:04:19 -0400 Subject: [PATCH 14/23] fix the error for v4 --- .github/workflows/pull-request.yml | 34 ++++++++++++++++-------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 9d1c51d16..9cffb5ef5 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -57,16 +57,17 @@ jobs: emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none disable-animations: true script: | - # Clean up any existing test packages before running tests - adb shell settings put global transition_animation_scale 0.0 - adb shell settings put global animator_duration_scale 0.0 - - for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test - do + # Disable animations and clean up test packages + /bin/bash -c ' + adb shell settings put global transition_animation_scale 0.0 + adb shell settings put global animator_duration_scale 0.0 + + for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do if adb shell pm list packages | grep -q "$pkg"; then - adb uninstall "$pkg" + adb uninstall "$pkg" fi - done + done + ' ./gradlew connectedCheck --info --stacktrace @@ -125,16 +126,17 @@ jobs: disable-animations: true script: | # Disable benchmark tests as they do not work on emulators - # Clean up any existing test packages before running tests - adb shell settings put global transition_animation_scale 0.0 - adb shell settings put global animator_duration_scale 0.0 - - for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test - do + # Disable animations and clean up test packages + /bin/bash -c ' + adb shell settings put global transition_animation_scale 0.0 + adb shell settings put global animator_duration_scale 0.0 + + for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do if adb shell pm list packages | grep -q "$pkg"; then - adb uninstall "$pkg" + adb uninstall "$pkg" fi - done + done + ' ./gradlew connectedCheck --stacktrace ./gradlew -Porchestrator=true :android-core:cAT -Pandroid.testInstrumentationRunnerArguments.androidx.benchmark.enabledRules=none From dbc1ddbab9934ea3e0e289e140c25c7017f15748 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Mon, 29 Sep 2025 11:19:03 -0400 Subject: [PATCH 15/23] fix syntax issue --- .github/workflows/pull-request.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 9cffb5ef5..557fb7226 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -58,16 +58,16 @@ jobs: disable-animations: true script: | # Disable animations and clean up test packages - /bin/bash -c ' + /bin/bash -c " adb shell settings put global transition_animation_scale 0.0 adb shell settings put global animator_duration_scale 0.0 for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do - if adb shell pm list packages | grep -q "$pkg"; then - adb uninstall "$pkg" + if adb shell pm list packages | grep -q \"\$pkg\"; then + adb uninstall \"\$pkg\" fi done - ' + " ./gradlew connectedCheck --info --stacktrace @@ -127,16 +127,16 @@ jobs: script: | # Disable benchmark tests as they do not work on emulators # Disable animations and clean up test packages - /bin/bash -c ' + /bin/bash -c " adb shell settings put global transition_animation_scale 0.0 adb shell settings put global animator_duration_scale 0.0 for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do - if adb shell pm list packages | grep -q "$pkg"; then - adb uninstall "$pkg" + if adb shell pm list packages | grep -q \"\$pkg\"; then + adb uninstall \"\$pkg\" fi done - ' + " ./gradlew connectedCheck --stacktrace ./gradlew -Porchestrator=true :android-core:cAT -Pandroid.testInstrumentationRunnerArguments.androidx.benchmark.enabledRules=none From 31ba262d7a48a21668b308d52c38690c1c8873ef Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Mon, 29 Sep 2025 13:07:34 -0400 Subject: [PATCH 16/23] correct GitHub Actions script to remove unterminated quotes --- .github/workflows/pull-request.yml | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 557fb7226..ba2358429 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -61,7 +61,7 @@ jobs: /bin/bash -c " adb shell settings put global transition_animation_scale 0.0 adb shell settings put global animator_duration_scale 0.0 - + for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do if adb shell pm list packages | grep -q \"\$pkg\"; then adb uninstall \"\$pkg\" @@ -127,16 +127,14 @@ jobs: script: | # Disable benchmark tests as they do not work on emulators # Disable animations and clean up test packages - /bin/bash -c " - adb shell settings put global transition_animation_scale 0.0 - adb shell settings put global animator_duration_scale 0.0 - - for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do - if adb shell pm list packages | grep -q \"\$pkg\"; then - adb uninstall \"\$pkg\" - fi - done - " + adb shell settings put global transition_animation_scale 0.0 + adb shell settings put global animator_duration_scale 0.0 + + for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do + if adb shell pm list packages | grep -q "$pkg"; then + adb uninstall "$pkg" + fi + done ./gradlew connectedCheck --stacktrace ./gradlew -Porchestrator=true :android-core:cAT -Pandroid.testInstrumentationRunnerArguments.androidx.benchmark.enabledRules=none From abe23e36ea3027647d9f6d677e9d7af3942df805 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Mon, 29 Sep 2025 13:49:33 -0400 Subject: [PATCH 17/23] Fixed indentation of for loop in script: block --- .github/workflows/pull-request.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index ba2358429..fd0ce9fa3 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -131,9 +131,9 @@ jobs: adb shell settings put global animator_duration_scale 0.0 for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do - if adb shell pm list packages | grep -q "$pkg"; then - adb uninstall "$pkg" - fi + if adb shell pm list packages | grep -q "$pkg"; then + adb uninstall "$pkg" + fi done ./gradlew connectedCheck --stacktrace From dda108b8ac656a7ad12f63ab8c31471bcfb2d8bb Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Mon, 29 Sep 2025 14:08:57 -0400 Subject: [PATCH 18/23] fix: correct shell loop in instrumented orchestrator tests --- .github/workflows/pull-request.yml | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index fd0ce9fa3..76692236b 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -58,16 +58,16 @@ jobs: disable-animations: true script: | # Disable animations and clean up test packages - /bin/bash -c " + bash -eo pipefail -c ' adb shell settings put global transition_animation_scale 0.0 adb shell settings put global animator_duration_scale 0.0 for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do - if adb shell pm list packages | grep -q \"\$pkg\"; then - adb uninstall \"\$pkg\" + if adb shell pm list packages | grep -q "$pkg"; then + adb uninstall "$pkg" fi done - " + ' ./gradlew connectedCheck --info --stacktrace @@ -130,11 +130,7 @@ jobs: adb shell settings put global transition_animation_scale 0.0 adb shell settings put global animator_duration_scale 0.0 - for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do - if adb shell pm list packages | grep -q "$pkg"; then - adb uninstall "$pkg" - fi - done + for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do adb shell pm list packages | grep -q "$pkg" && adb uninstall "$pkg"; done ./gradlew connectedCheck --stacktrace ./gradlew -Porchestrator=true :android-core:cAT -Pandroid.testInstrumentationRunnerArguments.androidx.benchmark.enabledRules=none From 11ea2f3d51406874dd0919dbafb27e9636091550 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Mon, 29 Sep 2025 14:24:38 -0400 Subject: [PATCH 19/23] Prevents shell errors when packages are missing --- .github/workflows/pull-request.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 76692236b..6d3ed70a9 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -130,7 +130,7 @@ jobs: adb shell settings put global transition_animation_scale 0.0 adb shell settings put global animator_duration_scale 0.0 - for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do adb shell pm list packages | grep -q "$pkg" && adb uninstall "$pkg"; done + for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do if adb shell pm list packages | grep -q "$pkg"; then adb uninstall "$pkg"; fi; done ./gradlew connectedCheck --stacktrace ./gradlew -Porchestrator=true :android-core:cAT -Pandroid.testInstrumentationRunnerArguments.androidx.benchmark.enabledRules=none From 5a596a4ec39964c96427dcc2060c45dd5193fa6d Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Mon, 29 Sep 2025 14:37:16 -0400 Subject: [PATCH 20/23] fix the test case and syntax of instrument test cases --- .github/workflows/pull-request.yml | 11 +++-------- .../kits/testkits/UserAttributeListenerTestKit.kt | 4 ++-- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 6d3ed70a9..bdf76a929 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -59,15 +59,10 @@ jobs: script: | # Disable animations and clean up test packages bash -eo pipefail -c ' - adb shell settings put global transition_animation_scale 0.0 - adb shell settings put global animator_duration_scale 0.0 + adb shell settings put global transition_animation_scale 0.0 + adb shell settings put global animator_duration_scale 0.0 - for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do - if adb shell pm list packages | grep -q "$pkg"; then - adb uninstall "$pkg" - fi - done - ' + for pkg in com.mparticle.kittests com.mparticle.kits.test com.mparticle.legacyTest com.mparticle.test; do if adb shell pm list packages | grep -q "$pkg"; then adb uninstall "$pkg"; fi; done ./gradlew connectedCheck --info --stacktrace diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt index 3f7bc928a..f9981d182 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt @@ -15,11 +15,11 @@ open class UserAttributeListenerTestKit : var onSetUserTag: ((key: String?, user: FilteredMParticleUser?) -> Unit)? = null var onSetUserAttributeList: ((attributeKey: String?, attributeValueList: List?, user: FilteredMParticleUser?) -> Unit)? = null - var onSetAllUserAttributes: ( + var onSetAllUserAttributes: (( userAttributes: Map?, userAttributeLists: Map?>?, user: FilteredMParticleUser?, - ) -> Unit? = null + ) -> Unit)? = null var supportsAttributeLists: (() -> Boolean)? = null var onConsentStateUpdated: ((oldState: ConsentState?, newState: ConsentState?, user: FilteredMParticleUser?) -> Unit)? = null From fe9924ddd77cfd8771b2f5c5e43af3b03830e8bc Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Mon, 29 Sep 2025 14:53:49 -0400 Subject: [PATCH 21/23] Remove unnecessary bash pipefail line from script --- .github/workflows/pull-request.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index bdf76a929..5e5ae7a3c 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -58,7 +58,6 @@ jobs: disable-animations: true script: | # Disable animations and clean up test packages - bash -eo pipefail -c ' adb shell settings put global transition_animation_scale 0.0 adb shell settings put global animator_duration_scale 0.0 From e1dda2980811029f2dd0373dfde7f93e4a352461 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Mon, 29 Sep 2025 16:50:03 -0400 Subject: [PATCH 22/23] fix lint issue and sonarqube issue --- .../mparticle/internal/ApplicationContextWrapper.kt | 6 +++++- .../kits/testkits/UserAttributeListenerTestKit.kt | 12 +++++++----- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/android-core/src/main/kotlin/com/mparticle/internal/ApplicationContextWrapper.kt b/android-core/src/main/kotlin/com/mparticle/internal/ApplicationContextWrapper.kt index b06efbfcb..a2075719d 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/ApplicationContextWrapper.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/ApplicationContextWrapper.kt @@ -130,7 +130,11 @@ open class ApplicationContextWrapper( override fun hashCode(): Int = mBaseApplication.hashCode() - override fun equals(obj: Any?): Boolean = mBaseApplication == obj + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is ApplicationContextWrapper) return false + return mBaseApplication == other.mBaseApplication + } override fun toString(): String = mBaseApplication.toString() diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt index f9981d182..8c0fcb881 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt @@ -15,11 +15,13 @@ open class UserAttributeListenerTestKit : var onSetUserTag: ((key: String?, user: FilteredMParticleUser?) -> Unit)? = null var onSetUserAttributeList: ((attributeKey: String?, attributeValueList: List?, user: FilteredMParticleUser?) -> Unit)? = null - var onSetAllUserAttributes: (( - userAttributes: Map?, - userAttributeLists: Map?>?, - user: FilteredMParticleUser?, - ) -> Unit)? = null + var onSetAllUserAttributes: ( + ( + userAttributes: Map?, + userAttributeLists: Map?>?, + user: FilteredMParticleUser?, + ) -> Unit + )? = null var supportsAttributeLists: (() -> Boolean)? = null var onConsentStateUpdated: ((oldState: ConsentState?, newState: ConsentState?, user: FilteredMParticleUser?) -> Unit)? = null From c7ddb6c63668e0342e17839f253a3426f3bb7aff Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Fri, 7 Nov 2025 11:48:31 -0500 Subject: [PATCH 23/23] Add trunk check in Pullrequest and remove kit/rokt-kit from tracking --- .github/workflows/pull-request.yml | 12 ++++++++++++ kits/rokt-kit | 1 - 2 files changed, 12 insertions(+), 1 deletion(-) delete mode 160000 kits/rokt-kit diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 51319312d..3452738f5 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -12,6 +12,18 @@ permissions: checks: write id-token: write + # Code quality checks + trunk-check: + name: Trunk code check + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 #v5.0.0 + - name: Trunk Check + uses: trunk-io/trunk-action@75699af9e26881e564e9d832ef7dc3af25ec031b # v1.2.4 + with: + check-mode: all + jobs: pr-check-hadcoded-secrets: name: "Check PR for hardcoded secrets" diff --git a/kits/rokt-kit b/kits/rokt-kit deleted file mode 160000 index 29ee4a36e..000000000 --- a/kits/rokt-kit +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 29ee4a36eaab76287c6fee3a34cd2293df438f8d