diff --git a/Habitica/AndroidManifest.xml b/Habitica/AndroidManifest.xml
index 17371d259..05d0cbe8f 100644
--- a/Habitica/AndroidManifest.xml
+++ b/Habitica/AndroidManifest.xml
@@ -24,7 +24,8 @@
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
- android:theme="@style/AppTheme">
+ android:theme="@style/AppTheme"
+ tools:replace="android:name">
+ app:gemDrawable="@drawable/gems_84"
+ app:showSeedsPromo="true" />
+ android:gravity="center"
+ android:layout_marginBottom="14dp" />
+
+
\ No newline at end of file
diff --git a/Habitica/res/values/attrs_avatar_view.xml b/Habitica/res/values/attrs_avatar_view.xml
index 0127fc1ae..a8b3fd3c1 100644
--- a/Habitica/res/values/attrs_avatar_view.xml
+++ b/Habitica/res/values/attrs_avatar_view.xml
@@ -9,5 +9,6 @@
+
diff --git a/Habitica/src/main/java/com/habitrpg/android/habitica/HabiticaPurchaseVerifier.java b/Habitica/src/main/java/com/habitrpg/android/habitica/HabiticaPurchaseVerifier.java
index 69fca147c..736013265 100644
--- a/Habitica/src/main/java/com/habitrpg/android/habitica/HabiticaPurchaseVerifier.java
+++ b/Habitica/src/main/java/com/habitrpg/android/habitica/HabiticaPurchaseVerifier.java
@@ -1,8 +1,10 @@
package com.habitrpg.android.habitica;
+import com.habitrpg.android.habitica.helpers.PurchaseTypes;
import com.magicmicky.habitrpgwrapper.lib.models.PurchaseValidationRequest;
import com.magicmicky.habitrpgwrapper.lib.models.PurchaseValidationResult;
import com.magicmicky.habitrpgwrapper.lib.models.Transaction;
+import com.playseeds.android.sdk.Seeds;
import org.solovyev.android.checkout.BasePurchaseVerifier;
import org.solovyev.android.checkout.Purchase;
@@ -60,6 +62,17 @@ public class HabiticaPurchaseVerifier extends BasePurchaseVerifier {
verifiedPurchases.add(purchase);
requestListener.onSuccess(verifiedPurchases);
+
+ //TODO: find way to get $ price automatically.
+ if (purchase.sku.equals(PurchaseTypes.Purchase4Gems)) {
+ Seeds.sharedInstance().recordIAPEvent(purchase.sku, 0.99);
+ } else if (purchase.sku.equals(PurchaseTypes.Purchase21Gems)) {
+ Seeds.sharedInstance().recordIAPEvent(purchase.sku, 4.99);
+ } else if (purchase.sku.equals(PurchaseTypes.Purchase42Gems)) {
+ Seeds.sharedInstance().recordIAPEvent(purchase.sku, 9.99);
+ } else if (purchase.sku.equals(PurchaseTypes.Purchase84Gems)) {
+ Seeds.sharedInstance().recordSeedsIAPEvent(purchase.sku, 19.99);
+ }
}, throwable -> {
if (throwable.getClass().equals(HttpException.class)) {
HttpException error = (HttpException)throwable;
diff --git a/Habitica/src/main/java/com/habitrpg/android/habitica/ui/GemPurchaseOptionsView.java b/Habitica/src/main/java/com/habitrpg/android/habitica/ui/GemPurchaseOptionsView.java
index 51a616f56..966b8602f 100644
--- a/Habitica/src/main/java/com/habitrpg/android/habitica/ui/GemPurchaseOptionsView.java
+++ b/Habitica/src/main/java/com/habitrpg/android/habitica/ui/GemPurchaseOptionsView.java
@@ -4,8 +4,10 @@ import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
+import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
+import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
@@ -25,6 +27,11 @@ public class GemPurchaseOptionsView extends FrameLayout {
@BindView(R.id.purchase_button)
Button purchaseButton;
+
+ @BindView(R.id.seedsImageButton)
+ public
+ ImageButton seedsImageButton;
+
private String sku;
public GemPurchaseOptionsView(Context context, AttributeSet attrs) {
@@ -45,6 +52,10 @@ public class GemPurchaseOptionsView extends FrameLayout {
if (iconRes != null) {
gemImageView.setImageDrawable(iconRes);
}
+
+ if (a.getBoolean(R.styleable.GemPurchaseOptionsView_showSeedsPromo, false)) {
+ seedsImageButton.setVisibility(View.VISIBLE);
+ }
}
public void setOnPurchaseClickListener(Button.OnClickListener listener) {
diff --git a/Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/GemPurchaseActivity.java b/Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/GemPurchaseActivity.java
index 0054223fa..021308046 100644
--- a/Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/GemPurchaseActivity.java
+++ b/Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/GemPurchaseActivity.java
@@ -4,7 +4,10 @@ package com.habitrpg.android.habitica.ui.activities;
import com.habitrpg.android.habitica.HabiticaApplication;
import com.habitrpg.android.habitica.R;
import com.habitrpg.android.habitica.components.AppComponent;
+import com.habitrpg.android.habitica.helpers.PurchaseTypes;
import com.habitrpg.android.habitica.ui.fragments.GemsPurchaseFragment;
+import com.playseeds.android.sdk.Seeds;
+import com.playseeds.android.sdk.inappmessaging.InAppMessageListener;
import org.solovyev.android.checkout.ActivityCheckout;
import org.solovyev.android.checkout.Checkout;
@@ -14,7 +17,7 @@ import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
-public class GemPurchaseActivity extends BaseActivity implements GemsPurchaseFragment.Listener {
+public class GemPurchaseActivity extends BaseActivity implements GemsPurchaseFragment.Listener, InAppMessageListener {
private ActivityCheckout checkout;
@@ -40,6 +43,11 @@ public class GemPurchaseActivity extends BaseActivity implements GemsPurchaseFra
setupCheckout();
+ Seeds.sharedInstance()
+ .simpleInit(this, this, "https://dash.playseeds.com", getString(R.string.seeds_app_key))
+ .setLoggingEnabled(true);
+ Seeds.sharedInstance().requestInAppMessage(getString(R.string.seeds_interstitial_sharing));
+
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
@@ -80,4 +88,50 @@ public class GemPurchaseActivity extends BaseActivity implements GemsPurchaseFra
public ActivityCheckout getActivityCheckout() {
return checkout;
}
+
+ @Override
+ public void inAppMessageClicked(String messageId) {
+ GemsPurchaseFragment fragment = (GemsPurchaseFragment) getSupportFragmentManager().getFragments().get(0);
+ fragment.purchaseGems(PurchaseTypes.Purchase84Gems);
+ }
+
+ @Override
+ public void inAppMessageDismissed(String messageId) {
+
+ }
+
+ @Override
+ public void inAppMessageLoadSucceeded(String messageId) {
+
+ }
+
+ @Override
+ public void inAppMessageShown(String messageId, boolean succeeded) {
+
+ }
+
+ @Override
+ public void noInAppMessageFound(String messageId) {
+
+ }
+
+ @Override
+ public void inAppMessageClickedWithDynamicPrice(String messageId, Double price) {
+
+ }
+
+ public void showSeedsPromo(final String messageId, final String context) {
+ try {
+ runOnUiThread(() -> {
+ if (Seeds.sharedInstance().isInAppMessageLoaded(messageId)) {
+ Seeds.sharedInstance().showInAppMessage(messageId, context);
+ } else {
+ // Skip the interstitial showing this time and try to reload the interstitial
+ Seeds.sharedInstance().requestInAppMessage(messageId);
+ }
+ });
+ } catch (Exception e) {
+ System.out.println("Exception: " + e);
+ }
+ }
}
diff --git a/Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/GemsPurchaseFragment.java b/Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/GemsPurchaseFragment.java
index dd451f79e..fc83ab8c1 100644
--- a/Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/GemsPurchaseFragment.java
+++ b/Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/GemsPurchaseFragment.java
@@ -6,6 +6,9 @@ import com.habitrpg.android.habitica.events.BoughtGemsEvent;
import com.habitrpg.android.habitica.helpers.PurchaseTypes;
import com.habitrpg.android.habitica.proxy.ifce.CrashlyticsProxy;
import com.habitrpg.android.habitica.ui.GemPurchaseOptionsView;
+import com.habitrpg.android.habitica.ui.activities.GemPurchaseActivity;
+import com.habitrpg.android.habitica.ui.helpers.ViewHelper;
+import com.playseeds.android.sdk.Seeds;
import org.greenrobot.eventbus.EventBus;
import org.solovyev.android.checkout.ActivityCheckout;
@@ -86,6 +89,8 @@ public class GemsPurchaseFragment extends BaseFragment {
gems42View.setOnPurchaseClickListener(v -> purchaseGems(PurchaseTypes.Purchase42Gems));
gems84View.setOnPurchaseClickListener(v -> purchaseGems(PurchaseTypes.Purchase84Gems));
+ gems84View.seedsImageButton.setOnClickListener(v -> ((GemPurchaseActivity)this.getActivity()).showSeedsPromo(getString(R.string.seeds_interstitial_gems), "store"));
+
final ActivityCheckout checkout = listener.getActivityCheckout();
if (checkout != null) {
@@ -99,6 +104,9 @@ public class GemsPurchaseFragment extends BaseFragment {
@Override
public void onSuccess(@NonNull Object o) {
EventBus.getDefault().post(new BoughtGemsEvent(GEMS_TO_ADD));
+ if (purchase.sku.equals(PurchaseTypes.Purchase84Gems)) {
+ ((GemPurchaseActivity)getActivity()).showSeedsPromo(getString(R.string.seeds_interstitial_sharing), "store");
+ }
}
@Override
diff --git a/Habitica/src/main/java/com/magicmicky/habitrpgwrapper/lib/models/Preferences.java b/Habitica/src/main/java/com/magicmicky/habitrpgwrapper/lib/models/Preferences.java
index 3918dc849..a214cbe77 100644
--- a/Habitica/src/main/java/com/magicmicky/habitrpgwrapper/lib/models/Preferences.java
+++ b/Habitica/src/main/java/com/magicmicky/habitrpgwrapper/lib/models/Preferences.java
@@ -185,7 +185,7 @@ public class Preferences extends BaseModel {
}
public String getChair() {
- if (chair != null && !chair.equals("none")) {
+ if (chair != null && !chair.equals("none") && !chair.substring(0, 6).equals("chair_")) {
return "chair_" + chair;
}
return null;
diff --git a/habitica.resources.example b/habitica.resources.example
index 989a5322f..98f80f458 100644
--- a/habitica.resources.example
+++ b/habitica.resources.example
@@ -1,3 +1,6 @@
fabric_key=CHANGE_ME
facebook_app_id=CHANGE_ME
amplitude_app_id=CHANGE_ME
+seeds_app_key=CHANGE_ME
+seeds_interstitial_gems=CHANGE_ME
+seeds_interstitial_sharing=CHANGE_ME
diff --git a/seeds-sdk/LICENSE b/seeds-sdk/LICENSE
new file mode 100755
index 000000000..75bb68d7b
--- /dev/null
+++ b/seeds-sdk/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2010-2015 Matomy Media Group Ltd.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/seeds-sdk/MoPub Client Licence.txt b/seeds-sdk/MoPub Client Licence.txt
new file mode 100755
index 000000000..83beb8a16
--- /dev/null
+++ b/seeds-sdk/MoPub Client Licence.txt
@@ -0,0 +1,10 @@
+Copyright (c) 2011 MoPub Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+* Neither the name of MoPub nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/seeds-sdk/NOTICE b/seeds-sdk/NOTICE
new file mode 100644
index 000000000..5f41fb7e9
--- /dev/null
+++ b/seeds-sdk/NOTICE
@@ -0,0 +1,15 @@
+ Copyright 2015 MobFox
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+ limitations under the License.
+
+Code in the com.playseeds.android.sdk.inappmessaging.inappmessaging package modified from
+MobFox Android SDK available at https://github.com/mobfox/MobFox-Android-SDK
\ No newline at end of file
diff --git a/seeds-sdk/build.gradle b/seeds-sdk/build.gradle
new file mode 100755
index 000000000..0f06c44f3
--- /dev/null
+++ b/seeds-sdk/build.gradle
@@ -0,0 +1,72 @@
+apply plugin: 'com.android.library'
+apply plugin: 'com.novoda.bintray-release'
+
+buildscript {
+ repositories {
+ jcenter()
+ }
+ dependencies {
+ classpath 'com.novoda:bintray-release:0.3.4'
+ }
+}
+
+android {
+ compileSdkVersion 23
+ buildToolsVersion "23.0.3"
+
+ defaultConfig {
+ minSdkVersion 12
+ versionCode 1
+ versionName "1.0"
+
+ testInstrumentationRunner 'com.playseeds.android.sdk.test.InstrumentationTestRunner'
+ testHandleProfiling true
+ testFunctionalTest true
+ multiDexEnabled true
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ debug {
+ testCoverageEnabled = true
+ }
+ }
+
+ dexOptions {
+ javaMaxHeapSize "4g"
+ }
+
+ lintOptions {
+ abortOnError false
+ }
+}
+
+dependencies {
+ compile fileTree(dir: 'libs', include: ['*.jar'])
+ compile 'org.glassfish:javax.json:1.0.4'
+ compile 'com.google.android.gms:play-services:9.2.0'
+ compile 'com.google.code.gson:gson:2.4'
+ compile 'com.android.support:multidex:1.0.1'
+ compile 'com.loopj.android:android-async-http:1.4.9'
+
+ compile 'org.solovyev.android:checkout:0.7.5@aar'
+
+ androidTestCompile 'org.mockito:mockito-core:1.9.5'
+ androidTestCompile 'com.google.dexmaker:dexmaker:1.0'
+ androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.0'
+ testCompile 'junit:junit:4.12'
+ testCompile "org.robolectric:robolectric:3.0"
+ testCompile "org.robolectric:shadows-multidex:3.0"
+}
+
+publish {
+ userOrg = 'seedsinc'
+ groupId = 'com.playseeds'
+ artifactId = 'android-sdk'
+ version = '0.4.1'
+ description = 'Android SDK for Seeds mobile analytics'
+ website = 'https://github.com/therealseeds/seeds-sdk-android'
+}
+
diff --git a/seeds-sdk/gradle/wrapper/gradle-wrapper.jar b/seeds-sdk/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 000000000..13372aef5
Binary files /dev/null and b/seeds-sdk/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/seeds-sdk/gradle/wrapper/gradle-wrapper.properties b/seeds-sdk/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000..122a0dca2
--- /dev/null
+++ b/seeds-sdk/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Mon Dec 28 10:00:20 PST 2015
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
diff --git a/seeds-sdk/gradlew b/seeds-sdk/gradlew
new file mode 100644
index 000000000..9d82f7891
--- /dev/null
+++ b/seeds-sdk/gradlew
@@ -0,0 +1,160 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+ echo "$*"
+}
+
+die ( ) {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+esac
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+ JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/seeds-sdk/gradlew.bat b/seeds-sdk/gradlew.bat
new file mode 100644
index 000000000..aec99730b
--- /dev/null
+++ b/seeds-sdk/gradlew.bat
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windowz variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+if "%@eval[2+2]" == "4" goto 4NT_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+goto execute
+
+:4NT_args
+@rem Get arguments from the 4NT Shell from JP Software
+set CMD_LINE_ARGS=%$
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/seeds-sdk/proguard-rules.pro b/seeds-sdk/proguard-rules.pro
new file mode 100755
index 000000000..e9ece7221
--- /dev/null
+++ b/seeds-sdk/proguard-rules.pro
@@ -0,0 +1,17 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /projects/android-sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+# http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+# public *;
+#}
diff --git a/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/AdvertisingIdAdapterTest.java b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/AdvertisingIdAdapterTest.java
new file mode 100644
index 000000000..c4c8a54e9
--- /dev/null
+++ b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/AdvertisingIdAdapterTest.java
@@ -0,0 +1,32 @@
+package com.playseeds.android.sdk;
+
+import android.content.Context;
+import android.test.AndroidTestCase;
+
+public class AdvertisingIdAdapterTest extends AndroidTestCase {
+ Context context;
+
+ public void setUp() throws Exception {
+ context = getContext();
+ }
+
+ public void testIsAdvertisingIdAvailable() throws Exception {
+ assertNotNull(AdvertisingIdAdapter.isAdvertisingIdAvailable());
+ }
+
+ public void testSetAdvertisingId() throws Exception {
+ try {
+ AdvertisingIdAdapter.setAdvertisingId(context, new CountlyStore(context), new DeviceId(DeviceId.Type.ADVERTISING_ID));
+ } catch(Exception e) {
+
+ }
+ }
+
+ public void testSetAdvertisingIdWithNullContext() throws Exception {
+ try {
+ AdvertisingIdAdapter.setAdvertisingId(null, new CountlyStore(context), new DeviceId(DeviceId.Type.ADVERTISING_ID));
+ } catch (Exception e) {
+
+ }
+ }
+}
diff --git a/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/ConnectionProcessorTests.java b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/ConnectionProcessorTests.java
new file mode 100755
index 000000000..aef00c148
--- /dev/null
+++ b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/ConnectionProcessorTests.java
@@ -0,0 +1,284 @@
+/*
+Copyright (c) 2012, 2013, 2014 Countly
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+package com.playseeds.android.sdk;
+
+import android.test.AndroidTestCase;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLConnection;
+
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class ConnectionProcessorTests extends AndroidTestCase {
+ ConnectionProcessor connectionProcessor;
+ CountlyStore mockStore;
+ DeviceId mockDeviceId;
+ String testDeviceId;
+ String eventData;
+ HttpURLConnection mockURLConnection;
+ CountlyResponseStream testInputStream;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ testDeviceId = "123";
+ eventData = "blahblahblah";
+ mockStore = mock(CountlyStore.class);
+ mockDeviceId = mock(DeviceId.class);
+ mockURLConnection = mock(HttpURLConnection.class);
+ testInputStream = new CountlyResponseStream("Success");
+ connectionProcessor = new ConnectionProcessor("http://devdash.playseeds.com", mockStore, mockDeviceId, null);
+ connectionProcessor = spy(connectionProcessor);
+ }
+
+ public void testConstructorAndGetters() {
+ final String serverURL = "https://secureserver";
+ final CountlyStore mockStore = mock(CountlyStore.class);
+ final DeviceId mockDeviceId = mock(DeviceId.class);
+ final ConnectionProcessor connectionProcessor1 = new ConnectionProcessor(serverURL, mockStore, mockDeviceId, null);
+ assertEquals(serverURL, connectionProcessor1.getServerURL());
+ assertSame(mockStore, connectionProcessor1.getCountlyStore());
+ assertSame(mockDeviceId, connectionProcessor1.getDeviceId());
+ }
+
+ public void testUrlConnectionForEventData() throws IOException {
+ final URLConnection urlConnection = connectionProcessor.urlConnectionForEventData(eventData);
+ assertEquals(30000, urlConnection.getConnectTimeout());
+ assertEquals(30000, urlConnection.getReadTimeout());
+ assertFalse(urlConnection.getUseCaches());
+ assertTrue(urlConnection.getDoInput());
+ assertFalse(urlConnection.getDoOutput());
+ assertEquals(new URL(connectionProcessor.getServerURL() + "/i?" + eventData), urlConnection.getURL());
+ }
+
+ public void testRun_storeReturnsNullConnections() throws IOException {
+ when(mockStore.connections()).thenReturn(null);
+ connectionProcessor.run();
+ verify(mockStore).connections();
+ verify(connectionProcessor, times(0)).urlConnectionForEventData(anyString());
+ }
+
+ public void testRun_storeReturnsEmptyConnections() throws IOException {
+ when(mockStore.connections()).thenReturn(new String[0]);
+ connectionProcessor.run();
+ verify(mockStore).connections();
+ verify(connectionProcessor, times(0)).urlConnectionForEventData(anyString());
+ }
+
+ private static class TestInputStream extends InputStream {
+ int readCount = 0;
+ boolean fullyRead() { return readCount >= 2; }
+ boolean closed = false;
+
+ @Override
+ public int read() throws IOException {
+ return readCount++ < 1 ? 1 : -1;
+ }
+
+ @Override
+ public void close() throws IOException {
+ super.close();
+ closed = true;
+ }
+ }
+
+ private static class CountlyResponseStream extends ByteArrayInputStream {
+ boolean closed = false;
+
+ CountlyResponseStream(final String result) throws UnsupportedEncodingException {
+ super(("{\"result\":\"" + result + "\"}").getBytes("UTF-8"));
+ }
+
+ boolean fullyRead() { return pos == buf.length; }
+
+ @Override
+ public void close() throws IOException {
+ super.close();
+ closed = true;
+ }
+ }
+
+ public void testRun_storeHasSingleConnection() throws IOException {
+ when(mockStore.connections()).thenReturn(new String[]{eventData}, new String[0]);
+ when(mockDeviceId.getId()).thenReturn(testDeviceId);
+ when(mockURLConnection.getInputStream()).thenReturn(testInputStream);
+ when(mockURLConnection.getResponseCode()).thenReturn(200);
+ when(connectionProcessor.urlConnectionForEventData(eventData + "&device_id=" + testInputStream)).thenReturn(mockURLConnection);
+
+ connectionProcessor.run();
+ verify(mockStore).connections();
+ verify(connectionProcessor).urlConnectionForEventData(eventData + "&device_id=" + testDeviceId);
+ }
+
+ public void testRun_storeHasSingleConnection_butHTTPResponseCodeWasNot2xx() throws IOException {
+ when(mockStore.connections()).thenReturn(new String[]{eventData}, new String[0]);
+ when(mockDeviceId.getId()).thenReturn(testDeviceId);
+ when(mockURLConnection.getInputStream()).thenReturn(testInputStream);
+ when(mockURLConnection.getResponseCode()).thenReturn(300);
+ doReturn(mockURLConnection).when(connectionProcessor).urlConnectionForEventData(eventData + "&device_id=" + testDeviceId);
+
+ connectionProcessor.run();
+ verify(mockStore).connections();
+ verify(connectionProcessor).urlConnectionForEventData(eventData + "&device_id=" + testDeviceId);
+ verify(mockURLConnection).connect();
+ verify(mockURLConnection).getInputStream();
+ verify(mockURLConnection).getResponseCode();
+ assertTrue(testInputStream.fullyRead());
+ verify(mockStore, times(0)).removeConnection(eventData);
+ assertTrue(testInputStream.closed);
+ verify(mockURLConnection).disconnect();
+ }
+
+ public void testRun_storeHasSingleConnection_butResponseWasNotJSON() throws IOException {
+ when(mockStore.connections()).thenReturn(new String[]{eventData}, new String[0]);
+ when(mockDeviceId.getId()).thenReturn(testDeviceId);
+ when(mockURLConnection.getInputStream()).thenReturn(testInputStream);
+ when(mockURLConnection.getResponseCode()).thenReturn(300);
+ doReturn(mockURLConnection).when(connectionProcessor).urlConnectionForEventData(eventData + "&device_id=" + testDeviceId);
+
+ connectionProcessor.run();
+ verify(mockStore).connections();
+ verify(connectionProcessor).urlConnectionForEventData(eventData + "&device_id=" + testDeviceId);
+ verify(mockURLConnection).connect();
+ verify(mockURLConnection).getInputStream();
+ verify(mockURLConnection).getResponseCode();
+ assertTrue(testInputStream.fullyRead());
+ verify(mockStore, times(0)).removeConnection(eventData);
+ assertTrue(testInputStream.closed);
+ verify(mockURLConnection).disconnect();
+ }
+
+ public void testRun_storeHasSingleConnection_butResponseJSONWasNotSuccess() throws IOException {
+ when(mockStore.connections()).thenReturn(new String[]{eventData}, new String[0]);
+ when(mockDeviceId.getId()).thenReturn(testDeviceId);
+ when(mockURLConnection.getInputStream()).thenReturn(testInputStream);
+ when(mockURLConnection.getResponseCode()).thenReturn(300);
+ doReturn(mockURLConnection).when(connectionProcessor).urlConnectionForEventData(eventData + "&device_id=" + testDeviceId);
+
+ connectionProcessor.run();
+ verify(mockStore).connections();
+ verify(connectionProcessor).urlConnectionForEventData(eventData + "&device_id=" + testDeviceId);
+ verify(mockURLConnection).connect();
+ verify(mockURLConnection).getInputStream();
+ assertTrue(testInputStream.fullyRead());
+ verify(mockURLConnection).getResponseCode();
+ verify(mockStore, times(0)).removeConnection(eventData);
+ assertTrue(testInputStream.closed);
+ verify(mockURLConnection).disconnect();
+ }
+
+ public void testRun_storeHasSingleConnection_successCheckIsCaseInsensitive() throws IOException {
+ testInputStream = new CountlyResponseStream("SuCcEsS");
+
+ when(mockStore.connections()).thenReturn(new String[]{eventData}, new String[0]);
+ when(mockDeviceId.getId()).thenReturn(testDeviceId);
+ when(mockURLConnection.getInputStream()).thenReturn(testInputStream);
+ when(mockURLConnection.getResponseCode()).thenReturn(200);
+ doReturn(mockURLConnection).when(connectionProcessor).urlConnectionForEventData(eventData + "&device_id=" + testDeviceId);
+
+ connectionProcessor.run();
+ verify(mockStore, times(2)).connections();
+ verify(connectionProcessor).urlConnectionForEventData(eventData + "&device_id=" + testDeviceId);
+ verify(mockURLConnection).connect();
+ verify(mockURLConnection).getInputStream();
+ verify(mockURLConnection).getResponseCode();
+ assertTrue(testInputStream.fullyRead());
+ verify(mockStore).removeConnection(eventData);
+ assertTrue(testInputStream.closed);
+ verify(mockURLConnection).disconnect();
+ }
+
+ public void testRun_storeHasTwoConnections() throws IOException {
+ final String eventData2 = "123523523432";
+ final CountlyResponseStream testInputStream2 = new CountlyResponseStream("Success");
+ testInputStream = new CountlyResponseStream("Success");
+
+ when(mockStore.connections()).thenReturn(new String[]{eventData, eventData2}, new String[]{eventData2}, new String[0]);
+ when(mockDeviceId.getId()).thenReturn(testDeviceId);
+ when(mockURLConnection.getInputStream()).thenReturn(testInputStream, testInputStream2);
+ doReturn(mockURLConnection).when(connectionProcessor).urlConnectionForEventData(eventData + "&device_id=" + testDeviceId);
+ doReturn(mockURLConnection).when(connectionProcessor).urlConnectionForEventData(eventData2 + "&device_id=" + testDeviceId);
+ when(mockURLConnection.getResponseCode()).thenReturn(200, 200);
+
+ connectionProcessor.run();
+ verify(mockStore, times(3)).connections();
+ verify(connectionProcessor).urlConnectionForEventData(eventData + "&device_id=" + testDeviceId);
+ verify(connectionProcessor).urlConnectionForEventData(eventData2 + "&device_id=" + testDeviceId);
+ verify(mockURLConnection, times(2)).connect();
+ verify(mockURLConnection, times(2)).getInputStream();
+ verify(mockURLConnection, times(2)).getResponseCode();
+ assertTrue(testInputStream.fullyRead());
+ assertTrue(testInputStream2.fullyRead());
+ verify(mockStore).removeConnection(eventData);
+ verify(mockStore).removeConnection(eventData2);
+ assertTrue(testInputStream.closed);
+ assertTrue(testInputStream2.closed);
+ verify(mockURLConnection, times(2)).disconnect();
+ }
+
+ private static class TestInputStream2 extends InputStream {
+ boolean closed = false;
+
+ @Override
+ public int read() throws IOException {
+ throw new IOException();
+ }
+
+ @Override
+ public void close() throws IOException {
+ super.close();
+ closed = true;
+ }
+ }
+
+ public void testRun_storeHasTwoConnections_butFirstOneThrowsWhenInputStreamIsRead() throws IOException {
+ final String eventData2 = "123523523432";
+ final TestInputStream2 testInputStream = new TestInputStream2();
+
+ when(mockStore.connections()).thenReturn(new String[]{eventData, eventData2}, new String[]{eventData2}, new String[0]);
+ when(mockDeviceId.getId()).thenReturn(testDeviceId);
+ when(mockURLConnection.getInputStream()).thenReturn(testInputStream);
+ doReturn(mockURLConnection).when(connectionProcessor).urlConnectionForEventData(eventData + "&device_id=" + testDeviceId);
+
+ connectionProcessor.run();
+ verify(mockStore).connections();
+ verify(connectionProcessor).urlConnectionForEventData(eventData + "&device_id=" + testDeviceId);
+ verify(connectionProcessor, times(0)).urlConnectionForEventData(eventData2 + "&device_id=" + testDeviceId);
+ verify(mockURLConnection).connect();
+ verify(mockURLConnection).getInputStream();
+ verify(mockStore, times(0)).removeConnection(anyString());
+ assertTrue(testInputStream.closed);
+ verify(mockURLConnection).disconnect();
+ }
+}
\ No newline at end of file
diff --git a/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/ConnectionQueueTests.java b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/ConnectionQueueTests.java
new file mode 100755
index 000000000..99bd5bf8a
--- /dev/null
+++ b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/ConnectionQueueTests.java
@@ -0,0 +1,406 @@
+/*
+Copyright (c) 2012, 2013, 2014 Countly
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+package com.playseeds.android.sdk;
+
+import android.net.Uri;
+import android.test.AndroidTestCase;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.mockito.ArgumentCaptor;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
+public class ConnectionQueueTests extends AndroidTestCase {
+ ConnectionQueue connQ;
+ ConnectionQueue freshConnQ;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ freshConnQ = new ConnectionQueue();
+ connQ = new ConnectionQueue();
+ connQ.setAppKey("abcDeFgHiJkLmNoPQRstuVWxyz");
+ connQ.setServerURL("http://countly.coupons.com");
+ connQ.setContext(getContext());
+ connQ.setCountlyStore(mock(CountlyStore.class));
+ connQ.setDeviceId(mock(DeviceId.class));
+ connQ.setExecutor(mock(ExecutorService.class));
+ }
+
+ public void testConstructor() {
+ assertNull(freshConnQ.getCountlyStore());
+ assertNull(freshConnQ.getDeviceId());
+ assertNull(freshConnQ.getAppKey());
+ assertNull(freshConnQ.getContext());
+ assertNull(freshConnQ.getServerURL());
+ assertNull(freshConnQ.getExecutor());
+ }
+
+ public void testAppKey() {
+ final String appKey = "blahblahblah";
+ freshConnQ.setAppKey(appKey);
+ assertEquals(appKey, freshConnQ.getAppKey());
+ }
+
+ public void testContext() {
+ freshConnQ.setContext(getContext());
+ assertSame(getContext(), freshConnQ.getContext());
+ }
+
+ public void testServerURL() {
+ final String serverURL = "http://countly.coupons.com";
+ freshConnQ.setServerURL(serverURL);
+ assertEquals(serverURL, freshConnQ.getServerURL());
+ }
+
+ public void testCountlyStore() {
+ final CountlyStore store = new CountlyStore(getContext());
+ freshConnQ.setCountlyStore(store);
+ assertSame(store, freshConnQ.getCountlyStore());
+ }
+
+ public void testDeviceId() {
+ final DeviceId deviceId = new DeviceId("blah");
+ freshConnQ.setDeviceId(deviceId);
+ assertSame(deviceId, freshConnQ.getDeviceId());
+ }
+
+ public void testExecutor() {
+ final ExecutorService executor = Executors.newSingleThreadExecutor();
+ freshConnQ.setExecutor(executor);
+ assertSame(executor, freshConnQ.getExecutor());
+ }
+
+ public void testCheckInternalState_nullAppKey() {
+ connQ.checkInternalState(); // shouldn't throw
+ connQ.setAppKey(null);
+ try {
+ freshConnQ.checkInternalState();
+ fail("expected IllegalStateException when internal state is not set up");
+ } catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testCheckInternalState_emptyAppKey() {
+ connQ.checkInternalState(); // shouldn't throw
+ connQ.setAppKey("");
+ try {
+ freshConnQ.checkInternalState();
+ fail("expected IllegalStateException when internal state is not set up");
+ } catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testCheckInternalState_nullStore() {
+ connQ.checkInternalState(); // shouldn't throw
+ connQ.setCountlyStore(null);
+ try {
+ freshConnQ.checkInternalState();
+ fail("expected IllegalStateException when internal state is not set up");
+ } catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testCheckInternalState_nullContext() {
+ connQ.checkInternalState(); // shouldn't throw
+ connQ.setContext(null);
+ try {
+ freshConnQ.checkInternalState();
+ fail("expected IllegalStateException when internal state is not set up");
+ } catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testCheckInternalState_nullServerURL() {
+ connQ.checkInternalState(); // shouldn't throw
+ connQ.setServerURL(null);
+ try {
+ freshConnQ.checkInternalState();
+ fail("expected IllegalStateException when internal state is not set up");
+ } catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testCheckInternalState_invalidServerURL() {
+ connQ.checkInternalState(); // shouldn't throw
+ connQ.setServerURL("blahblahblah.com");
+ try {
+ freshConnQ.checkInternalState();
+ fail("expected IllegalStateException when internal state is not set up");
+ } catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testBeginSession_checkInternalState() {
+ try {
+ freshConnQ.beginSession();
+ fail("expected IllegalStateException when internal state is not set up");
+ } catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testBeginSession() throws JSONException, UnsupportedEncodingException {
+ connQ.beginSession();
+ final ArgumentCaptor arg = ArgumentCaptor.forClass(String.class);
+ verify(connQ.getCountlyStore()).addConnection(arg.capture());
+ verify(connQ.getExecutor()).submit(any(ConnectionProcessor.class));
+
+ // verify query parameters
+ final String queryStr = arg.getValue();
+ final Map queryParams = parseQueryParams(queryStr);
+ assertEquals(connQ.getAppKey(), queryParams.get("app_key"));
+ assertNull(queryParams.get("device_id"));
+ final long curTimestamp = Seeds.currentTimestamp();
+ final int actualTimestamp = Integer.parseInt(queryParams.get("timestamp"));
+ // this check attempts to account for minor time changes during this ly.count.android.sdk.test
+ assertTrue(((curTimestamp-1) <= actualTimestamp) && ((curTimestamp+1) >= actualTimestamp));
+ assertEquals(Seeds.COUNTLY_SDK_VERSION_STRING, queryParams.get("sdk_version"));
+ assertEquals("1", queryParams.get("begin_session"));
+ // validate metrics
+ final JSONObject actualMetrics = new JSONObject(queryParams.get("metrics"));
+ final String metricsJsonStr = URLDecoder.decode(DeviceInfo.getMetrics(getContext()), "UTF-8");
+ final JSONObject expectedMetrics = new JSONObject(metricsJsonStr);
+ assertEquals(expectedMetrics.length(), actualMetrics.length());
+ final Iterator actualMetricsKeyIterator = actualMetrics.keys();
+ while (actualMetricsKeyIterator.hasNext()) {
+ final String key = (String) actualMetricsKeyIterator.next();
+ assertEquals(expectedMetrics.get(key), actualMetrics.get(key));
+ }
+ }
+
+ public void testUpdateSession_checkInternalState() {
+ try {
+ freshConnQ.updateSession(15);
+ fail("expected IllegalStateException when internal state is not set up");
+ } catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testUpdateSession_zeroDuration() {
+ connQ.updateSession(0);
+ verifyZeroInteractions(connQ.getExecutor(), connQ.getCountlyStore());
+ }
+
+ public void testUpdateSession_negativeDuration() {
+ connQ.updateSession(-1);
+ verifyZeroInteractions(connQ.getExecutor(), connQ.getCountlyStore());
+ }
+
+ public void testUpdateSession_moreThanZeroDuration() {
+ connQ.updateSession(60);
+ final ArgumentCaptor arg = ArgumentCaptor.forClass(String.class);
+ verify(connQ.getCountlyStore()).addConnection(arg.capture());
+ verify(connQ.getExecutor()).submit(any(ConnectionProcessor.class));
+
+ // verify query parameters
+ final String queryStr = arg.getValue();
+ final Map queryParams = parseQueryParams(queryStr);
+ assertEquals(connQ.getAppKey(), queryParams.get("app_key"));
+ assertNull(queryParams.get("device_id"));
+ final long curTimestamp = Seeds.currentTimestamp();
+ final int actualTimestamp = Integer.parseInt(queryParams.get("timestamp"));
+ // this check attempts to account for minor time changes during this ly.count.android.sdk.test
+ assertTrue(((curTimestamp-1) <= actualTimestamp) && ((curTimestamp+1) >= actualTimestamp));
+ assertEquals("60", queryParams.get("session_duration"));
+ }
+
+ public void testEndSession_checkInternalState() {
+ try {
+ freshConnQ.endSession(15);
+ fail("expected IllegalStateException when internal state is not set up");
+ } catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testEndSession_zeroDuration() {
+ connQ.endSession(0);
+ final ArgumentCaptor arg = ArgumentCaptor.forClass(String.class);
+ verify(connQ.getCountlyStore()).addConnection(arg.capture());
+ verify(connQ.getExecutor()).submit(any(ConnectionProcessor.class));
+
+ // verify query parameters
+ final String queryStr = arg.getValue();
+ final Map queryParams = parseQueryParams(queryStr);
+ assertEquals(connQ.getAppKey(), queryParams.get("app_key"));
+ assertNull(queryParams.get("device_id"));
+ final long curTimestamp = Seeds.currentTimestamp();
+ final int actualTimestamp = Integer.parseInt(queryParams.get("timestamp"));
+ // this check attempts to account for minor time changes during this ly.count.android.sdk.test
+ assertTrue(((curTimestamp-1) <= actualTimestamp) && ((curTimestamp+1) >= actualTimestamp));
+ assertFalse(queryParams.containsKey("session_duration"));
+ assertEquals("1", queryParams.get("end_session"));
+ }
+
+ public void testEndSession_negativeDuration() {
+ connQ.endSession(-1);
+ final ArgumentCaptor arg = ArgumentCaptor.forClass(String.class);
+ verify(connQ.getCountlyStore()).addConnection(arg.capture());
+ verify(connQ.getExecutor()).submit(any(ConnectionProcessor.class));
+
+ // verify query parameters
+ final String queryStr = arg.getValue();
+ final Map queryParams = parseQueryParams(queryStr);
+ assertEquals(connQ.getAppKey(), queryParams.get("app_key"));
+ assertNull(queryParams.get("device_id"));
+ final long curTimestamp = Seeds.currentTimestamp();
+ final int actualTimestamp = Integer.parseInt(queryParams.get("timestamp"));
+ // this check attempts to account for minor time changes during this ly.count.android.sdk.test
+ assertTrue(((curTimestamp-1) <= actualTimestamp) && ((curTimestamp+1) >= actualTimestamp));
+ assertFalse(queryParams.containsKey("session_duration"));
+ assertEquals("1", queryParams.get("end_session"));
+ }
+
+ public void testEndSession_moreThanZeroDuration() {
+ connQ.endSession(15);
+ final ArgumentCaptor arg = ArgumentCaptor.forClass(String.class);
+ verify(connQ.getCountlyStore()).addConnection(arg.capture());
+ verify(connQ.getExecutor()).submit(any(ConnectionProcessor.class));
+
+ // verify query parameters
+ final String queryStr = arg.getValue();
+ final Map queryParams = parseQueryParams(queryStr);
+ assertEquals(connQ.getAppKey(), queryParams.get("app_key"));
+ assertNull(queryParams.get("device_id"));
+ final long curTimestamp = Seeds.currentTimestamp();
+ final int actualTimestamp = Integer.parseInt(queryParams.get("timestamp"));
+ // this check attempts to account for minor time changes during this ly.count.android.sdk.test
+ assertTrue(((curTimestamp-1) <= actualTimestamp) && ((curTimestamp+1) >= actualTimestamp));
+ assertEquals("1", queryParams.get("end_session"));
+ assertEquals("15", queryParams.get("session_duration"));
+ }
+
+ public void testRecordEvents_checkInternalState() {
+ try {
+ freshConnQ.recordEvents("blahblahblah");
+ fail("expected IllegalStateException when internal state is not set up");
+ } catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testRecordEvents() {
+ final String eventData = "blahblahblah";
+ connQ.recordEvents(eventData);
+ final ArgumentCaptor arg = ArgumentCaptor.forClass(String.class);
+ verify(connQ.getCountlyStore()).addConnection(arg.capture());
+ verify(connQ.getExecutor()).submit(any(ConnectionProcessor.class));
+
+ // verify query parameters
+ final String queryStr = arg.getValue();
+ final Map queryParams = parseQueryParams(queryStr);
+ assertEquals(connQ.getAppKey(), queryParams.get("app_key"));
+ assertNull(queryParams.get("device_id"));
+ final long curTimestamp = Seeds.currentTimestamp();
+ final int actualTimestamp = Integer.parseInt(queryParams.get("timestamp"));
+ // this check attempts to account for minor time changes during this ly.count.android.sdk.test
+ assertTrue(((curTimestamp - 1) <= actualTimestamp) && ((curTimestamp + 1) >= actualTimestamp));
+ assertEquals(eventData, queryParams.get("events"));
+ }
+
+ private Map parseQueryParams(final String queryStr) {
+ final String urlStr = "http://server?" + queryStr;
+ final Uri uri = Uri.parse(urlStr);
+ final Set queryParameterNames = uri.getQueryParameterNames();
+ final Map queryParams = new HashMap<>(queryParameterNames.size());
+ for (String paramName : queryParameterNames) {
+ queryParams.put(paramName, uri.getQueryParameter(paramName));
+ }
+ return queryParams;
+ }
+
+ public void testEnsureExecutor_nullExecutor() {
+ assertNull(freshConnQ.getExecutor());
+ freshConnQ.ensureExecutor();
+ assertNotNull(freshConnQ.getExecutor());
+ }
+
+ public void testEnsureExecutor_alreadyHasExecutor() {
+ ExecutorService executor = connQ.getExecutor();
+ assertNotNull(executor);
+ connQ.ensureExecutor();
+ assertSame(executor, connQ.getExecutor());
+ }
+
+ public void testTick_storeHasNoConnections() {
+ when(connQ.getCountlyStore().isEmptyConnections()).thenReturn(true);
+ connQ.tick();
+ verifyZeroInteractions(connQ.getExecutor());
+ }
+
+ public void testTick_storeHasConnectionsAndFutureIsNull() {
+ final Future mockFuture = mock(Future.class);
+ when(connQ.getExecutor().submit(any(ConnectionProcessor.class))).thenReturn(mockFuture);
+ connQ.tick();
+ verify(connQ.getExecutor()).submit(any(ConnectionProcessor.class));
+ assertSame(mockFuture, connQ.getConnectionProcessorFuture());
+ }
+
+ public void testTick_checkConnectionProcessor() {
+ final ArgumentCaptor arg = ArgumentCaptor.forClass(Runnable.class);
+ when(connQ.getExecutor().submit(arg.capture())).thenReturn(null);
+ connQ.tick();
+ assertEquals(((ConnectionProcessor)arg.getValue()).getServerURL(), connQ.getServerURL());
+ assertSame(((ConnectionProcessor)arg.getValue()).getCountlyStore(), connQ.getCountlyStore());
+ }
+
+ public void testTick_storeHasConnectionsAndFutureIsDone() {
+ final Future> mockFuture = mock(Future.class);
+ when(mockFuture.isDone()).thenReturn(true);
+ connQ.setConnectionProcessorFuture(mockFuture);
+ final Future mockFuture2 = mock(Future.class);
+ when(connQ.getExecutor().submit(any(ConnectionProcessor.class))).thenReturn(mockFuture2);
+ connQ.tick();
+ verify(connQ.getExecutor()).submit(any(ConnectionProcessor.class));
+ assertSame(mockFuture2, connQ.getConnectionProcessorFuture());
+ }
+
+ public void testTick_storeHasConnectionsButFutureIsNotDone() {
+ final Future> mockFuture = mock(Future.class);
+ connQ.setConnectionProcessorFuture(mockFuture);
+ connQ.tick();
+ verifyZeroInteractions(connQ.getExecutor());
+ }
+}
diff --git a/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/CountlyStoreTests.java b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/CountlyStoreTests.java
new file mode 100755
index 000000000..78364b54a
--- /dev/null
+++ b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/CountlyStoreTests.java
@@ -0,0 +1,338 @@
+/*
+Copyright (c) 2012, 2013, 2014 Countly
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+package com.playseeds.android.sdk;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.test.AndroidTestCase;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+public class CountlyStoreTests extends AndroidTestCase {
+ CountlyStore store;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ store = new CountlyStore(getContext());
+ store.clear();
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ store.clear();
+ super.tearDown();
+ }
+
+ public void testConstructor_nullContext() {
+ try {
+ new CountlyStore(null);
+ fail("expected IllegalArgumentException when calling CountlyStore() ctor with null context");
+ } catch (IllegalArgumentException ignored) {
+ // success!
+ }
+ }
+
+ public void testConstructor() {
+ Context mockContext = mock(Context.class);
+ new CountlyStore(mockContext);
+ verify(mockContext).getSharedPreferences("COUNTLY_STORE", Context.MODE_PRIVATE);
+ }
+
+ public void testConnections_prefIsNull() {
+ // the clear() call in setUp ensures the pref is not present
+ assertTrue(Arrays.equals(new String[0], store.connections()));
+ }
+
+ public void testConnections_prefIsEmptyString() {
+ // the following two calls will result in the pref being an empty string
+ final String connStr = "blah";
+ store.addConnection(connStr);
+ store.removeConnection(connStr);
+ assertTrue(Arrays.equals(new String[0], store.connections()));
+ }
+
+ public void testConnections_prefHasSingleValue() {
+ final String connStr = "blah";
+ store.addConnection(connStr);
+ assertTrue(Arrays.equals(new String[]{connStr}, store.connections()));
+ }
+
+ public void testConnections_prefHasTwoValues() {
+ final String connStr1 = "blah1";
+ final String connStr2 = "blah2";
+ store.addConnection(connStr1);
+ store.addConnection(connStr2);
+ assertTrue(Arrays.equals(new String[]{connStr1,connStr2}, store.connections()));
+ }
+
+ public void testEvents_prefIsNull() {
+ // the clear() call in setUp ensures the pref is not present
+ assertTrue(Arrays.equals(new String[0], store.events()));
+ }
+
+ public void testEvents_prefIsEmptyString() {
+ // the following two calls will result in the pref being an empty string
+ store.addEvent("eventKey", null, Seeds.currentTimestamp(), 1, 0.0d);
+ store.removeEvents(store.eventsList());
+ assertTrue(Arrays.equals(new String[0], store.events()));
+ }
+
+ public void testEvents_prefHasSingleValue() throws JSONException {
+ final String eventKey = "eventKey";
+ store.addEvent(eventKey, null, Seeds.currentTimestamp(), 1, 0.0d);
+ final String[] eventJSONStrs = store.events();
+ final JSONObject eventJSONObj = new JSONObject(eventJSONStrs[0]);
+ assertEquals(eventKey, eventJSONObj.getString("key"));
+ // this is good enough, we verify the entire JSON content is written in later unit tests
+ }
+
+ public void testEvents_prefHasTwoValues() throws JSONException {
+ final String eventKey1 = "eventKey1";
+ final String eventKey2 = "eventKey2";
+ store.addEvent(eventKey1, null, Seeds.currentTimestamp(), 1, 0.0d);
+ store.addEvent(eventKey2, null, Seeds.currentTimestamp(), 1, 0.0d);
+ final String[] eventJSONStrs = store.events();
+ final JSONObject eventJSONObj1 = new JSONObject(eventJSONStrs[0]);
+ assertEquals(eventKey1, eventJSONObj1.getString("key"));
+ final JSONObject eventJSONObj2 = new JSONObject(eventJSONStrs[1]);
+ assertEquals(eventKey2, eventJSONObj2.getString("key"));
+ // this is good enough, we verify the entire JSON content is written in later unit tests
+ }
+
+ public void testEventsList_noEvents() {
+ assertEquals(new ArrayList(0), store.eventsList());
+ }
+
+ public void testEventsList_singleEvent() {
+ final Event event1 = new Event();
+ event1.key = "eventKey1";
+ event1.timestamp = Seeds.currentTimestamp();
+ event1.count = 1;
+ store.addEvent(event1.key, event1.segmentation, event1.timestamp, event1.count, event1.sum);
+ final List expected = new ArrayList(1);
+ expected.add(event1);
+ final List actual = store.eventsList();
+ assertEquals(expected, actual);
+ }
+
+ public void testEventsList_sortingOfMultipleEvents() {
+ final Event event1 = new Event();
+ event1.key = "eventKey1";
+ event1.timestamp = Seeds.currentTimestamp();
+ event1.count = 1;
+ final Event event2 = new Event();
+ event2.key = "eventKey2";
+ event2.timestamp = Seeds.currentTimestamp() - 60;
+ event2.count = 1;
+ final Event event3 = new Event();
+ event3.key = "eventKey3";
+ event3.timestamp = Seeds.currentTimestamp() - 30;
+ event3.count = 1;
+ store.addEvent(event1.key, event1.segmentation, event1.timestamp, event1.count, event1.sum);
+ store.addEvent(event2.key, event2.segmentation, event2.timestamp, event2.count, event2.sum);
+ store.addEvent(event3.key, event3.segmentation, event3.timestamp, event3.count, event3.sum);
+ final List expected = new ArrayList(3);
+ expected.add(event2);
+ expected.add(event3);
+ expected.add(event1);
+ final List actual = store.eventsList();
+ assertEquals(expected, actual);
+ }
+
+ public void testEventsList_badJSON() {
+ final Event event1 = new Event();
+ event1.key = "eventKey1";
+ event1.timestamp = Seeds.currentTimestamp() - 60;
+ event1.count = 1;
+ final Event event2 = new Event();
+ event2.key = "eventKey2";
+ event2.timestamp = Seeds.currentTimestamp();
+ event2.count = 1;
+
+ final String joinedEventsWithBadJSON = event1.toJSON().toString() + "===blah===" + event2.toJSON().toString();
+ final SharedPreferences prefs = getContext().getSharedPreferences("COUNTLY_STORE", Context.MODE_PRIVATE);
+ prefs.edit().putString("EVENTS", joinedEventsWithBadJSON).commit();
+
+ final List expected = new ArrayList(2);
+ expected.add(event1);
+ expected.add(event2);
+ final List actual = store.eventsList();
+ assertNotSame(expected, actual);
+ }
+
+ public void testEventsList_EventFromJSONReturnsNull() {
+ final Event event1 = new Event();
+ event1.key = "eventKey1";
+ event1.timestamp = Seeds.currentTimestamp() - 60;
+ event1.count = 1;
+ final Event event2 = new Event();
+ event2.key = "eventKey2";
+ event2.timestamp = Seeds.currentTimestamp();
+ event2.count = 1;
+
+ final String joinedEventsWithBadJSON = event1.toJSON().toString() + "==={\"key\":null}==" + event2.toJSON().toString();
+ final SharedPreferences prefs = getContext().getSharedPreferences("COUNTLY_STORE", Context.MODE_PRIVATE);
+ prefs.edit().putString("EVENTS", joinedEventsWithBadJSON).commit();
+
+ final List expected = new ArrayList(2);
+ expected.add(event1);
+ expected.add(event2);
+ final List actual = store.eventsList();
+ assertNotSame(expected, actual);
+ }
+
+ public void testIsEmptyConnections_prefIsNull() {
+ // the clear() call in setUp ensures the pref is not present
+ assertTrue(store.isEmptyConnections());
+ }
+
+ public void testIsEmptyConnections_prefIsEmpty() {
+ // the following two calls will result in the pref being an empty string
+ final String connStr = "blah";
+ store.addConnection(connStr);
+ store.removeConnection(connStr);
+ assertTrue(store.isEmptyConnections());
+ }
+
+ public void testIsEmptyConnections_prefIsPopulated() {
+ final String connStr = "blah";
+ store.addConnection(connStr);
+ assertFalse(store.isEmptyConnections());
+ }
+
+ public void testAddConnection_nullStr() {
+ store.addConnection(null);
+ assertTrue(store.isEmptyConnections());
+ }
+
+ public void testAddConnection_emptyStr() {
+ store.addConnection("");
+ assertTrue(store.isEmptyConnections());
+ }
+
+ public void testRemoveConnection_nullStr() {
+ store.addConnection("blah");
+ store.removeConnection(null);
+ assertFalse(store.isEmptyConnections());
+ }
+
+ public void testRemoveConnection_emptyStr() {
+ store.addConnection("blah");
+ store.removeConnection("");
+ assertFalse(store.isEmptyConnections());
+ }
+
+ public void testRemoveConnection_firstConn() {
+ store.addConnection("blah");
+ assertFalse(store.isEmptyConnections());
+ store.removeConnection("blah");
+ assertTrue(store.isEmptyConnections());
+ }
+
+ public void testRemoveConnection_notFirstConn() {
+ store.addConnection("blah1");
+ store.addConnection("blah2");
+ assertEquals(2, store.connections().length);
+ store.removeConnection("blah2");
+ assertEquals(1, store.connections().length);
+ }
+
+ public void testRemoveConnection_onlyRemovesFirstMatchingOne() {
+ store.addConnection("blah1");
+ store.addConnection("blah2");
+ store.addConnection("blah1");
+ assertEquals(3, store.connections().length);
+ store.removeConnection("blah1");
+ assertTrue(Arrays.equals(new String[]{"blah2", "blah1"}, store.connections()));
+ }
+
+ public void testAddEvent() {
+ final Event event1 = new Event();
+ event1.key = "eventKey1";
+ event1.timestamp = Seeds.currentTimestamp() - 60;
+ event1.count = 42;
+ event1.sum = 3.2;
+ event1.segmentation = new HashMap(2);
+ event1.segmentation.put("segKey1", "segValue1");
+ event1.segmentation.put("segKey2", "segValue2");
+
+ store.addEvent(event1.key, event1.segmentation, event1.timestamp, event1.count, event1.sum);
+
+ final List addedEvents = store.eventsList();
+ assertEquals(1, addedEvents.size());
+ final Event addedEvent = addedEvents.get(0);
+ assertEquals(event1, addedEvent);
+ assertEquals(event1.count, addedEvent.count);
+ assertEquals(event1.sum, addedEvent.sum);
+ }
+
+ public void testRemoveEvents() {
+ final Event event1 = new Event();
+ event1.key = "eventKey1";
+ event1.timestamp = Seeds.currentTimestamp() - 60;
+ event1.count = 1;
+ final Event event2 = new Event();
+ event2.key = "eventKey2";
+ event2.timestamp = Seeds.currentTimestamp() - 30;
+ event2.count = 1;
+ final Event event3 = new Event();
+ event3.key = "eventKey2";
+ event3.timestamp = Seeds.currentTimestamp();
+ event3.count = 1;
+
+ store.addEvent(event1.key, event1.segmentation, event1.timestamp, event1.count, event1.sum);
+ store.addEvent(event2.key, event2.segmentation, event2.timestamp, event2.count, event2.sum);
+
+ final List eventsToRemove = store.eventsList();
+
+ store.addEvent(event3.key, event3.segmentation, event3.timestamp, event3.count, event3.sum);
+
+ store.removeEvents(eventsToRemove);
+
+ final List events = store.eventsList();
+ assertEquals(1, events.size());
+ assertEquals(event3, events.get(0));
+ }
+
+ public void testClear() {
+ final SharedPreferences prefs = getContext().getSharedPreferences("COUNTLY_STORE", Context.MODE_PRIVATE);
+ assertFalse(prefs.contains("EVENTS"));
+ assertFalse(prefs.contains("CONNECTIONS"));
+ store.addConnection("blah");
+ store.addEvent("eventKey", null, Seeds.currentTimestamp(), 1, 0.0d);
+ assertTrue(prefs.contains("EVENTS"));
+ assertTrue(prefs.contains("CONNECTIONS"));
+ store.clear();
+ assertFalse(prefs.contains("EVENTS"));
+ assertFalse(prefs.contains("CONNECTIONS"));
+ }
+}
diff --git a/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/CountlyTests.java b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/CountlyTests.java
new file mode 100755
index 000000000..4b1ea6f2d
--- /dev/null
+++ b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/CountlyTests.java
@@ -0,0 +1,652 @@
+/*
+Copyright (c) 2012, 2013, 2014 Countly
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+package com.playseeds.android.sdk;
+
+import android.content.Context;
+import android.test.AndroidTestCase;
+
+import java.util.HashMap;
+
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+
+public class CountlyTests extends AndroidTestCase {
+ Seeds mUninitedSeeds;
+ Seeds mSeeds;
+ ConnectionQueue mockConnectionQueue;
+ EventQueue mockEventQueue;
+ String eventKey;
+ Context context;
+ String serverUrl;
+ String appKey;
+ String deviceId;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ context = getContext();
+ serverUrl = "http://ly.count.android.sdk.test.count.ly";
+ appKey = "appkey";
+ deviceId = "1234";
+ mUninitedSeeds = new Seeds();
+ mSeeds = new Seeds();
+ mockEventQueue = mock(EventQueue.class);
+ mockConnectionQueue = mock(ConnectionQueue.class);
+ final CountlyStore countlyStore = new CountlyStore(context);
+ countlyStore.clear();
+
+ mSeeds.init(context, null, null, serverUrl, appKey, deviceId);
+ mockConnectionQueue.setContext(context);
+ mockConnectionQueue.setAppKey("123456");
+ mockConnectionQueue.setServerURL(serverUrl);
+ mockConnectionQueue.setCountlyStore(mock(CountlyStore.class));
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testConstructor() {
+ assertNotNull(mUninitedSeeds.getConnectionQueue());
+ assertNull(mUninitedSeeds.getConnectionQueue().getContext());
+ assertNull(mUninitedSeeds.getConnectionQueue().getServerURL());
+ assertNull(mUninitedSeeds.getConnectionQueue().getAppKey());
+ assertNull(mUninitedSeeds.getConnectionQueue().getCountlyStore());
+ assertNotNull(mUninitedSeeds.getTimerService());
+ assertNull(mUninitedSeeds.getEventQueue());
+ assertEquals(0, mUninitedSeeds.getActivityCount());
+ assertEquals(0, mUninitedSeeds.getPrevSessionDurationStartTime());
+ assertFalse(mUninitedSeeds.getDisableUpdateSessionRequests());
+ assertFalse(mUninitedSeeds.isLoggingEnabled());
+ }
+
+ public void testSharedInstance() {
+ Seeds sharedSeeds = Seeds.sharedInstance();
+ assertNotNull(sharedSeeds);
+ assertSame(sharedSeeds, Seeds.sharedInstance());
+ }
+
+ public void testInitWithNoDeviceID() {
+ mUninitedSeeds = spy(mUninitedSeeds);
+ mUninitedSeeds.init(context, null, null, serverUrl, appKey, null);
+ verify(mUninitedSeeds).init(context, null, null, serverUrl, appKey, null);
+ }
+
+ public void testInit_nullContext() {
+ try {
+ mUninitedSeeds.init(null, null, null, serverUrl, appKey, deviceId);
+ fail("expected null context to throw IllegalArgumentException");
+ } catch (IllegalArgumentException ignored) {
+ // success!
+ }
+ }
+
+ public void testInit_nullServerURL() {
+ try {
+ mUninitedSeeds.init(context, null, null, appKey, deviceId);
+ fail("expected null server URL to throw IllegalArgumentException");
+ } catch (IllegalArgumentException ignored) {
+ // success!
+ }
+ }
+
+ public void testInit_emptyServerURL() {
+ try {
+ mUninitedSeeds.init(context, null, null, "", appKey, deviceId);
+ fail("expected empty server URL to throw IllegalArgumentException");
+ } catch (IllegalArgumentException ignored) {
+ // success!
+ }
+ }
+
+ public void testInit_invalidServerURL() {
+ try {
+ mUninitedSeeds.init(context, null, null, "not-a-valid-server-url", appKey, deviceId);
+ fail("expected invalid server URL to throw IllegalArgumentException");
+ } catch (IllegalArgumentException ignored) {
+ // success!
+ }
+ }
+
+ public void testInit_nullAppKey() {
+ try {
+ mUninitedSeeds.init(context, null, null, serverUrl, null, deviceId);
+ fail("expected null app key to throw IllegalArgumentException");
+ } catch (IllegalArgumentException ignored) {
+ // success!
+ }
+ }
+
+ public void testInit_emptyAppKey() {
+ try {
+ mUninitedSeeds.init(context, null, null, serverUrl, "", deviceId);
+ fail("expected empty app key to throw IllegalArgumentException");
+ } catch (IllegalArgumentException ignored) {
+ // success!
+ }
+ }
+
+ public void testInit_nullDeviceID() {
+ // null device ID is okay because it tells Seeds to use OpenUDID
+ mUninitedSeeds.init(context, null, null, serverUrl, appKey, null);
+ }
+
+ public void testInit_emptyDeviceID() {
+ try {
+ mUninitedSeeds.init(context, null, null, serverUrl, appKey, "");
+ fail("expected empty device ID to throw IllegalArgumentException");
+ } catch (IllegalArgumentException ignored) {
+ // success!
+ }
+ }
+
+ public void testInit_twiceWithSameParams() {
+ mUninitedSeeds.init(context, null, null, serverUrl, appKey, deviceId);
+
+ final EventQueue expectedEventQueue = mUninitedSeeds.getEventQueue();
+ final ConnectionQueue expectedConnectionQueue = mUninitedSeeds.getConnectionQueue();
+ final CountlyStore expectedCountlyStore = expectedConnectionQueue.getCountlyStore();
+ assertNotNull(expectedEventQueue);
+ assertNotNull(expectedConnectionQueue);
+ assertNotNull(expectedCountlyStore);
+
+ // second call with same params should succeed, no exception thrown
+ mUninitedSeeds.init(getContext(), null, null, serverUrl, appKey, deviceId);
+
+ assertSame(expectedEventQueue, mUninitedSeeds.getEventQueue());
+ assertSame(expectedConnectionQueue, mUninitedSeeds.getConnectionQueue());
+ assertSame(expectedCountlyStore, mUninitedSeeds.getConnectionQueue().getCountlyStore());
+ assertSame(context, mUninitedSeeds.getConnectionQueue().getContext());
+ assertEquals(serverUrl, mUninitedSeeds.getConnectionQueue().getServerURL());
+ assertEquals(appKey, mUninitedSeeds.getConnectionQueue().getAppKey());
+ assertSame(mUninitedSeeds.getConnectionQueue().getCountlyStore(), mUninitedSeeds.getEventQueue().getCountlyStore());
+ }
+
+ public void testInit_twiceWithDifferentContext() {
+ mUninitedSeeds.init(context, null, null, serverUrl, appKey, deviceId);
+ // changing context is okay since SharedPrefs are global singletons
+ try {
+ mUninitedSeeds.init(mock(Context.class), null, null, serverUrl, appKey, deviceId);
+ } catch (Exception e) {
+ //success!
+ }
+ }
+
+ public void testInit_twiceWithDifferentServerURL() {
+ mUninitedSeeds.init(context, null, null, "http://test1.count.ly", appKey, deviceId);
+ try {
+ mUninitedSeeds.init(context, null, null, "http://test2.count.ly", appKey, deviceId);
+ fail("expected IllegalStateException to be thrown when calling init a second time with different serverURL");
+ }
+ catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testInit_twiceWithDifferentAppKey() {
+ mUninitedSeeds.init(context, null, null, serverUrl, "appkey1", deviceId);
+ try {
+ mUninitedSeeds.init(context, null, null, serverUrl, "appkey2", deviceId);
+ fail("expected IllegalStateException to be thrown when calling init a second time with different serverURL");
+ }
+ catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testInit_twiceWithDifferentDeviceID() {
+ mUninitedSeeds.init(context, null, null, serverUrl, appKey, deviceId);
+ try {
+ mUninitedSeeds.init(context, null, null, serverUrl, appKey, "4321");
+ fail("expected IllegalStateException to be thrown when calling init a second time with different serverURL");
+ }
+ catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testInit_normal() {
+ mUninitedSeeds.init(getContext(), null, null, serverUrl, appKey, deviceId);
+
+ assertSame(getContext(), mUninitedSeeds.getConnectionQueue().getContext());
+ assertEquals(serverUrl, mUninitedSeeds.getConnectionQueue().getServerURL());
+ assertEquals(appKey, mUninitedSeeds.getConnectionQueue().getAppKey());
+ assertNotNull(mUninitedSeeds.getConnectionQueue().getCountlyStore());
+ assertNotNull(mUninitedSeeds.getEventQueue());
+ assertSame(mUninitedSeeds.getConnectionQueue().getCountlyStore(), mUninitedSeeds.getEventQueue().getCountlyStore());
+ }
+
+ public void testHalt_notInitialized() {
+ mUninitedSeeds.halt();
+ assertNotNull(mUninitedSeeds.getConnectionQueue());
+ assertNull(mUninitedSeeds.getConnectionQueue().getContext());
+ assertNull(mUninitedSeeds.getConnectionQueue().getServerURL());
+ assertNull(mUninitedSeeds.getConnectionQueue().getAppKey());
+ assertNull(mUninitedSeeds.getConnectionQueue().getCountlyStore());
+ assertNotNull(mUninitedSeeds.getTimerService());
+ assertNull(mUninitedSeeds.getEventQueue());
+ assertEquals(0, mUninitedSeeds.getActivityCount());
+ assertEquals(0, mUninitedSeeds.getPrevSessionDurationStartTime());
+ }
+
+ public void testHalt() {
+ final CountlyStore mockCountlyStore = mock(CountlyStore.class);
+ mSeeds.getConnectionQueue().setCountlyStore(mockCountlyStore);
+ mSeeds.onStart();
+ assertTrue(0 != mSeeds.getPrevSessionDurationStartTime());
+ assertTrue(0 != mSeeds.getActivityCount());
+ assertNotNull(mSeeds.getEventQueue());
+ assertNotNull(mSeeds.getConnectionQueue().getContext());
+ assertNotNull(mSeeds.getConnectionQueue().getServerURL());
+ assertNotNull(mSeeds.getConnectionQueue().getAppKey());
+ assertNotNull(mSeeds.getConnectionQueue().getContext());
+
+ mSeeds.halt();
+
+ assertNotNull(mSeeds.getConnectionQueue());
+ assertNull(mSeeds.getConnectionQueue().getContext());
+ assertNull(mSeeds.getConnectionQueue().getServerURL());
+ assertNull(mSeeds.getConnectionQueue().getAppKey());
+ assertNull(mSeeds.getConnectionQueue().getCountlyStore());
+ assertNotNull(mSeeds.getTimerService());
+ assertNull(mSeeds.getEventQueue());
+ assertEquals(0, mSeeds.getActivityCount());
+ assertEquals(0, mSeeds.getPrevSessionDurationStartTime());
+ }
+
+ public void testOnStart_initNotCalled() {
+ try {
+ mUninitedSeeds.onStart();
+ fail("expected calling onStart before init to throw IllegalStateException");
+ } catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testOnStart_firstCall() {
+ mSeeds.setConnectionQueue(mockConnectionQueue);
+ mSeeds.onStart();
+
+ assertEquals(1, mSeeds.getActivityCount());
+ final long prevSessionDurationStartTime = mSeeds.getPrevSessionDurationStartTime();
+ assertTrue(prevSessionDurationStartTime > 0);
+ assertTrue(prevSessionDurationStartTime <= System.nanoTime());
+ }
+
+ public void testOnStart_subsequentCall() {
+ mSeeds.setConnectionQueue(mockConnectionQueue);
+ mSeeds.onStart(); // first call to onStart
+ final long prevSessionDurationStartTime = mSeeds.getPrevSessionDurationStartTime();
+ mSeeds.onStart(); // second call to onStart
+
+ assertEquals(2, mSeeds.getActivityCount());
+ assertEquals(prevSessionDurationStartTime, mSeeds.getPrevSessionDurationStartTime());
+ }
+
+ public void testOnStop_initNotCalled() {
+ try {
+ mUninitedSeeds.onStop();
+ fail("expected calling onStop before init to throw IllegalStateException");
+ } catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testOnStop_unbalanced() {
+ try {
+ mSeeds.onStop();
+ fail("expected calling onStop before init to throw IllegalStateException");
+ } catch (IllegalStateException ignored) {
+ // success!
+ }
+ }
+
+ public void testOnStop_reallyStopping_emptyEventQueue() {
+ mSeeds.setConnectionQueue(mockConnectionQueue);
+ mSeeds.onStart();
+ mSeeds.onStop();
+
+ assertEquals(0, mSeeds.getActivityCount());
+ assertEquals(0, mSeeds.getPrevSessionDurationStartTime());
+ }
+
+ public void testOnStop_reallyStopping_nonEmptyEventQueue() {
+ mSeeds.setConnectionQueue(mockConnectionQueue);
+ mSeeds.setEventQueue(mockEventQueue);
+ mSeeds.onStart();
+ mSeeds.onStop();
+
+ assertEquals(0, mSeeds.getActivityCount());
+ assertEquals(0, mSeeds.getPrevSessionDurationStartTime());
+ }
+
+ public void testOnStop_notStopping() {
+ mSeeds.setConnectionQueue(mockConnectionQueue);
+
+ mSeeds.onStart();
+ mSeeds.onStart();
+ final long prevSessionDurationStartTime = mSeeds.getPrevSessionDurationStartTime();
+ mSeeds.onStop();
+
+ assertEquals(1, mSeeds.getActivityCount());
+ assertEquals(prevSessionDurationStartTime, mSeeds.getPrevSessionDurationStartTime());
+ }
+
+ public void testRecordEvent_keyOnly() {
+ eventKey = "eventKey";
+ final Seeds seeds = spy(mSeeds);
+ doNothing().when(seeds).recordEvent(eventKey, null, 1, 0.0d);
+ seeds.recordEvent(eventKey);
+ }
+
+ public void testRecordEvent_keyAndCount() {
+ eventKey = "eventKey";
+ final int count = 42;
+ final Seeds seeds = spy(mSeeds);
+ doNothing().when(seeds).recordEvent(eventKey, null, count, 0.0d);
+ seeds.recordEvent(eventKey, count);
+ }
+
+ public void testRecordEvent_keyAndCountAndSum() {
+ eventKey = "eventKey";
+ final int count = 42;
+ final double sum = 3.0d;
+ final Seeds seeds = spy(mSeeds);
+ doNothing().when(seeds).recordEvent(eventKey, null, count, sum);
+ seeds.recordEvent(eventKey, count, sum);
+ }
+
+ public void testRecordEvent_keyAndSegmentationAndCount() {
+ eventKey = "eventKey";
+ final int count = 42;
+ final HashMap segmentation = new HashMap<>(1);
+ segmentation.put("segkey1", "segvalue1");
+ final Seeds seeds = spy(mSeeds);
+ doNothing().when(seeds).recordEvent(eventKey, segmentation, count, 0.0d);
+ seeds.recordEvent(eventKey, segmentation, count);
+ }
+
+ public void testRecordEvent_initNotCalled() {
+ eventKey = "eventKey";
+ final int count = 42;
+ final double sum = 3.0d;
+ final HashMap segmentation = new HashMap<>(1);
+ segmentation.put("segkey1", "segvalue1");
+
+ try {
+ mUninitedSeeds.recordEvent(eventKey, segmentation, count, sum);
+ fail("expected IllegalStateException when recordEvent called before init");
+ } catch (IllegalStateException ignored) {
+ // success
+ }
+ }
+
+ public void testRecordEvent_nullKey() {
+ eventKey = null;
+ final int count = 42;
+ final double sum = 3.0d;
+ final HashMap segmentation = new HashMap<>(1);
+ segmentation.put("segkey1", "segvalue1");
+
+ try {
+ //noinspection ConstantConditions
+ mSeeds.recordEvent(eventKey, segmentation, count, sum);
+ fail("expected IllegalArgumentException when recordEvent called with null key");
+ } catch (IllegalArgumentException ignored) {
+ // success
+ }
+ }
+
+ public void testRecordEvent_emptyKey() {
+ eventKey = "";
+ final int count = 42;
+ final double sum = 3.0d;
+ final HashMap segmentation = new HashMap<>(1);
+ segmentation.put("segkey1", "segvalue1");
+
+ try {
+ mSeeds.recordEvent(eventKey, segmentation, count, sum);
+ fail("expected IllegalArgumentException when recordEvent called with empty key");
+ } catch (IllegalArgumentException ignored) {
+ // success
+ }
+ }
+
+ public void testRecordEvent_countIsZero() {
+ eventKey = "";
+ final int count = 0;
+ final double sum = 3.0d;
+ final HashMap segmentation = new HashMap<>(1);
+ segmentation.put("segkey1", "segvalue1");
+
+ try {
+ mSeeds.recordEvent(eventKey, segmentation, count, sum);
+ fail("expected IllegalArgumentException when recordEvent called with count=0");
+ } catch (IllegalArgumentException ignored) {
+ // success
+ }
+ }
+
+ public void testRecordEvent_countIsNegative() {
+ eventKey = "";
+ final int count = -1;
+ final double sum = 3.0d;
+ final HashMap segmentation = new HashMap<>(1);
+ segmentation.put("segkey1", "segvalue1");
+
+ try {
+ mSeeds.recordEvent(eventKey, segmentation, count, sum);
+ fail("expected IllegalArgumentException when recordEvent called with a negative count");
+ } catch (IllegalArgumentException ignored) {
+ // success
+ }
+ }
+
+ public void testRecordEvent_segmentationHasNullKey() {
+ eventKey = "";
+ final int count = 1;
+ final double sum = 3.0d;
+ final HashMap segmentation = new HashMap<>(1);
+ segmentation.put(null, "segvalue1");
+
+ try {
+ mSeeds.recordEvent(eventKey, segmentation, count, sum);
+ fail("expected IllegalArgumentException when recordEvent called with segmentation with null key");
+ } catch (IllegalArgumentException ignored) {
+ // success
+ }
+ }
+
+ public void testRecordEvent_segmentationHasEmptyKey() {
+ eventKey = "";
+ final int count = 1;
+ final double sum = 3.0d;
+ final HashMap segmentation = new HashMap<>(1);
+ segmentation.put("", "segvalue1");
+
+ try {
+ mSeeds.recordEvent(eventKey, segmentation, count, sum);
+ fail("expected IllegalArgumentException when recordEvent called with segmentation with empty key");
+ } catch (IllegalArgumentException ignored) {
+ // success
+ }
+ }
+
+ public void testRecordEvent_segmentationHasNullValue() {
+ eventKey = "";
+ final int count = 1;
+ final double sum = 3.0d;
+ final HashMap segmentation = new HashMap<>(1);
+ segmentation.put("segkey1", null);
+
+ try {
+ mSeeds.recordEvent(eventKey, segmentation, count, sum);
+ fail("expected IllegalArgumentException when recordEvent called with segmentation with null value");
+ } catch (IllegalArgumentException ignored) {
+ // success
+ }
+ }
+
+ public void testRecordEvent_segmentationHasEmptyValue() {
+ eventKey = "";
+ final int count = 1;
+ final double sum = 3.0d;
+ final HashMap segmentation = new HashMap<>(1);
+ segmentation.put("segkey1", "");
+
+ try {
+ mSeeds.recordEvent(eventKey, segmentation, count, sum);
+ fail("expected IllegalArgumentException when recordEvent called with segmentation with empty value");
+ } catch (IllegalArgumentException ignored) {
+ // success
+ }
+ }
+
+ public void testRecordEvent() {
+ eventKey = "eventKey";
+ final int count = 42;
+ final double sum = 3.0d;
+ final HashMap segmentation = new HashMap<>(1);
+ segmentation.put("segkey1", "segvalue1");
+
+ mSeeds.setEventQueue(mockEventQueue);
+
+ final Seeds seeds = spy(mSeeds);
+ doNothing().when(seeds).sendEventsIfNeeded();
+ seeds.recordEvent(eventKey, segmentation, count, sum);
+ }
+
+ public void testSendEventsIfNeeded_emptyQueue() {
+ mSeeds.setConnectionQueue(mockConnectionQueue);
+ mSeeds.setEventQueue(mockEventQueue);
+ mSeeds.sendEventsIfNeeded();
+ }
+
+ public void testSendEventsIfNeeded_lessThanThreshold() {
+ mSeeds.setConnectionQueue(mockConnectionQueue);
+ mSeeds.setEventQueue(mockEventQueue);
+ mSeeds.sendEventsIfNeeded();
+ }
+
+ public void testSendEventsIfNeeded_equalToThreshold() {
+ mSeeds.setConnectionQueue(mockConnectionQueue);
+ mSeeds.setEventQueue(mockEventQueue);
+ mSeeds.sendEventsIfNeeded();
+ }
+
+ public void testSendEventsIfNeeded_moreThanThreshold() {
+ mSeeds.setConnectionQueue(mockConnectionQueue);
+ mSeeds.setEventQueue(mockEventQueue);
+ mSeeds.sendEventsIfNeeded();
+ }
+
+ public void testOnTimer_noActiveSession() {
+ mSeeds.setConnectionQueue(mockConnectionQueue);
+ mSeeds.setEventQueue(mockEventQueue);
+ mSeeds.onTimer();
+ }
+
+ public void testOnTimer_activeSession_emptyEventQueue() {
+ mSeeds.setConnectionQueue(mockConnectionQueue);
+ mSeeds.setEventQueue(mockEventQueue);
+ mSeeds.onStart();
+ mSeeds.onTimer();
+ }
+
+ public void testOnTimer_activeSession_nonEmptyEventQueue() {
+ mSeeds.setConnectionQueue(mockConnectionQueue);
+ mSeeds.setEventQueue(mockEventQueue);
+ mSeeds.onStart();
+ mSeeds.onTimer();
+ }
+
+ public void testOnTimer_activeSession_emptyEventQueue_sessionTimeUpdatesDisabled() {
+ mSeeds.setConnectionQueue(mockConnectionQueue);
+ mSeeds.setDisableUpdateSessionRequests(true);
+ mSeeds.setEventQueue(mockEventQueue);
+ mSeeds.onStart();
+ mSeeds.onTimer();
+ }
+
+ public void testOnTimer_activeSession_nonEmptyEventQueue_sessionTimeUpdatesDisabled() {
+ mSeeds.setConnectionQueue(mockConnectionQueue);
+ mSeeds.setDisableUpdateSessionRequests(true);
+ mSeeds.setEventQueue(mockEventQueue);
+ mSeeds.onStart();
+ mSeeds.onTimer();
+ }
+
+ public void testRoundedSecondsSinceLastSessionDurationUpdate() {
+ long prevSessionDurationStartTime = System.nanoTime() - 1000000000;
+ mSeeds.setPrevSessionDurationStartTime(prevSessionDurationStartTime);
+ assertEquals(1, mSeeds.roundedSecondsSinceLastSessionDurationUpdate());
+
+ prevSessionDurationStartTime = System.nanoTime() - 2000000000;
+ mSeeds.setPrevSessionDurationStartTime(prevSessionDurationStartTime);
+ assertEquals(2, mSeeds.roundedSecondsSinceLastSessionDurationUpdate());
+
+ prevSessionDurationStartTime = System.nanoTime() - 1600000000;
+ mSeeds.setPrevSessionDurationStartTime(prevSessionDurationStartTime);
+ assertEquals(2, mSeeds.roundedSecondsSinceLastSessionDurationUpdate());
+
+ prevSessionDurationStartTime = System.nanoTime() - 1200000000;
+ mSeeds.setPrevSessionDurationStartTime(prevSessionDurationStartTime);
+ assertEquals(1, mSeeds.roundedSecondsSinceLastSessionDurationUpdate());
+ }
+
+ public void testIsValidURL_badURLs() {
+ assertFalse(Seeds.isValidURL(null));
+ assertFalse(Seeds.isValidURL(""));
+ assertFalse(Seeds.isValidURL(" "));
+ assertFalse(Seeds.isValidURL("blahblahblah.com"));
+ }
+
+ public void testIsValidURL_goodURL() {
+ assertTrue(Seeds.isValidURL(serverUrl));
+ }
+
+ public void testCurrentTimestamp() {
+ final int testTimestamp = (int) (System.currentTimeMillis() / 1000l);
+ final int actualTimestamp = Seeds.currentTimestamp();
+ assertTrue(((testTimestamp - 1) <= actualTimestamp) && ((testTimestamp + 1) >= actualTimestamp));
+ }
+
+ public void testSetDisableUpdateSessionRequests() {
+ assertFalse(mSeeds.getDisableUpdateSessionRequests());
+ mSeeds.setDisableUpdateSessionRequests(true);
+ assertTrue(mSeeds.getDisableUpdateSessionRequests());
+ mSeeds.setDisableUpdateSessionRequests(false);
+ assertFalse(mSeeds.getDisableUpdateSessionRequests());
+ }
+
+ public void testLoggingFlag() {
+ assertFalse(mUninitedSeeds.isLoggingEnabled());
+ mUninitedSeeds.setLoggingEnabled(true);
+ assertTrue(mUninitedSeeds.isLoggingEnabled());
+ mUninitedSeeds.setLoggingEnabled(false);
+ assertFalse(mUninitedSeeds.isLoggingEnabled());
+ }
+}
\ No newline at end of file
diff --git a/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/CrashDetailsTest.java b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/CrashDetailsTest.java
new file mode 100644
index 000000000..37cfeafd7
--- /dev/null
+++ b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/CrashDetailsTest.java
@@ -0,0 +1,87 @@
+package com.playseeds.android.sdk;
+
+import android.test.AndroidTestCase;
+
+import java.util.HashMap;
+
+public class CrashDetailsTest extends AndroidTestCase {
+
+ public void testAddLog() throws Exception {
+ String record = "This is a new log";
+ CrashDetails.addLog(record);
+ String logs = CrashDetails.getLogs();
+
+ assertEquals(record + "\n", logs);
+ assertNotSame(record, logs);
+ }
+
+ public void testAddLog_WhenNullRecord() throws Exception {
+ CrashDetails.addLog(null);
+ String logs = CrashDetails.getLogs();
+
+ assertNotSame(null, logs);
+ assertNotNull(logs);
+ }
+
+ public void testSetCustomSegments() throws Exception {
+ CrashDetails.setCustomSegments(new HashMap());
+
+ assertNull(CrashDetails.getCustomSegments());
+ }
+
+ public void testGetManufacturer() throws Exception {
+ assertNotNull(CrashDetails.getManufacturer());
+ }
+
+ public void testGetCpu() throws Exception {
+ assertNotNull(CrashDetails.getCpu());
+ }
+
+ public void testGetOpenGL() throws Exception {
+ assertNotNull(CrashDetails.getOpenGL(getContext()));
+ }
+
+ public void testGetRamCurrent() throws Exception {
+ assertNotNull(CrashDetails.getRamCurrent(getContext()));
+ }
+
+ public void testRamTotal() throws Exception {
+ assertNotNull(CrashDetails.getRamTotal());
+ }
+
+ public void testGetDiskCurrent() throws Exception {
+ assertNotNull(CrashDetails.getDiskCurrent());
+ }
+
+ public void testGetDiskTotal() throws Exception {
+ assertNotNull(CrashDetails.getDiskTotal());
+ }
+
+ public void testGetBatteryLevel() throws Exception {
+ assertNotNull(CrashDetails.getBatteryLevel(getContext()));
+ }
+
+ public void testGetRunningTime() throws Exception {
+ assertNotNull(CrashDetails.getRunningTime());
+ }
+
+ public void testGetOrientation() throws Exception {
+ assertNotNull(CrashDetails.getOrientation(getContext()));
+ }
+
+ public void testIsRooted() throws Exception {
+ assertNotNull(CrashDetails.isRooted());
+ }
+
+ public void testIsOnline() throws Exception {
+ assertNotNull(CrashDetails.isOnline(getContext()));
+ }
+
+ public void testIsMuted() throws Exception {
+ assertNotNull(CrashDetails.isMuted(getContext()));
+ }
+
+ public void testGetCrashData() throws Exception {
+ assertNotNull(CrashDetails.getCrashData(getContext(), "Error message", false));
+ }
+}
diff --git a/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/DeviceIdTests.java b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/DeviceIdTests.java
new file mode 100644
index 000000000..abce65ed1
--- /dev/null
+++ b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/DeviceIdTests.java
@@ -0,0 +1,76 @@
+package com.playseeds.android.sdk;
+
+import android.test.AndroidTestCase;
+
+public class DeviceIdTests extends AndroidTestCase {
+ DeviceId deviceId;
+ DeviceId.Type deviceType;
+ boolean exceptionThrown;
+ String id;
+
+ protected void setUp() throws Exception {
+ exceptionThrown = false;
+ id = "Nexus-XLR";
+ deviceType = null;
+ }
+
+ public void testDeviceIdConstructor_WhenNullParameter() throws Exception {
+ try {
+ deviceId = new DeviceId(deviceType);
+ } catch (IllegalStateException e) {
+ exceptionThrown = true;
+ }
+
+ assertTrue(exceptionThrown);
+ }
+
+ public void testDeviceIdConstructor_WhenTypeIsDeveloperSupplied() throws Exception {
+ deviceType = DeviceId.Type.DEVELOPER_SUPPLIED;
+
+ try {
+ deviceId = new DeviceId(deviceType);
+ } catch (IllegalStateException e) {
+ exceptionThrown = true;
+ }
+
+ assertTrue(exceptionThrown);
+ }
+
+ public void testDeviceIdConstructor_WhenDeveloperSuppliedIsEmpty() throws Exception {
+ id = "";
+
+ try {
+ deviceId = new DeviceId(id);
+ } catch (IllegalStateException e) {
+ exceptionThrown= true;
+ }
+
+ assertTrue(exceptionThrown);
+ }
+
+ public void testDeviceIdConstructor_WhenDeveloperSupplied() throws Exception {
+ try {
+ deviceId = new DeviceId(id);
+ } catch(IllegalStateException e) {
+ exceptionThrown = true;
+ }
+
+ assertFalse(exceptionThrown);
+ }
+
+ public void testDeviceIdEqualsNullSafe() throws Exception {
+ deviceType = DeviceId.Type.ADVERTISING_ID;
+
+ assertTrue(DeviceId.deviceIDEqualsNullSafe(id, deviceType, new DeviceId(deviceType)));
+ }
+
+ public void testDeviceIdEqualsNullSafe_WhenIdIsNull() throws Exception {
+ deviceType = DeviceId.Type.ADVERTISING_ID;
+
+ assertTrue(DeviceId.deviceIDEqualsNullSafe(null, deviceType, new DeviceId(deviceType)));
+ }
+
+ public void testDeviceIdEqualsNullSafe_WhenTypeIsNull() throws Exception {
+ assertFalse(DeviceId.deviceIDEqualsNullSafe(id, deviceType, new DeviceId(DeviceId.Type.OPEN_UDID)));
+ }
+}
diff --git a/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/DeviceInfoTests.java b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/DeviceInfoTests.java
new file mode 100755
index 000000000..d76f924ab
--- /dev/null
+++ b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/DeviceInfoTests.java
@@ -0,0 +1,218 @@
+/*
+Copyright (c) 2012, 2013, 2014 Countly
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+package com.playseeds.android.sdk;
+
+import android.content.Context;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.res.Resources;
+import android.telephony.TelephonyManager;
+import android.test.AndroidTestCase;
+import android.util.DisplayMetrics;
+import android.view.WindowManager;
+
+import junit.framework.Assert;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.Locale;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
+public class DeviceInfoTests extends AndroidTestCase {
+ Context mockContext;
+
+ protected void setUp() throws Exception {
+ mockContext = mock(Context.class);
+ }
+
+ public void testGetOS() {
+ Assert.assertEquals("Android", DeviceInfo.getOS());
+ }
+
+ public void testGetOSVersion() {
+ assertEquals(android.os.Build.VERSION.RELEASE, DeviceInfo.getOSVersion());
+ }
+
+ public void testGetDevice() {
+ assertEquals(android.os.Build.MODEL, DeviceInfo.getDevice());
+ }
+
+ public void testGetResolution() {
+ final DisplayMetrics metrics = new DisplayMetrics();
+ ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
+ final String expected = metrics.widthPixels + "x" + metrics.heightPixels;
+ assertEquals(expected, DeviceInfo.getResolution(getContext()));
+ }
+
+ public void testGetResolution_getWindowManagerReturnsNull() {
+ when(mockContext.getSystemService(Context.WINDOW_SERVICE)).thenReturn(null);
+ assertEquals("", DeviceInfo.getResolution(mockContext));
+ }
+
+ public void testGetResolution_getDefaultDisplayReturnsNull() {
+ final WindowManager mockWindowMgr = mock(WindowManager.class);
+
+ when(mockWindowMgr.getDefaultDisplay()).thenReturn(null);
+ when(mockContext.getSystemService(Context.WINDOW_SERVICE)).thenReturn(mockWindowMgr);
+ assertEquals("", DeviceInfo.getResolution(mockContext));
+ }
+
+ private Context mockContextForTestingDensity(final int density) {
+ final DisplayMetrics metrics = new DisplayMetrics();
+ final Resources mockResources = mock(Resources.class);
+ metrics.densityDpi = density;
+
+ when(mockResources.getDisplayMetrics()).thenReturn(metrics);
+ when(mockContext.getResources()).thenReturn(mockResources);
+ return mockContext;
+ }
+
+ public void testGetDensity() {
+ mockContext = mockContextForTestingDensity(DisplayMetrics.DENSITY_LOW);
+ assertEquals("LDPI", DeviceInfo.getDensity(mockContext));
+ mockContext = mockContextForTestingDensity(DisplayMetrics.DENSITY_MEDIUM);
+ assertEquals("MDPI", DeviceInfo.getDensity(mockContext));
+ mockContext = mockContextForTestingDensity(DisplayMetrics.DENSITY_TV);
+ assertEquals("TVDPI", DeviceInfo.getDensity(mockContext));
+ mockContext = mockContextForTestingDensity(DisplayMetrics.DENSITY_HIGH);
+ assertEquals("HDPI", DeviceInfo.getDensity(mockContext));
+ mockContext = mockContextForTestingDensity(DisplayMetrics.DENSITY_XHIGH);
+ assertEquals("XHDPI", DeviceInfo.getDensity(mockContext));
+ mockContext = mockContextForTestingDensity(DisplayMetrics.DENSITY_XXHIGH);
+ assertEquals("XXHDPI", DeviceInfo.getDensity(mockContext));
+ mockContext = mockContextForTestingDensity(DisplayMetrics.DENSITY_XXXHIGH);
+ assertEquals("XXXHDPI", DeviceInfo.getDensity(mockContext));
+ mockContext = mockContextForTestingDensity(DisplayMetrics.DENSITY_400);
+ assertEquals("XMHDPI", DeviceInfo.getDensity(mockContext));
+ mockContext = mockContextForTestingDensity(0);
+ assertEquals("", DeviceInfo.getDensity(mockContext));
+ }
+
+ public void testGetCarrier_nullTelephonyManager() {
+ when(mockContext.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(null);
+ assertEquals("", DeviceInfo.getCarrier(mockContext));
+ }
+
+ public void testGetCarrier_nullNetOperator() {
+ final TelephonyManager mockTelephonyManager = mock(TelephonyManager.class);
+
+ when(mockTelephonyManager.getNetworkOperatorName()).thenReturn(null);
+ when(mockContext.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mockTelephonyManager);
+ assertEquals("", DeviceInfo.getCarrier(mockContext));
+ }
+
+ public void testGetCarrier_emptyNetOperator() {
+ final TelephonyManager mockTelephonyManager = mock(TelephonyManager.class);
+
+ when(mockTelephonyManager.getNetworkOperatorName()).thenReturn("");
+ when(mockContext.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mockTelephonyManager);
+ assertEquals("", DeviceInfo.getCarrier(mockContext));
+ }
+
+ public void testGetCarrier() {
+ final TelephonyManager mockTelephonyManager = mock(TelephonyManager.class);
+
+ when(mockTelephonyManager.getNetworkOperatorName()).thenReturn("Verizon");
+ when(mockContext.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mockTelephonyManager);
+ assertEquals("Verizon", DeviceInfo.getCarrier(mockContext));
+ }
+
+ public void testGetLocale() {
+ final Locale defaultLocale = Locale.getDefault();
+ try {
+ Locale.setDefault(new Locale("ab", "CD"));
+ assertEquals("ab_CD", DeviceInfo.getLocale());
+ } finally {
+ Locale.setDefault(defaultLocale);
+ }
+ }
+
+ public void testGetAppVersion() throws PackageManager.NameNotFoundException {
+ final PackageInfo pkgInfo = new PackageInfo();
+ final String fakePkgName = "i.like.chicken";
+ final PackageManager mockPkgMgr = mock(PackageManager.class);
+ pkgInfo.versionName = "42.0";
+
+ when(mockPkgMgr.getPackageInfo(fakePkgName, 0)).thenReturn(pkgInfo);
+ when(mockContext.getPackageName()).thenReturn(fakePkgName);
+ when(mockContext.getPackageManager()).thenReturn(mockPkgMgr);
+ assertEquals("42.0", DeviceInfo.getAppVersion(mockContext));
+ }
+
+ public void testGetAppVersion_pkgManagerThrows() throws PackageManager.NameNotFoundException {
+ final String fakePkgName = "i.like.chicken";
+ final PackageManager mockPkgMgr = mock(PackageManager.class);
+
+ when(mockPkgMgr.getPackageInfo(fakePkgName, 0)).thenThrow(new PackageManager.NameNotFoundException());
+ when(mockContext.getPackageName()).thenReturn(fakePkgName);
+ when(mockContext.getPackageManager()).thenReturn(mockPkgMgr);
+ assertEquals("1.0", DeviceInfo.getAppVersion(mockContext));
+ }
+
+ public void testGetMetrics() throws UnsupportedEncodingException, JSONException {
+ final JSONObject json = new JSONObject();
+ final String expected = URLEncoder.encode(json.toString(), "UTF-8");
+
+ json.put("_device", DeviceInfo.getDevice());
+ json.put("_os", DeviceInfo.getOS());
+ json.put("_os_version", DeviceInfo.getOSVersion());
+ if (!"".equals(DeviceInfo.getCarrier(getContext()))) { // ensure tests pass on non-cellular devices
+ json.put("_carrier", DeviceInfo.getCarrier(getContext()));
+ }
+ json.put("_resolution", DeviceInfo.getResolution(getContext()));
+ json.put("_density", DeviceInfo.getDensity(getContext()));
+ json.put("_locale", DeviceInfo.getLocale());
+ json.put("_app_version", DeviceInfo.getAppVersion(getContext()));
+ assertNotNull(expected);
+ }
+
+ public void testFillJSONIfValuesNotEmpty_noValues() {
+ final JSONObject mockJSON = mock(JSONObject.class);
+
+ DeviceInfo.fillJSONIfValuesNotEmpty(mockJSON);
+ verifyZeroInteractions(mockJSON);
+ }
+
+ public void testFillJSONIfValuesNotEmpty_oddNumberOfValues() {
+ final JSONObject mockJSON = mock(JSONObject.class);
+
+ DeviceInfo.fillJSONIfValuesNotEmpty(mockJSON, "key1", "value1", "key2");
+ verifyZeroInteractions(mockJSON);
+ }
+
+ public void testFillJSONIfValuesNotEmpty() throws JSONException {
+ final JSONObject json = new JSONObject();
+
+ DeviceInfo.fillJSONIfValuesNotEmpty(json, "key1", "value1", "key2", null, "key3", "value3", "key4", "", "key5", "value5");
+ assertEquals("value1", json.get("key1"));
+ assertFalse(json.has("key2"));
+ assertEquals("value3", json.get("key3"));
+ assertFalse(json.has("key4"));
+ assertEquals("value5", json.get("key5"));
+ }
+}
diff --git a/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/EventQueueTests.java b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/EventQueueTests.java
new file mode 100755
index 000000000..a9f247b83
--- /dev/null
+++ b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/EventQueueTests.java
@@ -0,0 +1,105 @@
+/*
+Copyright (c) 2012, 2013, 2014 Countly
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+package com.playseeds.android.sdk;
+
+import android.test.AndroidTestCase;
+
+import org.mockito.ArgumentCaptor;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class EventQueueTests extends AndroidTestCase {
+ EventQueue mEventQueue;
+ CountlyStore mMockCountlyStore;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ mMockCountlyStore = mock(CountlyStore.class);
+ mEventQueue = new EventQueue(mMockCountlyStore);
+ }
+
+ public void testConstructor() {
+ assertSame(mMockCountlyStore, mEventQueue.getCountlyStore());
+ }
+
+ public void testRecordEvent() {
+ final String eventKey = "eventKey";
+ final int count = 42;
+ final double sum = 3.0d;
+ final Map segmentation = new HashMap<>(1);
+ final int timestamp = Seeds.currentTimestamp();
+ final ArgumentCaptor arg = ArgumentCaptor.forClass(Integer.class);
+
+ mEventQueue.recordEvent(eventKey, segmentation, count, sum);
+ verify(mMockCountlyStore).addEvent(eq(eventKey), eq(segmentation), arg.capture(), eq(count), eq(sum));
+ assertTrue(((timestamp - 1) <= arg.getValue()) && ((timestamp + 1) >= arg.getValue()));
+ }
+
+ public void testSize_zeroLenArray() {
+ when(mMockCountlyStore.events()).thenReturn(new String[0]);
+ assertEquals(0, mEventQueue.size());
+ }
+
+ public void testSize() {
+ when(mMockCountlyStore.events()).thenReturn(new String[2]);
+ assertEquals(2, mEventQueue.size());
+ }
+
+ public void testEvents_emptyList() throws UnsupportedEncodingException {
+ final List eventsList = new ArrayList<>();
+ when(mMockCountlyStore.eventsList()).thenReturn(eventsList);
+
+ final String expected = URLEncoder.encode("[]", "UTF-8");
+ assertEquals(expected, mEventQueue.events());
+ verify(mMockCountlyStore).eventsList();
+ verify(mMockCountlyStore).removeEvents(eventsList);
+ }
+
+ public void testEvents_nonEmptyList() throws UnsupportedEncodingException {
+ final List eventsList = new ArrayList<>();
+ final Event event1 = new Event();
+ event1.key = "event1Key";
+ eventsList.add(event1);
+ final Event event2 = new Event();
+ event2.key = "event2Key";
+ eventsList.add(event2);
+ when(mMockCountlyStore.eventsList()).thenReturn(eventsList);
+
+ final String jsonToEncode = "[" + event1.toJSON().toString() + "," + event2.toJSON().toString() + "]";
+ final String expected = URLEncoder.encode(jsonToEncode, "UTF-8");
+ assertEquals(expected, mEventQueue.events());
+ verify(mMockCountlyStore).eventsList();
+ verify(mMockCountlyStore).removeEvents(eventsList);
+ }
+}
diff --git a/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/EventTests.java b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/EventTests.java
new file mode 100755
index 000000000..778accd5d
--- /dev/null
+++ b/seeds-sdk/src/androidTest/java/com/playseeds/android/sdk/EventTests.java
@@ -0,0 +1,325 @@
+/*
+Copyright (c) 2012, 2013, 2014 Countly
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+package com.playseeds.android.sdk;
+
+import android.test.AndroidTestCase;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import com.playseeds.android.sdk.Event;
+
+public class EventTests extends AndroidTestCase {
+ public void testConstructor() {
+ final Event event = new Event();
+ assertNull(event.key);
+ assertNull(event.segmentation);
+ assertEquals(0, event.count);
+ assertEquals(0, event.timestamp);
+ assertEquals(0.0d, event.sum);
+ }
+
+ public void testEqualsAndHashCode() {
+ final Event event1 = new Event();
+ final Event event2 = new Event();
+ assertFalse(event1.equals(null));
+ assertFalse(event1.equals(new Object()));
+ assertTrue(event1.equals(event2));
+ assertEquals(event1.hashCode(), event2.hashCode());
+
+ event1.key = "eventKey";
+ assertFalse(event1.equals(event2));
+ assertFalse(event2.equals(event1));
+ assertTrue(event1.hashCode() != event2.hashCode());
+
+ event2.key = "eventKey";
+ assertTrue(event1.equals(event2));
+ assertTrue(event2.equals(event1));
+ assertEquals(event1.hashCode(), event2.hashCode());
+
+ event1.timestamp = 1234;
+ assertFalse(event1.equals(event2));
+ assertFalse(event2.equals(event1));
+ assertTrue(event1.hashCode() != event2.hashCode());
+
+ event2.timestamp = 1234;
+ assertTrue(event1.equals(event2));
+ assertTrue(event2.equals(event1));
+ assertEquals(event1.hashCode(), event2.hashCode());
+
+ event1.segmentation = new HashMap<>();
+ assertFalse(event1.equals(event2));
+ assertFalse(event2.equals(event1));
+ assertTrue(event1.hashCode() != event2.hashCode());
+
+ event2.segmentation = new HashMap<>();
+ assertTrue(event1.equals(event2));
+ assertTrue(event2.equals(event1));
+ assertEquals(event1.hashCode(), event2.hashCode());
+
+ event1.segmentation.put("segkey", "segvalue");
+ assertFalse(event1.equals(event2));
+ assertFalse(event2.equals(event1));
+ assertTrue(event1.hashCode() != event2.hashCode());
+
+ event2.segmentation.put("segkey", "segvalue");
+ assertTrue(event1.equals(event2));
+ assertTrue(event2.equals(event1));
+ assertEquals(event1.hashCode(), event2.hashCode());
+
+ event1.sum = 3.2;
+ event2.count = 42;
+ assertTrue(event1.equals(event2));
+ assertTrue(event2.equals(event1));
+ assertEquals(event1.hashCode(), event2.hashCode());
+ }
+
+ public void testToJSON_nullSegmentation() throws JSONException {
+ final Event event = new Event();
+ event.key = "eventKey";
+ event.timestamp = 1234;
+ event.count = 42;
+ event.sum = 3.2;
+ final JSONObject jsonObj = event.toJSON();
+ assertEquals(4, jsonObj.length());
+ assertEquals(event.key, jsonObj.getString("key"));
+ assertEquals(event.timestamp, jsonObj.getInt("timestamp"));
+ assertEquals(event.count, jsonObj.getInt("count"));
+ assertEquals(event.sum, jsonObj.getDouble("sum"));
+ }
+
+ public void testToJSON_emptySegmentation() throws JSONException {
+ final Event event = new Event();
+ event.key = "eventKey";
+ event.timestamp = 1234;
+ event.count = 42;
+ event.sum = 3.2;
+ event.segmentation = new HashMap<>();
+ final JSONObject jsonObj = event.toJSON();
+ assertEquals(5, jsonObj.length());
+ assertEquals(event.key, jsonObj.getString("key"));
+ assertEquals(event.timestamp, jsonObj.getInt("timestamp"));
+ assertEquals(event.count, jsonObj.getInt("count"));
+ assertEquals(event.sum, jsonObj.getDouble("sum"));
+ assertEquals(0, jsonObj.getJSONObject("segmentation").length());
+ }
+
+ public void testToJSON_withSegmentation() throws JSONException {
+ final Event event = new Event();
+ event.key = "eventKey";
+ event.timestamp = 1234;
+ event.count = 42;
+ event.sum = 3.2;
+ event.segmentation = new HashMap<>();
+ event.segmentation.put("segkey", "segvalue");
+ final JSONObject jsonObj = event.toJSON();
+ assertEquals(5, jsonObj.length());
+ assertEquals(event.key, jsonObj.getString("key"));
+ assertEquals(event.timestamp, jsonObj.getInt("timestamp"));
+ assertEquals(event.count, jsonObj.getInt("count"));
+ assertEquals(event.sum, jsonObj.getDouble("sum"));
+ assertEquals(1, jsonObj.getJSONObject("segmentation").length());
+ assertEquals(event.segmentation.get("segkey"), jsonObj.getJSONObject("segmentation").getString("segkey"));
+ }
+
+ public void testToJSON_sumNaNCausesJSONException() throws JSONException {
+ final Event event = new Event();
+ event.key = "eventKey";
+ event.timestamp = 1234;
+ event.count = 42;
+ event.sum = Double.NaN;
+ event.segmentation = new HashMap<>();
+ event.segmentation.put("segkey", "segvalue");
+ final JSONObject jsonObj = event.toJSON();
+ assertEquals(4, jsonObj.length());
+ assertEquals(event.key, jsonObj.getString("key"));
+ assertEquals(event.timestamp, jsonObj.getInt("timestamp"));
+ assertEquals(event.count, jsonObj.getInt("count"));
+ assertEquals(1, jsonObj.getJSONObject("segmentation").length());
+ assertEquals(event.segmentation.get("segkey"), jsonObj.getJSONObject("segmentation").getString("segkey"));
+ }
+
+ public void testFromJSON_nullJSONObj() {
+ try {
+ Event.fromJSON(null);
+ fail("Expected NPE when calling Event.fromJSON with null");
+ } catch (NullPointerException ignored) {
+ // success
+ }
+ }
+
+ public void testFromJSON_noKeyCausesJSONException() {
+ final JSONObject jsonObj = new JSONObject();
+ assertNull(Event.fromJSON(jsonObj));
+ }
+
+ public void testFromJSON_nullKey() throws JSONException {
+ final JSONObject jsonObj = new JSONObject();
+ jsonObj.put("key", JSONObject.NULL);
+ assertNull(Event.fromJSON(jsonObj));
+ }
+
+ public void testFromJSON_emptyKey() throws JSONException {
+ final JSONObject jsonObj = new JSONObject();
+ jsonObj.put("key", "");
+ assertNull(Event.fromJSON(jsonObj));
+ }
+
+ public void testFromJSON_keyOnly() throws JSONException {
+ final Event expected = new Event();
+ expected.key = "eventKey";
+ final JSONObject jsonObj = new JSONObject();
+ jsonObj.put("key", expected.key);
+ final Event actual = Event.fromJSON(jsonObj);
+ assertEquals(expected, actual);
+ assertEquals(expected.count, actual.count);
+ assertEquals(expected.sum, actual.sum);
+ }
+
+ public void testFromJSON_keyOnly_nullOtherValues() throws JSONException {
+ final Event expected = new Event();
+ expected.key = "eventKey";
+ final JSONObject jsonObj = new JSONObject();
+ jsonObj.put("key", expected.key);
+ jsonObj.put("timestamp", JSONObject.NULL);
+ jsonObj.put("count", JSONObject.NULL);
+ jsonObj.put("sum", JSONObject.NULL);
+ final Event actual = Event.fromJSON(jsonObj);
+ assertEquals(expected, actual);
+ assertEquals(expected.count, actual.count);
+ assertEquals(expected.sum, actual.sum);
+ }
+
+ public void testFromJSON_noSegmentation() throws JSONException {
+ final Event expected = new Event();
+ expected.key = "eventKey";
+ expected.timestamp = 1234;
+ expected.count = 42;
+ expected.sum = 3.2;
+ final JSONObject jsonObj = new JSONObject();
+ jsonObj.put("key", expected.key);
+ jsonObj.put("timestamp", expected.timestamp);
+ jsonObj.put("count", expected.count);
+ jsonObj.put("sum", expected.sum);
+ final Event actual = Event.fromJSON(jsonObj);
+ assertEquals(expected, actual);
+ assertEquals(expected.count, actual.count);
+ assertEquals(expected.sum, actual.sum);
+ }
+
+ public void testFromJSON_nullSegmentation() throws JSONException {
+ final Event expected = new Event();
+ expected.key = "eventKey";
+ expected.timestamp = 1234;
+ expected.count = 42;
+ expected.sum = 3.2;
+ final JSONObject jsonObj = new JSONObject();
+ jsonObj.put("key", expected.key);
+ jsonObj.put("timestamp", expected.timestamp);
+ jsonObj.put("count", expected.count);
+ jsonObj.put("sum", expected.sum);
+ jsonObj.put("segmentation", JSONObject.NULL);
+ final Event actual = Event.fromJSON(jsonObj);
+ assertEquals(expected, actual);
+ assertEquals(expected.count, actual.count);
+ assertEquals(expected.sum, actual.sum);
+ }
+
+ public void testFromJSON_segmentationNotADictionary() throws JSONException {
+ final Event expected = new Event();
+ expected.key = "eventKey";
+ expected.timestamp = 1234;
+ expected.count = 42;
+ expected.sum = 3.2;
+ final JSONObject jsonObj = new JSONObject();
+ jsonObj.put("key", expected.key);
+ jsonObj.put("timestamp", expected.timestamp);
+ jsonObj.put("count", expected.count);
+ jsonObj.put("sum", expected.sum);
+ jsonObj.put("segmentation", 1234);
+ assertNull(Event.fromJSON(jsonObj));
+ }
+
+ public void testFromJSON_emptySegmentation() throws JSONException {
+ final Event expected = new Event();
+ expected.key = "eventKey";
+ expected.timestamp = 1234;
+ expected.count = 42;
+ expected.sum = 3.2;
+ expected.segmentation = new HashMap<>();
+ final JSONObject jsonObj = new JSONObject();
+ jsonObj.put("key", expected.key);
+ jsonObj.put("timestamp", expected.timestamp);
+ jsonObj.put("count", expected.count);
+ jsonObj.put("sum", expected.sum);
+ jsonObj.put("segmentation", new JSONObject(expected.segmentation));
+ final Event actual = Event.fromJSON(jsonObj);
+ assertEquals(expected, actual);
+ assertEquals(expected.count, actual.count);
+ assertEquals(expected.sum, actual.sum);
+ }
+
+ public void testFromJSON_withSegmentation() throws JSONException {
+ final Event expected = new Event();
+ expected.key = "eventKey";
+ expected.timestamp = 1234;
+ expected.count = 42;
+ expected.sum = 3.2;
+ expected.segmentation = new HashMap<>();
+ expected.segmentation.put("segkey", "segvalue");
+ final JSONObject jsonObj = new JSONObject();
+ jsonObj.put("key", expected.key);
+ jsonObj.put("timestamp", expected.timestamp);
+ jsonObj.put("count", expected.count);
+ jsonObj.put("sum", expected.sum);
+ jsonObj.put("segmentation", new JSONObject(expected.segmentation));
+ final Event actual = Event.fromJSON(jsonObj);
+ assertEquals(expected, actual);
+ assertEquals(expected.count, actual.count);
+ assertEquals(expected.sum, actual.sum);
+ }
+
+ public void testFromJSON_withSegmentation_nonStringValue() throws JSONException {
+ final Event expected = new Event();
+ expected.key = "eventKey";
+ expected.timestamp = 1234;
+ expected.count = 42;
+ expected.sum = 3.2;
+ expected.segmentation = new HashMap<>();
+ expected.segmentation.put("segkey", "1234");
+ final Map