diff --git a/.gitignore b/.gitignore index c027320..72300e2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,27 +1,15 @@ -# Built application files -*.apk -*.ap_ -# Files for the Dalvik VM -*.dex -# Java class files -*.class +local.properties + # Generated files -bin/ -gen/ -# Gradle files -.gradle/ build/ -# Local configuration file (sdk path, etc) -local.properties -# Proguard folder generated by Eclipse -proguard/ -# Log Files -*.log -.gradle -/local.properties + +# Mac store .DS_Store -/build -*.iml + +# Gradle files +.gradle/ + +/captures # Log Files *.log @@ -41,3 +29,7 @@ proguard/ **/.idea/libraries **/.idea/dictionaries **/.idea/runConfigurations.xml +**/.idea/caches + +# layout inspector view captures +captures \ No newline at end of file diff --git a/.idea/.name b/.idea/.name deleted file mode 100644 index fc9365c..0000000 --- a/.idea/.name +++ /dev/null @@ -1 +0,0 @@ -hawk \ No newline at end of file diff --git a/.idea/codeStyleSettings.xml b/.idea/codeStyleSettings.xml deleted file mode 100644 index 76534c4..0000000 --- a/.idea/codeStyleSettings.xml +++ /dev/null @@ -1,280 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..8c95146 --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..79ee123 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml deleted file mode 100644 index 96cc43e..0000000 --- a/.idea/compiler.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml deleted file mode 100644 index e7bedf3..0000000 --- a/.idea/copyright/profiles_settings.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml deleted file mode 100644 index 97626ba..0000000 --- a/.idea/encodings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml deleted file mode 100644 index ecd817f..0000000 --- a/.idea/inspectionProfiles/Project_Default.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml deleted file mode 100644 index 3b31283..0000000 --- a/.idea/inspectionProfiles/profiles_settings.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml index 94a25f7..35eb1dd 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -1,6 +1,6 @@ - + \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index c8f3f9e..8bbde27 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,24 +1,15 @@ language: android +jdk: oraclejdk8 android: components: - tools - platform-tools - - build-tools-24.0.2 - - android-24 - - extra-android-m2repository - - sys-img-armeabi-v7a-android-18 + - build-tools-27.0.3 + - android-27 -jdk: - - oraclejdk8 - -notifications: - email: false +before_install: + - yes | sdkmanager "platforms;android-27" script: -- ./gradlew check - -cache: - directories: - - $HOME/.m2 - - $HOME/.gradle \ No newline at end of file +- ./gradlew check \ No newline at end of file diff --git a/README.md b/README.md index ae68e61..790a502 100644 --- a/README.md +++ b/README.md @@ -8,11 +8,16 @@ Secure, simple key-value storage for android #### Important Note This version has no backward compatibility with Hawk 1+ versions. If you still want to use old versions, [check here](https://github.com/orhanobut/hawk/tree/hawk1) +### Download +```groovy +compile "com.orhanobut:hawk:2.0.1" +``` + ### Initialize ```java Hawk.init(context).build(); ``` -### Use +### Usage Save any type (Any object, primitives, lists, sets, maps ...) ```java Hawk.put(key, T); @@ -21,7 +26,7 @@ Get the original value with the original type ```java T value = Hawk.get(key); ``` -Delete unwanted data +Delete any entry ```java Hawk.delete(key); ``` @@ -29,7 +34,7 @@ Check if any key exists ```java Hawk.contains(key); ``` -Check total count +Check total entry count ```java Hawk.count(); ``` @@ -38,12 +43,7 @@ Get crazy and delete everything Hawk.deleteAll(); ``` -### Download -```groovy -compile 'com.orhanobut:hawk:2.0.1' -``` - -### How Hawk works +### How does Hawk work? @@ -60,9 +60,6 @@ Hawk.init(context) .build(); ``` -### Proguard -Would love to have proguard pull request for consumer proguard implementation - ### License
 Copyright 2016 Orhan Obut
diff --git a/benchmark/build.gradle b/benchmark/build.gradle
index 482abcd..dbce8d2 100644
--- a/benchmark/build.gradle
+++ b/benchmark/build.gradle
@@ -7,7 +7,7 @@ android {
   defaultConfig {
     applicationId "com.orhanobut.benchmark"
     minSdkVersion rootProject.ext.minSdkVersion
-    targetSdkVersion rootProject.ext.targetSdkVersion
+    targetSdkVersion 26
     versionCode 1
     versionName "1.0"
   }
@@ -20,9 +20,6 @@ android {
 }
 
 dependencies {
-  compile fileTree(dir: 'libs', include: ['*.jar'])
-  testCompile 'junit:junit:4.12'
-  compile 'com.android.support:appcompat-v7:24.2.1'
-
-  compile project(':hawk')
+  implementation 'com.android.support:appcompat-v7:27.1.0'
+  implementation project(':hawk')
 }
diff --git a/build.gradle b/build.gradle
index efddefc..06e7a44 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,4 +1,22 @@
-// Top-level build file where you can add configuration options common to all sub-projects/modules.
+buildscript {
+  ext.kotlinVersion = '1.2.31'
+  repositories {
+    google()
+    jcenter()
+  }
+  dependencies {
+    classpath 'com.android.tools.build:gradle:3.1.0'
+    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
+  }
+}
+
+allprojects {
+  repositories {
+    google()
+    jcenter()
+  }
+}
+
 subprojects { project ->
   group = GROUP
   version = VERSION_NAME
@@ -20,39 +38,32 @@ subprojects { project ->
       check.dependsOn('checkstyle')
     }
   }
+}
 
-  buildscript {
-    repositories {
-      jcenter()
-    }
-    dependencies {
-      classpath 'com.android.tools.build:gradle:2.2.1'
-    }
-  }
-
-  repositories {
-    jcenter()
-  }
+task clean(type: Delete) {
+  delete rootProject.buildDir
 }
 
 ext {
-  minSdkVersion = 10
-  targetSdkVersion = 24
-  compileSdkVersion = 24
-  buildToolsVersion = '24.0.2'
+  minSdkVersion = 15
+  targetSdkVersion = 27
+  compileSdkVersion = 27
+  buildToolsVersion = '27.0.3'
   sourceCompatibilityVersion = JavaVersion.VERSION_1_7
   targetCompatibilityVersion = JavaVersion.VERSION_1_7
 }
 
 ext.deps = [
-    gson          : 'com.google.code.gson:gson:2.4',
+    gson          : 'com.google.code.gson:gson:2.8.2',
     conceal       : 'com.facebook.conceal:conceal:1.1.3@aar',
 
     // Test dependencies
     junit         : 'junit:junit:4.12',
     truth         : 'com.google.truth:truth:0.28',
-    robolectric   : 'org.robolectric:robolectric:3.1.2',
-    mockito       : 'org.mockito:mockito-core:1.10.19',
+    robolectric   : 'org.robolectric:robolectric:3.3',
+    mockito       : 'org.mockito:mockito-core:2.8.9',
     espressoRunner: 'com.android.support.test:runner:0.5',
-    espressoRules : 'com.android.support.test:rules:0.5'
+    espressoRules : 'com.android.support.test:rules:0.5',
+    kotlin        : "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion"
+
 ]
diff --git a/gradle.properties b/gradle.properties
index a5cd717..cafe0a6 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -1,4 +1,4 @@
-VERSION_NAME=2.0.1
+VERSION_NAME=2.1.0
 GROUP=com.orhanobut
 
 POM_DESCRIPTION=Secure, simple key-value storage for android
diff --git a/gradle/maven_push.gradle b/gradle/maven_push.gradle
index 50e961d..840f277 100644
--- a/gradle/maven_push.gradle
+++ b/gradle/maven_push.gradle
@@ -27,7 +27,7 @@ afterEvaluate { project ->
         pom.artifactId = POM_ARTIFACT_ID
         repository(url: sonatypeRepositoryUrl) {
           try {
-            authentication(userName: mavenUser, password: mavenPassword)
+            authentication(userName: NEXUS_USERNAME, password: NEXUS_PASSWORD)
           } catch (Exception e) {
             println "mavenUser or mavenPassword is missing"
           }
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 191af49..ed805a8 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
-#Fri Aug 26 22:12:19 CEST 2016
+#Mon Apr 02 17:27:38 AEST 2018
 distributionBase=GRADLE_USER_HOME
 distributionPath=wrapper/dists
 zipStoreBase=GRADLE_USER_HOME
 zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
diff --git a/hawk/build.gradle b/hawk/build.gradle
index 69f654b..4bae333 100644
--- a/hawk/build.gradle
+++ b/hawk/build.gradle
@@ -1,4 +1,5 @@
 apply plugin: 'com.android.library'
+apply plugin: 'kotlin-android'
 
 android {
   compileSdkVersion rootProject.ext.compileSdkVersion
@@ -17,19 +18,20 @@ android {
 }
 
 dependencies {
-  compile deps.gson
-  compile deps.conceal
-
-  testCompile deps.junit
-  testCompile deps.truth
-  testCompile deps.robolectric
-  testCompile deps.mockito
-
-  androidTestCompile deps.junit
-  androidTestCompile deps.truth
-
-  androidTestCompile deps.espressoRunner
-  androidTestCompile deps.espressoRules
+  api deps.conceal
+  implementation deps.gson
+
+  testImplementation deps.junit
+  testImplementation deps.truth
+  testImplementation deps.robolectric
+  testImplementation deps.mockito
+  testImplementation deps.kotlin
+
+  androidTestImplementation deps.junit
+  androidTestImplementation deps.truth
+  androidTestImplementation deps.espressoRunner
+  androidTestImplementation deps.espressoRules
+  androidTestImplementation deps.kotlin
 
 }
 
diff --git a/hawk/src/androidTest/java/com/orhanobut/hawk/ConcealEncryptionTest.java b/hawk/src/androidTest/java/com/orhanobut/hawk/ConcealEncryptionTest.java
deleted file mode 100644
index 3862a75..0000000
--- a/hawk/src/androidTest/java/com/orhanobut/hawk/ConcealEncryptionTest.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.orhanobut.hawk;
-
-import android.support.test.InstrumentationRegistry;
-import android.support.test.runner.AndroidJUnit4;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.google.common.truth.Truth.assertThat;
-
-@RunWith(AndroidJUnit4.class)
-public class ConcealEncryptionTest {
-
-  private Encryption encryption;
-
-  @Before public void setup() {
-    encryption = new ConcealEncryption(InstrumentationRegistry.getContext());
-  }
-
-  @Test public void init() throws Exception {
-    assertThat(encryption.init()).isTrue();
-  }
-
-  @Test public void testEncryptAndDecrypt() throws Exception {
-    String key = "key";
-    String value = "value";
-
-    String cipherText = encryption.encrypt(key, value);
-
-    String plainValue = encryption.decrypt(key, cipherText);
-
-    assertThat(plainValue).isEqualTo(value);
-  }
-}
\ No newline at end of file
diff --git a/hawk/src/androidTest/java/com/orhanobut/hawk/ConcealEncryptionTest.kt b/hawk/src/androidTest/java/com/orhanobut/hawk/ConcealEncryptionTest.kt
new file mode 100644
index 0000000..e713a9f
--- /dev/null
+++ b/hawk/src/androidTest/java/com/orhanobut/hawk/ConcealEncryptionTest.kt
@@ -0,0 +1,35 @@
+package com.orhanobut.hawk
+
+import android.support.test.InstrumentationRegistry
+import android.support.test.runner.AndroidJUnit4
+
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+import com.google.common.truth.Truth.assertThat
+
+@RunWith(AndroidJUnit4::class)
+class ConcealEncryptionTest {
+
+  private lateinit var encryption: Encryption
+
+  @Before fun setup() {
+    encryption = ConcealEncryption(InstrumentationRegistry.getContext())
+  }
+
+  @Test fun init() {
+    assertThat(encryption.init()).isTrue()
+  }
+
+  @Test fun testEncryptAndDecrypt() {
+    val key = "key"
+    val value = "value"
+
+    val cipherText = encryption.encrypt(key, value)
+
+    val plainValue = encryption.decrypt(key, cipherText)
+
+    assertThat(plainValue).isEqualTo(value)
+  }
+}
\ No newline at end of file
diff --git a/hawk/src/androidTest/java/com/orhanobut/hawk/ConcealTest.java b/hawk/src/androidTest/java/com/orhanobut/hawk/ConcealTest.java
deleted file mode 100644
index e48b89d..0000000
--- a/hawk/src/androidTest/java/com/orhanobut/hawk/ConcealTest.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package com.orhanobut.hawk;
-
-import android.content.Context;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.runner.AndroidJUnit4;
-
-import com.facebook.android.crypto.keychain.AndroidConceal;
-import com.facebook.android.crypto.keychain.SharedPrefsBackedKeyChain;
-import com.facebook.crypto.Crypto;
-import com.facebook.crypto.CryptoConfig;
-import com.facebook.crypto.Entity;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.google.common.truth.Truth.assertThat;
-
-
-@RunWith(AndroidJUnit4.class)
-public class ConcealTest {
-
-  private Crypto crypto;
-
-  @Before public void setup() {
-    Context context = InstrumentationRegistry.getContext();
-    SharedPrefsBackedKeyChain keyChain = new SharedPrefsBackedKeyChain(context, CryptoConfig.KEY_256);
-    crypto = AndroidConceal.get().createDefaultCrypto(keyChain);
-  }
-
-  @Test public void cryptoIsAvailable() {
-    assertThat(crypto.isAvailable()).isTrue();
-  }
-
-  @Test public void testConceal() throws Exception {
-    Entity entity = Entity.create("key");
-    String value = "value";
-    byte[] encryptedValue = crypto.encrypt(value.getBytes(), entity);
-
-    assertThat(encryptedValue).isNotNull();
-
-    String decryptedValue = new String(crypto.decrypt(encryptedValue, entity));
-    assertThat(decryptedValue).isEqualTo("value");
-  }
-}
diff --git a/hawk/src/androidTest/java/com/orhanobut/hawk/ConcealTest.kt b/hawk/src/androidTest/java/com/orhanobut/hawk/ConcealTest.kt
new file mode 100644
index 0000000..5681cf5
--- /dev/null
+++ b/hawk/src/androidTest/java/com/orhanobut/hawk/ConcealTest.kt
@@ -0,0 +1,40 @@
+package com.orhanobut.hawk
+
+import android.support.test.InstrumentationRegistry
+import android.support.test.runner.AndroidJUnit4
+import com.facebook.android.crypto.keychain.AndroidConceal
+import com.facebook.android.crypto.keychain.SharedPrefsBackedKeyChain
+import com.facebook.crypto.Crypto
+import com.facebook.crypto.CryptoConfig
+import com.facebook.crypto.Entity
+import com.google.common.truth.Truth.assertThat
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(AndroidJUnit4::class)
+class ConcealTest {
+
+  private lateinit var crypto: Crypto
+
+  @Before fun setup() {
+    val context = InstrumentationRegistry.getContext()
+    val keyChain = SharedPrefsBackedKeyChain(context, CryptoConfig.KEY_256)
+    crypto = AndroidConceal.get().createDefaultCrypto(keyChain)
+  }
+
+  @Test fun cryptoIsAvailable() {
+    assertThat(crypto.isAvailable).isTrue()
+  }
+
+  @Test fun testConceal() {
+    val entity = Entity.create("key")
+    val value = "value"
+    val encryptedValue = crypto.encrypt(value.toByteArray(), entity)
+
+    assertThat(encryptedValue).isNotNull()
+
+    val decryptedValue = String(crypto.decrypt(encryptedValue, entity))
+    assertThat(decryptedValue).isEqualTo("value")
+  }
+}
diff --git a/hawk/src/main/java/com/orhanobut/hawk/Converter.java b/hawk/src/main/java/com/orhanobut/hawk/Converter.java
index 56b3c00..88c0d26 100644
--- a/hawk/src/main/java/com/orhanobut/hawk/Converter.java
+++ b/hawk/src/main/java/com/orhanobut/hawk/Converter.java
@@ -1,12 +1,17 @@
 package com.orhanobut.hawk;
 
-interface Converter {
+/**
+ * Used to handle encoding and decoding as an intermediate layer.
+ * 

Implement this interface if a custom implementation is needed

+ * + * @see HawkConverter + */ +public interface Converter { /** * Encodes the value * * @param value will be encoded - * * @return the encoded string */ String toString(T value); @@ -15,9 +20,7 @@ interface Converter { * Decodes * * @param value is the encoded data - * * @return the plain value - * * @throws Exception */ T fromString(String value, DataInfo dataInfo) throws Exception; diff --git a/hawk/src/main/java/com/orhanobut/hawk/Encryption.java b/hawk/src/main/java/com/orhanobut/hawk/Encryption.java index c98c321..cb78918 100644 --- a/hawk/src/main/java/com/orhanobut/hawk/Encryption.java +++ b/hawk/src/main/java/com/orhanobut/hawk/Encryption.java @@ -1,5 +1,12 @@ package com.orhanobut.hawk; +/** + * Intermediate layer which is used by Hawk to encrypt and decrypt the given values. + * + *

Use custom implementation if built-in implementation is not enough.

+ * + * @see ConcealEncryption + */ public interface Encryption { /** @@ -15,7 +22,6 @@ public interface Encryption { * * @param key is the given key * @param value is the plain text - * * @return cipher text as string */ String encrypt(String key, String value) throws Exception; @@ -25,7 +31,6 @@ public interface Encryption { * * @param key is the given key * @param value is the cipher text - * * @return plain text */ String decrypt(String key, String value) throws Exception; diff --git a/hawk/src/main/java/com/orhanobut/hawk/Hawk.java b/hawk/src/main/java/com/orhanobut/hawk/Hawk.java index 35e8b46..c01faa9 100644 --- a/hawk/src/main/java/com/orhanobut/hawk/Hawk.java +++ b/hawk/src/main/java/com/orhanobut/hawk/Hawk.java @@ -2,7 +2,9 @@ import android.content.Context; - +/** + * Secure, simple key-value storage for Android. + */ public final class Hawk { private Hawk() { @@ -32,7 +34,6 @@ static void build(HawkBuilder hawkBuilder) { * * @param key is required to differentiate the given data * @param value is the data that is going to be encrypted and persisted - * * @return true if the operation is successful. Any failure in any step will return false */ public static boolean put(String key, T value) { @@ -45,7 +46,6 @@ public static boolean put(String key, T value) { * data type might affect the result. It's guaranteed to return primitive types and String type * * @param key is used to get the persisted data - * * @return the original object */ public static T get(String key) { @@ -57,7 +57,6 @@ public static T get(String key) { * * @param key is used to get the saved data * @param defaultValue will be return if the response is null - * * @return the saved object */ public static T get(String key, T defaultValue) { @@ -87,7 +86,6 @@ public static boolean deleteAll() { * Removes the given key/value from the storage * * @param key is used for removing related data from storage - * * @return true if delete is successful */ public static boolean delete(String key) { @@ -98,7 +96,6 @@ public static boolean delete(String key) { * Checks the given key whether it exists or not * * @param key is the key to check - * * @return true if it exists in the storage */ public static boolean contains(String key) { diff --git a/hawk/src/main/java/com/orhanobut/hawk/Parser.java b/hawk/src/main/java/com/orhanobut/hawk/Parser.java index d95854e..e8c81b1 100644 --- a/hawk/src/main/java/com/orhanobut/hawk/Parser.java +++ b/hawk/src/main/java/com/orhanobut/hawk/Parser.java @@ -2,11 +2,34 @@ import java.lang.reflect.Type; -@SuppressWarnings("WeakerAccess") +/** + * Intermediate layer that handles serialization/deserialization for the end result. + * This is not the same as {@link Serializer}. This interface is only used to convert the intermediate value + * into String or vice-versa to be used for {@link Storage} + * + *

Use custom implementation if built-in implementation is not enough.

+ * + * @see GsonParser + */ public interface Parser { + /** + * Deserialize the given text for the given type and returns it. + * + * @param content is the value that will be deserialized. + * @param type is the object type which value will be converted to. + * @param is the expected type. + * @return the expected type. + * @throws Exception if the operation is not successful. + */ T fromJson(String content, Type type) throws Exception; + /** + * Serialize the given object to String. + * + * @param body is the object that will be serialized. + * @return the serialized text. + */ String toJson(Object body); } diff --git a/hawk/src/main/java/com/orhanobut/hawk/Serializer.java b/hawk/src/main/java/com/orhanobut/hawk/Serializer.java index 8fe44f6..bd9ccf2 100644 --- a/hawk/src/main/java/com/orhanobut/hawk/Serializer.java +++ b/hawk/src/main/java/com/orhanobut/hawk/Serializer.java @@ -1,6 +1,12 @@ package com.orhanobut.hawk; -@SuppressWarnings("WeakerAccess") +/** + * Intermediate layer that is used to serialize/deserialize the cipher text + * + *

Use custom implementation if built-in implementation is not enough.

+ * + * @see HawkSerializer + */ public interface Serializer { /** diff --git a/hawk/src/main/java/com/orhanobut/hawk/Storage.java b/hawk/src/main/java/com/orhanobut/hawk/Storage.java index bfad5cc..9d789d5 100644 --- a/hawk/src/main/java/com/orhanobut/hawk/Storage.java +++ b/hawk/src/main/java/com/orhanobut/hawk/Storage.java @@ -1,6 +1,12 @@ package com.orhanobut.hawk; -@SuppressWarnings("WeakerAccess") +/** + * Intermediate layer which stores the given data. Used by Hawk. + * + *

Use custom implementation if the built-in implementations are not enough.

+ * + * @see SharedPreferencesStorage + */ public interface Storage { /** diff --git a/hawk/src/test/java/com/orhanobut/hawk/DefaultHawkFacadeTest.java b/hawk/src/test/java/com/orhanobut/hawk/DefaultHawkFacadeTest.java deleted file mode 100644 index dec9126..0000000 --- a/hawk/src/test/java/com/orhanobut/hawk/DefaultHawkFacadeTest.java +++ /dev/null @@ -1,239 +0,0 @@ -package com.orhanobut.hawk; - -import android.content.Context; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.InOrder; -import org.mockito.Mock; - -import static com.google.common.truth.Truth.assertThat; -import static junit.framework.Assert.fail; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; - -public class DefaultHawkFacadeTest { - - private static final String KEY = "KEY"; - private static final String VALUE = "VALUE"; - private static final String CONVERTED_TEXT = "CONVERTED_TEXT"; - private static final String CIPHER_TEXT = "CIPHER_TEXT"; - private static final String SERIALIZED_TEXT = "SERIALIZED_TEXT"; - private static final DataInfo DATA_INFO = new DataInfo(DataInfo.TYPE_OBJECT, CIPHER_TEXT, String.class, null); - - private HawkFacade hawkFacade; - - @Mock Converter converter; - @Mock Encryption encryption; - @Mock Serializer serializer; - @Mock Storage storage; - @Mock Context context; - - @Before public void setup() { - initMocks(this); - - HawkBuilder builder = new HawkBuilder(context) - .setConverter(converter) - .setSerializer(serializer) - .setEncryption(encryption) - .setStorage(storage); - - hawkFacade = new DefaultHawkFacade(builder); - } - - //region PUT - - @Test public void putFailsOnNullKey() { - try { - hawkFacade.put(null, VALUE); - fail("Null is not accepted"); - } catch (Exception e) { - assertThat(e).hasMessage("Key should not be null"); - } - } - - @Test public void putSuccess() throws Exception { - when(converter.toString(VALUE)).thenReturn(CONVERTED_TEXT); - when(encryption.encrypt(KEY, CONVERTED_TEXT)).thenReturn(CIPHER_TEXT); - when(serializer.serialize(CIPHER_TEXT, VALUE)).thenReturn(SERIALIZED_TEXT); - when(storage.put(KEY, SERIALIZED_TEXT)).thenReturn(true); - - assertThat(hawkFacade.put(KEY, VALUE)).isTrue(); - - InOrder inOrder = inOrder(converter, encryption, serializer, storage); - inOrder.verify(converter).toString(VALUE); - inOrder.verify(encryption).encrypt(KEY, CONVERTED_TEXT); - inOrder.verify(serializer).serialize(CIPHER_TEXT, VALUE); - inOrder.verify(storage).put(KEY, SERIALIZED_TEXT); - } - - @Test public void putFailsOnConvert() throws Exception { - when(converter.toString(VALUE)).thenReturn(null); - - assertThat(hawkFacade.put(KEY, VALUE)).isFalse(); - - verify(converter).toString(VALUE); - verifyNoMoreInteractions(encryption, storage, serializer); - } - - @Test public void putFailsOnEncrypt() throws Exception { - when(converter.toString(VALUE)).thenReturn(CONVERTED_TEXT); - when(encryption.encrypt(KEY, CONVERTED_TEXT)).thenReturn(null); - - assertThat(hawkFacade.put(KEY, VALUE)).isFalse(); - - InOrder inOrder = inOrder(converter, encryption); - inOrder.verify(converter).toString(VALUE); - inOrder.verify(encryption).encrypt(KEY, CONVERTED_TEXT); - verifyNoMoreInteractions(serializer, storage); - } - - @Test public void putFailsOnSerialize() throws Exception { - when(converter.toString(VALUE)).thenReturn(CONVERTED_TEXT); - when(encryption.encrypt(KEY, CONVERTED_TEXT)).thenReturn(CIPHER_TEXT); - when(serializer.serialize(CIPHER_TEXT, VALUE)).thenReturn(null); - - assertThat(hawkFacade.put(KEY, VALUE)).isFalse(); - - InOrder inOrder = inOrder(converter, encryption, serializer, storage); - inOrder.verify(converter).toString(VALUE); - inOrder.verify(encryption).encrypt(KEY, CONVERTED_TEXT); - inOrder.verify(serializer).serialize(CIPHER_TEXT, VALUE); - verifyZeroInteractions(storage); - } - - @Test public void putFailsOnStorage() throws Exception { - when(converter.toString(VALUE)).thenReturn(CONVERTED_TEXT); - when(encryption.encrypt(KEY, CONVERTED_TEXT)).thenReturn(CIPHER_TEXT); - when(serializer.serialize(CIPHER_TEXT, VALUE)).thenReturn(SERIALIZED_TEXT); - when(storage.put(KEY, SERIALIZED_TEXT)).thenReturn(false); - - assertThat(hawkFacade.put(KEY, VALUE)).isFalse(); - - InOrder inOrder = inOrder(converter, encryption, serializer, storage); - inOrder.verify(converter).toString(VALUE); - inOrder.verify(encryption).encrypt(KEY, CONVERTED_TEXT); - inOrder.verify(serializer).serialize(CIPHER_TEXT, VALUE); - inOrder.verify(storage).put(KEY, SERIALIZED_TEXT); - } - - //endregion - - //region GET - @Test public void getNullKey() { - assertThat(hawkFacade.get(null)).isNull(); - } - - @Test public void getWithDefault() { - when(hawkFacade.get(anyString())).thenReturn(null); - - assertThat(hawkFacade.get("key", "default")).isEqualTo("default"); - assertThat(hawkFacade.get(null, "default")).isEqualTo("default"); - } - - @Test public void getSuccess() throws Exception { - when(storage.get(KEY)).thenReturn(SERIALIZED_TEXT); - when(serializer.deserialize(SERIALIZED_TEXT)).thenReturn(DATA_INFO); - when(encryption.decrypt(KEY, CIPHER_TEXT)).thenReturn(CONVERTED_TEXT); - when(converter.fromString(CONVERTED_TEXT, DATA_INFO)).thenReturn(VALUE); - - assertThat(hawkFacade.get(KEY)).isEqualTo(VALUE); - - InOrder inOrder = inOrder(converter, encryption, serializer, storage); - inOrder.verify(storage).get(KEY); - inOrder.verify(serializer).deserialize(SERIALIZED_TEXT); - inOrder.verify(encryption).decrypt(KEY, CIPHER_TEXT); - inOrder.verify(converter).fromString(CONVERTED_TEXT, DATA_INFO); - } - - @Test public void getFailsOnStorage() throws Exception { - when(storage.get(KEY)).thenReturn(null); - - assertThat(hawkFacade.get(KEY)).isEqualTo(null); - - verify(storage).get(KEY); - verifyZeroInteractions(encryption, serializer, converter); - } - - @Test public void getFailsOnDeserialize() throws Exception { - when(storage.get(KEY)).thenReturn(SERIALIZED_TEXT); - when(serializer.deserialize(SERIALIZED_TEXT)).thenReturn(null); - - assertThat(hawkFacade.get(KEY)).isEqualTo(null); - - InOrder inOrder = inOrder(converter, encryption, serializer, storage); - inOrder.verify(storage).get(KEY); - inOrder.verify(serializer).deserialize(SERIALIZED_TEXT); - - verifyZeroInteractions(encryption, converter); - } - - @Test public void getFailsOnDecrypt() throws Exception { - when(storage.get(KEY)).thenReturn(SERIALIZED_TEXT); - when(serializer.deserialize(SERIALIZED_TEXT)).thenReturn(DATA_INFO); - when(encryption.decrypt(KEY, CIPHER_TEXT)).thenReturn(null); - - assertThat(hawkFacade.get(KEY)).isEqualTo(null); - - InOrder inOrder = inOrder(converter, encryption, serializer, storage); - inOrder.verify(storage).get(KEY); - inOrder.verify(serializer).deserialize(SERIALIZED_TEXT); - inOrder.verify(encryption).decrypt(KEY, CIPHER_TEXT); - - verifyZeroInteractions(converter); - } - - @Test public void getFailsOnConvert() throws Exception { - when(storage.get(KEY)).thenReturn(SERIALIZED_TEXT); - when(serializer.deserialize(SERIALIZED_TEXT)).thenReturn(DATA_INFO); - when(encryption.decrypt(KEY, CIPHER_TEXT)).thenReturn(CONVERTED_TEXT); - when(converter.fromString(CONVERTED_TEXT, DATA_INFO)).thenReturn(null); - - assertThat(hawkFacade.get(KEY)).isEqualTo(null); - - InOrder inOrder = inOrder(converter, encryption, serializer, storage); - inOrder.verify(storage).get(KEY); - inOrder.verify(serializer).deserialize(SERIALIZED_TEXT); - inOrder.verify(encryption).decrypt(KEY, CIPHER_TEXT); - inOrder.verify(converter).fromString(CONVERTED_TEXT, DATA_INFO); - } - - //endregion - - @Test public void count() { - when(storage.count()).thenReturn(100L); - - assertThat(hawkFacade.count()).isEqualTo(100L); - verifyZeroInteractions(encryption, converter, serializer); - } - - @Test public void deleteAll() { - when(storage.deleteAll()).thenReturn(true); - - assertThat(hawkFacade.deleteAll()).isTrue(); - verifyZeroInteractions(encryption, converter, serializer); - } - - @Test public void delete() { - when(storage.delete(KEY)).thenReturn(true); - - assertThat(hawkFacade.delete(KEY)).isTrue(); - verifyZeroInteractions(encryption, converter, serializer); - } - - @Test public void contains() { - when(storage.contains(KEY)).thenReturn(true); - - assertThat(hawkFacade.contains(KEY)).isTrue(); - verifyZeroInteractions(encryption, converter, serializer); - } - - @Test public void isBuilt() { - assertThat(hawkFacade.isBuilt()).isTrue(); - } -} \ No newline at end of file diff --git a/hawk/src/test/java/com/orhanobut/hawk/DefaultHawkFacadeTest.kt b/hawk/src/test/java/com/orhanobut/hawk/DefaultHawkFacadeTest.kt new file mode 100644 index 0000000..cc91a09 --- /dev/null +++ b/hawk/src/test/java/com/orhanobut/hawk/DefaultHawkFacadeTest.kt @@ -0,0 +1,243 @@ +package com.orhanobut.hawk + +import android.content.Context + +import org.junit.Before +import org.junit.Test +import org.mockito.InOrder +import org.mockito.Mock + +import com.google.common.truth.Truth.assertThat +import junit.framework.Assert.fail +import org.mockito.Matchers.anyString +import org.mockito.Mockito.inOrder +import org.mockito.Mockito.verify +import org.mockito.Mockito.verifyNoMoreInteractions +import org.mockito.Mockito.verifyZeroInteractions +import org.mockito.Mockito.`when` +import org.mockito.MockitoAnnotations.initMocks + +class DefaultHawkFacadeTest { + + private lateinit var hawkFacade: HawkFacade + + @Mock private lateinit var converter: Converter + @Mock private lateinit var encryption: Encryption + @Mock private lateinit var serializer: Serializer + @Mock private lateinit var storage: Storage + @Mock private lateinit var context: Context + + @Before fun setup() { + initMocks(this) + + val builder = HawkBuilder(context) + .setConverter(converter) + .setSerializer(serializer) + .setEncryption(encryption) + .setStorage(storage) + + hawkFacade = DefaultHawkFacade(builder) + } + + //region PUT + + @Test fun putFailsOnNullKey() { + try { + hawkFacade.put(null, VALUE) + fail("Null is not accepted") + } catch (e: Exception) { + assertThat(e).hasMessage("Key should not be null") + } + + } + + @Test fun putSuccess() { + `when`(converter.toString(VALUE)).thenReturn(CONVERTED_TEXT) + `when`(encryption.encrypt(KEY, CONVERTED_TEXT)).thenReturn(CIPHER_TEXT) + `when`(serializer.serialize(CIPHER_TEXT, VALUE)).thenReturn(SERIALIZED_TEXT) + `when`(storage.put(KEY, SERIALIZED_TEXT)).thenReturn(true) + + assertThat(hawkFacade.put(KEY, VALUE)).isTrue() + + val inOrder = inOrder(converter, encryption, serializer, storage) + inOrder.verify(converter).toString(VALUE) + inOrder.verify(encryption).encrypt(KEY, CONVERTED_TEXT) + inOrder.verify(serializer).serialize(CIPHER_TEXT, VALUE) + inOrder.verify(storage).put(KEY, SERIALIZED_TEXT) + } + + @Test fun putFailsOnConvert() { + `when`(converter.toString(VALUE)).thenReturn(null) + + assertThat(hawkFacade.put(KEY, VALUE)).isFalse() + + verify(converter).toString(VALUE) + verifyNoMoreInteractions(encryption, storage, serializer) + } + + @Test fun putFailsOnEncrypt() { + `when`(converter.toString(VALUE)).thenReturn(CONVERTED_TEXT) + `when`(encryption.encrypt(KEY, CONVERTED_TEXT)).thenReturn(null) + + assertThat(hawkFacade.put(KEY, VALUE)).isFalse() + + val inOrder = inOrder(converter, encryption) + inOrder.verify(converter).toString(VALUE) + inOrder.verify(encryption).encrypt(KEY, CONVERTED_TEXT) + verifyNoMoreInteractions(serializer, storage) + } + + @Test fun putFailsOnSerialize() { + `when`(converter.toString(VALUE)).thenReturn(CONVERTED_TEXT) + `when`(encryption.encrypt(KEY, CONVERTED_TEXT)).thenReturn(CIPHER_TEXT) + `when`(serializer.serialize(CIPHER_TEXT, VALUE)).thenReturn(null) + + assertThat(hawkFacade.put(KEY, VALUE)).isFalse() + + val inOrder = inOrder(converter, encryption, serializer, storage) + inOrder.verify(converter).toString(VALUE) + inOrder.verify(encryption).encrypt(KEY, CONVERTED_TEXT) + inOrder.verify(serializer).serialize(CIPHER_TEXT, VALUE) + verifyZeroInteractions(storage) + } + + @Test fun putFailsOnStorage() { + `when`(converter.toString(VALUE)).thenReturn(CONVERTED_TEXT) + `when`(encryption.encrypt(KEY, CONVERTED_TEXT)).thenReturn(CIPHER_TEXT) + `when`(serializer.serialize(CIPHER_TEXT, VALUE)).thenReturn(SERIALIZED_TEXT) + `when`(storage.put(KEY, SERIALIZED_TEXT)).thenReturn(false) + + assertThat(hawkFacade.put(KEY, VALUE)).isFalse() + + val inOrder = inOrder(converter, encryption, serializer, storage) + inOrder.verify(converter).toString(VALUE) + inOrder.verify(encryption).encrypt(KEY, CONVERTED_TEXT) + inOrder.verify(serializer).serialize(CIPHER_TEXT, VALUE) + inOrder.verify(storage).put(KEY, SERIALIZED_TEXT) + } + + //endregion + + //region GET + @Test fun getNullKey() { + assertThat(hawkFacade.get(null)).isNull() + } + + @Test fun getWithDefault() { + `when`(hawkFacade.get(anyString())).thenReturn(null) + + assertThat(hawkFacade.get("key", "default")).isEqualTo("default") + assertThat(hawkFacade.get(null, "default")).isEqualTo("default") + } + + @Test fun getSuccess() { + `when`(storage.get(KEY)).thenReturn(SERIALIZED_TEXT) + `when`(serializer.deserialize(SERIALIZED_TEXT)).thenReturn(DATA_INFO) + `when`(encryption.decrypt(KEY, CIPHER_TEXT)).thenReturn(CONVERTED_TEXT) + `when`(converter.fromString(CONVERTED_TEXT, DATA_INFO)).thenReturn(VALUE) + + assertThat(hawkFacade.get(KEY)).isEqualTo(VALUE) + + val inOrder = inOrder(converter, encryption, serializer, storage) + inOrder.verify(storage).get(KEY) + inOrder.verify(serializer).deserialize(SERIALIZED_TEXT) + inOrder.verify(encryption).decrypt(KEY, CIPHER_TEXT) + inOrder.verify(converter).fromString(CONVERTED_TEXT, DATA_INFO) + } + + @Test fun getFailsOnStorage() { + `when`(storage.get(KEY)).thenReturn(null) + + assertThat(hawkFacade.get(KEY)).isEqualTo(null) + + verify(storage).get(KEY) + verifyZeroInteractions(encryption, serializer, converter) + } + + @Test fun getFailsOnDeserialize() { + `when`(storage.get(KEY)).thenReturn(SERIALIZED_TEXT) + `when`(serializer.deserialize(SERIALIZED_TEXT)).thenReturn(null) + + assertThat(hawkFacade.get(KEY)).isEqualTo(null) + + val inOrder = inOrder(converter, encryption, serializer, storage) + inOrder.verify(storage).get(KEY) + inOrder.verify(serializer).deserialize(SERIALIZED_TEXT) + + verifyZeroInteractions(encryption, converter) + } + + @Test fun getFailsOnDecrypt() { + `when`(storage.get(KEY)).thenReturn(SERIALIZED_TEXT) + `when`(serializer.deserialize(SERIALIZED_TEXT)).thenReturn(DATA_INFO) + `when`(encryption.decrypt(KEY, CIPHER_TEXT)).thenReturn(null) + + assertThat(hawkFacade.get(KEY)).isEqualTo(null) + + val inOrder = inOrder(converter, encryption, serializer, storage) + inOrder.verify(storage).get(KEY) + inOrder.verify(serializer).deserialize(SERIALIZED_TEXT) + inOrder.verify(encryption).decrypt(KEY, CIPHER_TEXT) + + verifyZeroInteractions(converter) + } + + @Test fun getFailsOnConvert() { + `when`(storage.get(KEY)).thenReturn(SERIALIZED_TEXT) + `when`(serializer.deserialize(SERIALIZED_TEXT)).thenReturn(DATA_INFO) + `when`(encryption.decrypt(KEY, CIPHER_TEXT)).thenReturn(CONVERTED_TEXT) + `when`(converter.fromString(CONVERTED_TEXT, DATA_INFO)).thenReturn(null) + + assertThat(hawkFacade.get(KEY)).isEqualTo(null) + + val inOrder = inOrder(converter, encryption, serializer, storage) + inOrder.verify(storage).get(KEY) + inOrder.verify(serializer).deserialize(SERIALIZED_TEXT) + inOrder.verify(encryption).decrypt(KEY, CIPHER_TEXT) + inOrder.verify(converter).fromString(CONVERTED_TEXT, DATA_INFO) + } + + //endregion + + @Test fun count() { + `when`(storage.count()).thenReturn(100L) + + assertThat(hawkFacade.count()).isEqualTo(100L) + verifyZeroInteractions(encryption, converter, serializer) + } + + @Test fun deleteAll() { + `when`(storage.deleteAll()).thenReturn(true) + + assertThat(hawkFacade.deleteAll()).isTrue() + verifyZeroInteractions(encryption, converter, serializer) + } + + @Test fun delete() { + `when`(storage.delete(KEY)).thenReturn(true) + + assertThat(hawkFacade.delete(KEY)).isTrue() + verifyZeroInteractions(encryption, converter, serializer) + } + + @Test fun contains() { + `when`(storage.contains(KEY)).thenReturn(true) + + assertThat(hawkFacade.contains(KEY)).isTrue() + verifyZeroInteractions(encryption, converter, serializer) + } + + @Test fun isBuilt() { + assertThat(hawkFacade.isBuilt).isTrue() + } + + companion object { + + private const val KEY = "KEY" + private const val VALUE = "VALUE" + private const val CONVERTED_TEXT = "CONVERTED_TEXT" + private const val CIPHER_TEXT = "CIPHER_TEXT" + private const val SERIALIZED_TEXT = "SERIALIZED_TEXT" + private val DATA_INFO = DataInfo(DataInfo.TYPE_OBJECT, CIPHER_TEXT, String::class.java, null) + } +} \ No newline at end of file diff --git a/hawk/src/test/java/com/orhanobut/hawk/EmptyHawkFacadeTest.java b/hawk/src/test/java/com/orhanobut/hawk/EmptyHawkFacadeTest.java deleted file mode 100644 index ff5151a..0000000 --- a/hawk/src/test/java/com/orhanobut/hawk/EmptyHawkFacadeTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.orhanobut.hawk; - -import org.junit.Test; - -import static com.google.common.truth.Truth.assertThat; -import static junit.framework.Assert.fail; - -public class EmptyHawkFacadeTest { - - private final HawkFacade hawkFacade = new HawkFacade.EmptyHawkFacade(); - - private void assertFail(Exception e) { - assertThat(e).hasMessage("Hawk is not built. " + - "Please call build() and wait the initialisation finishes."); - } - - @Test public void put() { - try { - hawkFacade.put("key", "value"); - fail(""); - } catch (Exception e) { - assertFail(e); - } - } - - @Test public void get() { - try { - hawkFacade.get("key"); - fail(""); - } catch (Exception e) { - assertFail(e); - } - } - - @Test public void getWithDefault() { - try { - hawkFacade.get("key", "default"); - fail(""); - } catch (Exception e) { - assertFail(e); - } - } - - @Test public void count() { - try { - hawkFacade.count(); - fail(""); - } catch (Exception e) { - assertFail(e); - } - } - - @Test public void deleteAll() { - try { - hawkFacade.deleteAll(); - fail(""); - } catch (Exception e) { - assertFail(e); - } - } - - @Test public void delete() { - try { - hawkFacade.delete("key"); - fail(""); - } catch (Exception e) { - assertFail(e); - } - } - - @Test public void contains() { - try { - hawkFacade.contains("Key"); - fail(""); - } catch (Exception e) { - assertFail(e); - } - } - - @Test public void isBuilt() { - assertThat(hawkFacade.isBuilt()).isFalse(); - } -} \ No newline at end of file diff --git a/hawk/src/test/java/com/orhanobut/hawk/EmptyHawkFacadeTest.kt b/hawk/src/test/java/com/orhanobut/hawk/EmptyHawkFacadeTest.kt new file mode 100644 index 0000000..02907ce --- /dev/null +++ b/hawk/src/test/java/com/orhanobut/hawk/EmptyHawkFacadeTest.kt @@ -0,0 +1,89 @@ +package com.orhanobut.hawk + +import org.junit.Test + +import com.google.common.truth.Truth.assertThat +import junit.framework.Assert.fail + +class EmptyHawkFacadeTest { + + private val hawkFacade = HawkFacade.EmptyHawkFacade() + + private fun assertFail(e: Exception) { + assertThat(e).hasMessage("Hawk is not built. " + "Please call build() and wait the initialisation finishes.") + } + + @Test fun put() { + try { + hawkFacade.put("key", "value") + fail("") + } catch (e: Exception) { + assertFail(e) + } + + } + + @Test fun get() { + try { + hawkFacade.get("key") + fail("") + } catch (e: Exception) { + assertFail(e) + } + + } + + @Test fun getWithDefault() { + try { + hawkFacade.get("key", "default") + fail("") + } catch (e: Exception) { + assertFail(e) + } + + } + + @Test fun count() { + try { + hawkFacade.count() + fail("") + } catch (e: Exception) { + assertFail(e) + } + + } + + @Test fun deleteAll() { + try { + hawkFacade.deleteAll() + fail("") + } catch (e: Exception) { + assertFail(e) + } + + } + + @Test fun delete() { + try { + hawkFacade.delete("key") + fail("") + } catch (e: Exception) { + assertFail(e) + } + + } + + @Test fun contains() { + try { + hawkFacade.contains("Key") + fail("") + } catch (e: Exception) { + assertFail(e) + } + + } + + @Test fun isBuilt() { + assertThat(hawkFacade.isBuilt).isFalse() + } +} \ No newline at end of file diff --git a/hawk/src/test/java/com/orhanobut/hawk/FooBar.java b/hawk/src/test/java/com/orhanobut/hawk/FooBar.java deleted file mode 100644 index adc9b97..0000000 --- a/hawk/src/test/java/com/orhanobut/hawk/FooBar.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.orhanobut.hawk; - -class FooBar { - final String name = "hawk"; - - static class InnerFoo { - final String name = "hawk"; - } -} diff --git a/hawk/src/test/java/com/orhanobut/hawk/FooBar.kt b/hawk/src/test/java/com/orhanobut/hawk/FooBar.kt new file mode 100644 index 0000000..a987bd1 --- /dev/null +++ b/hawk/src/test/java/com/orhanobut/hawk/FooBar.kt @@ -0,0 +1,9 @@ +package com.orhanobut.hawk + +class FooBar { + val name = "hawk" + + class InnerFoo { + val name = "hawk" + } +} diff --git a/hawk/src/test/java/com/orhanobut/hawk/HawkBuilderTest.java b/hawk/src/test/java/com/orhanobut/hawk/HawkBuilderTest.java deleted file mode 100644 index bd0c252..0000000 --- a/hawk/src/test/java/com/orhanobut/hawk/HawkBuilderTest.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.orhanobut.hawk; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.RuntimeEnvironment; -import org.robolectric.annotation.Config; - -import java.lang.reflect.Type; - -import static com.google.common.truth.Truth.assertThat; -import static junit.framework.Assert.fail; -import static org.mockito.MockitoAnnotations.initMocks; - -@RunWith(RobolectricTestRunner.class) -@Config(constants = BuildConfig.class, sdk = 21) -public class HawkBuilderTest { - - private HawkBuilder builder; - - @Before public void setup() { - initMocks(this); - - builder = new HawkBuilder(RuntimeEnvironment.application); - } - - @Test public void testInit() { - try { - new HawkBuilder(null); - fail("Context should not be null"); - } catch (Exception e) { - assertThat(e).hasMessage("Context should not be null"); - } - } - - @Test public void testStorage() { - builder.build(); - assertThat(builder.getStorage()).isInstanceOf(SharedPreferencesStorage.class); - - class MyStorage implements Storage { - @Override public boolean put(String key, T value) { - return false; - } - - @Override public T get(String key) { - return null; - } - - @Override public boolean delete(String key) { - return false; - } - - @Override public boolean deleteAll() { - return false; - } - - @Override public long count() { - return 0; - } - - @Override public boolean contains(String key) { - return false; - } - } - builder.setStorage(new MyStorage()).build(); - assertThat(builder.getStorage()).isInstanceOf(MyStorage.class); - } - - @Test public void testParser() { - builder.build(); - assertThat(builder.getParser()).isInstanceOf(GsonParser.class); - - class MyParser implements Parser { - - @Override public T fromJson(String content, Type type) throws Exception { - return null; - } - - @Override public String toJson(Object body) { - return null; - } - } - builder.setParser(new MyParser()).build(); - assertThat(builder.getParser()).isInstanceOf(MyParser.class); - } - - @Test public void testConverter() { - builder.build(); - assertThat(builder.getConverter()).isInstanceOf(HawkConverter.class); - - class MyConverter implements Converter { - @Override public String toString(T value) { - return null; - } - - @Override public T fromString(String value, DataInfo dataInfo) throws Exception { - return null; - } - } - - builder.setConverter(new MyConverter()).build(); - assertThat(builder.getConverter()).isInstanceOf(MyConverter.class); - } - - @Test public void testSerializer() { - builder.build(); - assertThat(builder.getSerializer()).isInstanceOf(HawkSerializer.class); - - class MySerializer implements Serializer { - @Override public String serialize(String cipherText, T value) { - return null; - } - - @Override public DataInfo deserialize(String plainText) { - return null; - } - } - - builder.setSerializer(new MySerializer()).build(); - assertThat(builder.getSerializer()).isInstanceOf(MySerializer.class); - } - - @Test public void testEncryption() { - builder.build(); - assertThat(builder.getEncryption()).isInstanceOf(NoEncryption.class); - - class MyEncryption implements Encryption { - - @Override public boolean init() { - return false; - } - - @Override public String encrypt(String key, String value) throws Exception { - return null; - } - - @Override public String decrypt(String key, String value) throws Exception { - return null; - } - } - builder.setEncryption(new MyEncryption()).build(); - assertThat(builder.getEncryption()).isInstanceOf(MyEncryption.class); - } - - @Test public void testLogInterceptor() { - builder.build(); - assertThat(builder.getLogInterceptor()).isInstanceOf(LogInterceptor.class); - - class MyLogInterceptor implements LogInterceptor { - @Override public void onLog(String message) { - - } - } - builder.setLogInterceptor(new MyLogInterceptor()).build(); - assertThat(builder.getLogInterceptor()).isInstanceOf(MyLogInterceptor.class); - } -} diff --git a/hawk/src/test/java/com/orhanobut/hawk/HawkBuilderTest.kt b/hawk/src/test/java/com/orhanobut/hawk/HawkBuilderTest.kt new file mode 100644 index 0000000..12e9800 --- /dev/null +++ b/hawk/src/test/java/com/orhanobut/hawk/HawkBuilderTest.kt @@ -0,0 +1,162 @@ +package com.orhanobut.hawk + +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +import java.lang.reflect.Type + +import com.google.common.truth.Truth.assertThat +import junit.framework.Assert.fail +import org.mockito.MockitoAnnotations.initMocks + +@RunWith(RobolectricTestRunner::class) +class HawkBuilderTest { + + private lateinit var builder: HawkBuilder + + @Before fun setup() { + initMocks(this) + + builder = HawkBuilder(RuntimeEnvironment.application) + } + + @Test fun testInit() { + try { + HawkBuilder(null) + fail("Context should not be null") + } catch (e: Exception) { + assertThat(e).hasMessage("Context should not be null") + } + + } + + @Test fun testStorage() { + builder.build() + assertThat(builder.storage).isInstanceOf(SharedPreferencesStorage::class.java) + + class MyStorage : Storage { + override fun put(key: String, value: T): Boolean { + return false + } + + override fun get(key: String): T? { + return null + } + + override fun delete(key: String): Boolean { + return false + } + + override fun deleteAll(): Boolean { + return false + } + + override fun count(): Long { + return 0 + } + + override fun contains(key: String): Boolean { + return false + } + } + builder.setStorage(MyStorage()).build() + assertThat(builder.storage).isInstanceOf(MyStorage::class.java) + } + + @Test fun testParser() { + builder.build() + assertThat(builder.parser).isInstanceOf(GsonParser::class.java) + + class MyParser : Parser { + + @Throws(Exception::class) + override fun fromJson(content: String, type: Type): T? { + return null + } + + override fun toJson(body: Any): String? { + return null + } + } + builder.setParser(MyParser()).build() + assertThat(builder.parser).isInstanceOf(MyParser::class.java) + } + + @Test fun testConverter() { + builder.build() + assertThat(builder.converter).isInstanceOf(HawkConverter::class.java) + + class MyConverter : Converter { + override fun toString(value: T): String? { + return null + } + + @Throws(Exception::class) + override fun fromString(value: String, dataInfo: DataInfo): T? { + return null + } + } + + builder.setConverter(MyConverter()).build() + assertThat(builder.converter).isInstanceOf(MyConverter::class.java) + } + + @Test fun testSerializer() { + builder.build() + assertThat(builder.serializer).isInstanceOf(HawkSerializer::class.java) + + class MySerializer : Serializer { + override fun serialize(cipherText: String, value: T): String? { + return null + } + + override fun deserialize(plainText: String): DataInfo? { + return null + } + } + + builder.setSerializer(MySerializer()).build() + assertThat(builder.serializer).isInstanceOf(MySerializer::class.java) + } + + @Test fun testEncryption() { + builder.build() + assertThat(builder.encryption).isInstanceOf(NoEncryption::class.java) + + class MyEncryption : Encryption { + + override fun init(): Boolean { + return false + } + + @Throws(Exception::class) + override fun encrypt(key: String, value: String): String? { + return null + } + + @Throws(Exception::class) + override fun decrypt(key: String, value: String): String? { + return null + } + } + builder.setEncryption(MyEncryption()).build() + assertThat(builder.encryption).isInstanceOf(MyEncryption::class.java) + } + + @Test fun testLogInterceptor() { + builder.build() + assertThat(builder.logInterceptor).isInstanceOf(LogInterceptor::class.java) + + class MyLogInterceptor : LogInterceptor { + override fun onLog(message: String) { + + } + } + builder.setLogInterceptor(MyLogInterceptor()).build() + assertThat(builder.logInterceptor).isInstanceOf(MyLogInterceptor::class.java) + } +} diff --git a/hawk/src/test/java/com/orhanobut/hawk/HawkConverterTest.java b/hawk/src/test/java/com/orhanobut/hawk/HawkConverterTest.java deleted file mode 100644 index 1f157e9..0000000 --- a/hawk/src/test/java/com/orhanobut/hawk/HawkConverterTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.orhanobut.hawk; - -import com.google.gson.Gson; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.annotation.Config; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static com.google.common.truth.Truth.assertThat; -import static junit.framework.Assert.fail; - -@RunWith(RobolectricTestRunner.class) -@Config(constants = BuildConfig.class, sdk = 18) -public class HawkConverterTest { - - private Converter converter; - private Parser parser; - private Serializer serializer; - - static class Foo { - } - - @Before public void setup() { - parser = new GsonParser(new Gson()); - converter = new HawkConverter(parser); - serializer = new HawkSerializer(new LogInterceptor() { - @Override public void onLog(String message) { - // ignore - } - }); - } - - @Test public void createInstanceWithInvalidValues() { - try { - new HawkConverter(null); - fail(); - } catch (Exception e) { - assertThat(e).hasMessage("Parser should not be null"); - } - } - - @Test public void encodeInvalidValues() { - assertThat(converter.toString(null)).isNull(); - } - - @Test public void encodeString() { - String text = "text"; - String expected = parser.toJson(text); - String actual = converter.toString(text); - - assertThat(actual).isEqualTo(expected); - } - - @Test public void encodeCustomObject() { - Foo data = new Foo(); - String expected = parser.toJson(data); - String actual = converter.toString(data); - - assertThat(actual).isEqualTo(expected); - } - - @Test public void encodeList() { - List data = new ArrayList<>(); - data.add("test"); - String expected = parser.toJson(data); - String actual = converter.toString(data); - - assertThat(actual).isEqualTo(expected); - } - - @Test public void encodeMap() { - Map data = new HashMap<>(); - data.put("key", "value"); - String expected = parser.toJson(data); - String actual = converter.toString(data); - - assertThat(actual).isEqualTo(expected); - } - - @Test public void encodeSet() { - Set data = new HashSet<>(); - data.add("key"); - String expected = parser.toJson(data); - String actual = converter.toString(data); - - assertThat(actual).isEqualTo(expected); - } - - @Test public void decodeInvalidValues() throws Exception { - assertThat(converter.fromString(null, null)).isNull(); - try { - assertThat(converter.fromString("value", null)).isNull(); - fail(); - } catch (Exception e) { - assertThat(e).hasMessage("data info should not be null"); - } - } - - @Test public void decodeObject() throws Exception { - String clazz = "java.lang.String"; - String info = "00V"; - String cipher = "cipher"; - DataInfo dataInfo = serializer.deserialize(clazz + "##" + info + "@" + cipher); - String actual = converter.fromString(cipher, dataInfo); - assertThat(actual).isEqualTo(cipher); - } - -} diff --git a/hawk/src/test/java/com/orhanobut/hawk/HawkConverterTest.kt b/hawk/src/test/java/com/orhanobut/hawk/HawkConverterTest.kt new file mode 100644 index 0000000..050ed54 --- /dev/null +++ b/hawk/src/test/java/com/orhanobut/hawk/HawkConverterTest.kt @@ -0,0 +1,114 @@ +package com.orhanobut.hawk + +import com.google.gson.Gson + +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +import java.util.ArrayList +import java.util.HashMap +import java.util.HashSet + +import com.google.common.truth.Truth.assertThat +import junit.framework.Assert.fail + +@RunWith(RobolectricTestRunner::class) +class HawkConverterTest { + + private lateinit var converter: Converter + private lateinit var parser: Parser + private lateinit var serializer: Serializer + + internal class Foo + + @Before fun setup() { + parser = GsonParser(Gson()) + converter = HawkConverter(parser) + serializer = HawkSerializer(LogInterceptor { + // ignore + }) + } + + @Test fun createInstanceWithInvalidValues() { + try { + HawkConverter(null) + fail() + } catch (e: Exception) { + assertThat(e).hasMessage("Parser should not be null") + } + + } + + @Test fun encodeInvalidValues() { + assertThat(converter.toString(null)).isNull() + } + + @Test fun encodeString() { + val text = "text" + val expected = parser.toJson(text) + val actual = converter.toString(text) + + assertThat(actual).isEqualTo(expected) + } + + @Test fun encodeCustomObject() { + val data = Foo() + val expected = parser.toJson(data) + val actual = converter.toString(data) + + assertThat(actual).isEqualTo(expected) + } + + @Test fun encodeList() { + val data = ArrayList() + data.add("test") + val expected = parser.toJson(data) + val actual = converter.toString>(data) + + assertThat(actual).isEqualTo(expected) + } + + @Test fun encodeMap() { + val data = HashMap() + data["key"] = "value" + val expected = parser.toJson(data) + val actual = converter.toString>(data) + + assertThat(actual).isEqualTo(expected) + } + + @Test fun encodeSet() { + val data = HashSet() + data.add("key") + val expected = parser.toJson(data) + val actual = converter.toString>(data) + + assertThat(actual).isEqualTo(expected) + } + + @Test @Throws(Exception::class) + fun decodeInvalidValues() { + assertThat(converter.fromString(null, null)).isNull() + try { + assertThat(converter.fromString("value", null)).isNull() + fail() + } catch (e: Exception) { + assertThat(e).hasMessage("data info should not be null") + } + + } + + @Test @Throws(Exception::class) + fun decodeObject() { + val clazz = "java.lang.String" + val info = "00V" + val cipher = "cipher" + val dataInfo = serializer.deserialize("$clazz##$info@$cipher") + val actual = converter.fromString(cipher, dataInfo) + assertThat(actual).isEqualTo(cipher) + } + +} diff --git a/hawk/src/test/java/com/orhanobut/hawk/HawkFacadeIntegrationTest.java b/hawk/src/test/java/com/orhanobut/hawk/HawkFacadeIntegrationTest.java index c30904f..fa0c90c 100644 --- a/hawk/src/test/java/com/orhanobut/hawk/HawkFacadeIntegrationTest.java +++ b/hawk/src/test/java/com/orhanobut/hawk/HawkFacadeIntegrationTest.java @@ -18,7 +18,6 @@ import static com.google.common.truth.Truth.assertThat; @RunWith(RobolectricTestRunner.class) -@Config(constants = BuildConfig.class, sdk = 21) public class HawkFacadeIntegrationTest { @Before public void setUp() { @@ -52,12 +51,12 @@ public class HawkFacadeIntegrationTest { FooBar fooBar = Hawk.get("object"); assertThat(fooBar).isNotNull(); - assertThat(fooBar.name).isEqualTo("hawk"); + assertThat(fooBar.getName()).isEqualTo("hawk"); assertThat(Hawk.put("innerClass", new FooBar.InnerFoo())).isTrue(); FooBar.InnerFoo innerFoo = Hawk.get("innerClass"); assertThat(innerFoo).isNotNull(); - assertThat(innerFoo.name).isEqualTo("hawk"); + assertThat(innerFoo.getName()).isEqualTo("hawk"); } @Test public void testSingleItemDefault() { diff --git a/hawk/src/test/java/com/orhanobut/hawk/HawkSerializerTest.java b/hawk/src/test/java/com/orhanobut/hawk/HawkSerializerTest.java deleted file mode 100644 index 4e33f5d..0000000 --- a/hawk/src/test/java/com/orhanobut/hawk/HawkSerializerTest.java +++ /dev/null @@ -1,159 +0,0 @@ -package com.orhanobut.hawk; - -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static com.google.common.truth.Truth.assertThat; - -public class HawkSerializerTest { - - private static final String CIPHER_TEXT = "CIPHER"; - - private Serializer serializer; - - @Before public void setup() { - serializer = new HawkSerializer(new LogInterceptor() { - @Override public void onLog(String message) { - // ignore - } - }); - } - - static class Foo { - } - - @Test public void serializeString() { - String text = "test"; - String actual = serializer.serialize(CIPHER_TEXT, text); - String expected = text.getClass().getName() + "##0V@" + CIPHER_TEXT; - - assertThat(actual).isEqualTo(expected); - } - - @Test public void deserializeString() { - String clazz = "java.lang.String"; - String info = "00V"; - String cipher = "cipher"; - DataInfo dataInfo = serializer.deserialize(clazz + "#" + clazz + "#" + info + "@" + cipher); - - assertThat(dataInfo.keyClazz.getName()).isEqualTo(clazz); - assertThat(dataInfo.valueClazz.getName()).isEqualTo(clazz); - assertThat(dataInfo.dataType).isEqualTo(DataInfo.TYPE_OBJECT); - assertThat(dataInfo.cipherText).isEqualTo(cipher); - } - - @Test public void serializeCustomObject() { - Foo foo = new Foo(); - String actual = serializer.serialize(CIPHER_TEXT, foo); - String expected = foo.getClass().getName() + "##0V@" + CIPHER_TEXT; - - assertThat(actual).isEqualTo(expected); - } - - @Test public void deserializeCustomObject() { - String clazz = Foo.class.getName(); - String info = "00V"; - String cipher = "cipher"; - DataInfo dataInfo = serializer.deserialize(clazz + "#" + clazz + "#" + info + "@" + cipher); - - assertThat(dataInfo.keyClazz.getName()).isEqualTo(clazz); - assertThat(dataInfo.valueClazz.getName()).isEqualTo(clazz); - assertThat(dataInfo.dataType).isEqualTo(DataInfo.TYPE_OBJECT); - assertThat(dataInfo.cipherText).isEqualTo(cipher); - } - - @Test public void serializeEmptyList() { - List list = new ArrayList<>(); - String actual = serializer.serialize(CIPHER_TEXT, list); - String expected = "##1V@" + CIPHER_TEXT; - - assertThat(actual).isEqualTo(expected); - } - - @Test public void serializeList() { - List list = new ArrayList<>(); - list.add("test"); - String actual = serializer.serialize(CIPHER_TEXT, list); - String expected = String.class.getName() + "##1V@" + CIPHER_TEXT; - - assertThat(actual).isEqualTo(expected); - } - - @Test public void deserializeList() { - String clazz = "java.lang.String"; - String info = "1V"; - String cipher = "cipher"; - DataInfo dataInfo = serializer.deserialize(clazz + "##" + info + "@" + cipher); - - assertThat(dataInfo.keyClazz.getName()).isEqualTo(clazz); - assertThat(dataInfo.valueClazz).isNull(); - assertThat(dataInfo.dataType).isEqualTo(DataInfo.TYPE_LIST); - assertThat(dataInfo.cipherText).isEqualTo(cipher); - } - - @Test public void serializeEmptyMap() { - Map map = new HashMap<>(); - String actual = serializer.serialize(CIPHER_TEXT, map); - String expected = "##2V@" + CIPHER_TEXT; - - assertThat(actual).isEqualTo(expected); - } - - @Test public void serializeMap() { - Map map = new HashMap<>(); - map.put("key", "value"); - String actual = serializer.serialize(CIPHER_TEXT, map); - String expected = String.class.getName() + "#" + String.class.getName() + "#2V@" + CIPHER_TEXT; - - assertThat(actual).isEqualTo(expected); - } - - @Test public void deserializeMap() { - String clazz = "java.lang.String"; - String info = "2V"; - String cipher = "cipher"; - DataInfo dataInfo = serializer.deserialize(clazz + "#" + clazz + "#" + info + "@" + cipher); - - assertThat(dataInfo.keyClazz.getName()).isEqualTo(clazz); - assertThat(dataInfo.valueClazz.getName()).isEqualTo(clazz); - assertThat(dataInfo.dataType).isEqualTo(DataInfo.TYPE_MAP); - assertThat(dataInfo.cipherText).isEqualTo(cipher); - } - - @Test public void serializeEmptySet() { - Set set = new HashSet<>(); - String actual = serializer.serialize(CIPHER_TEXT, set); - String expected = "##3V@" + CIPHER_TEXT; - - assertThat(actual).isEqualTo(expected); - } - - @Test public void serializeSet() { - Set set = new HashSet<>(); - set.add("test"); - String actual = serializer.serialize(CIPHER_TEXT, set); - String expected = String.class.getName() + "##3V@" + CIPHER_TEXT; - - assertThat(actual).isEqualTo(expected); - } - - @Test public void deserializeSet() { - String clazz = "java.lang.String"; - String info = "3V"; - String cipher = "cipher"; - DataInfo dataInfo = serializer.deserialize(clazz + "##" + info + "@" + cipher); - - assertThat(dataInfo.keyClazz.getName()).isEqualTo(clazz); - assertThat(dataInfo.valueClazz).isNull(); - assertThat(dataInfo.dataType).isEqualTo(DataInfo.TYPE_SET); - assertThat(dataInfo.cipherText).isEqualTo(cipher); - } - -} \ No newline at end of file diff --git a/hawk/src/test/java/com/orhanobut/hawk/HawkSerializerTest.kt b/hawk/src/test/java/com/orhanobut/hawk/HawkSerializerTest.kt new file mode 100644 index 0000000..daa4e79 --- /dev/null +++ b/hawk/src/test/java/com/orhanobut/hawk/HawkSerializerTest.kt @@ -0,0 +1,151 @@ +package com.orhanobut.hawk + +import org.junit.Before +import org.junit.Test + +import java.util.ArrayList +import java.util.HashMap +import java.util.HashSet + +import com.google.common.truth.Truth.assertThat + +class HawkSerializerTest { + + private val CIPHER_TEXT = "CIPHER" + private lateinit var serializer: Serializer + + @Before fun setup() { + serializer = HawkSerializer(LogInterceptor { + // ignore + }) + } + + internal class Foo + + @Test fun serializeString() { + val text = "test" + val actual = serializer.serialize(CIPHER_TEXT, text) + val expected = text.javaClass.name + "##0V@" + CIPHER_TEXT + + assertThat(actual).isEqualTo(expected) + } + + @Test fun deserializeString() { + val clazz = "java.lang.String" + val info = "00V" + val cipher = "cipher" + val dataInfo = serializer.deserialize("$clazz#$clazz#$info@$cipher") + + assertThat(dataInfo.keyClazz.name).isEqualTo(clazz) + assertThat(dataInfo.valueClazz.name).isEqualTo(clazz) + assertThat(dataInfo.dataType).isEqualTo(DataInfo.TYPE_OBJECT) + assertThat(dataInfo.cipherText).isEqualTo(cipher) + } + + @Test fun serializeCustomObject() { + val foo = Foo() + val actual = serializer.serialize(CIPHER_TEXT, foo) + val expected = foo.javaClass.name + "##0V@" + CIPHER_TEXT + + assertThat(actual).isEqualTo(expected) + } + + @Test fun deserializeCustomObject() { + val clazz = Foo::class.java.name + val info = "00V" + val cipher = "cipher" + val dataInfo = serializer.deserialize("$clazz#$clazz#$info@$cipher") + + assertThat(dataInfo.keyClazz.name).isEqualTo(clazz) + assertThat(dataInfo.valueClazz.name).isEqualTo(clazz) + assertThat(dataInfo.dataType).isEqualTo(DataInfo.TYPE_OBJECT) + assertThat(dataInfo.cipherText).isEqualTo(cipher) + } + + @Test fun serializeEmptyList() { + val list = ArrayList() + val actual = serializer.serialize>(CIPHER_TEXT, list) + val expected = "##1V@$CIPHER_TEXT" + + assertThat(actual).isEqualTo(expected) + } + + @Test fun serializeList() { + val list = ArrayList() + list.add("test") + val actual = serializer.serialize>(CIPHER_TEXT, list) + val expected = String::class.java.name + "##1V@" + CIPHER_TEXT + + assertThat(actual).isEqualTo(expected) + } + + @Test fun deserializeList() { + val clazz = "java.lang.String" + val info = "1V" + val cipher = "cipher" + val dataInfo = serializer.deserialize("$clazz##$info@$cipher") + + assertThat(dataInfo.keyClazz.name).isEqualTo(clazz) + assertThat(dataInfo.valueClazz).isNull() + assertThat(dataInfo.dataType).isEqualTo(DataInfo.TYPE_LIST) + assertThat(dataInfo.cipherText).isEqualTo(cipher) + } + + @Test fun serializeEmptyMap() { + val map = HashMap() + val actual = serializer.serialize>(CIPHER_TEXT, map) + val expected = "##2V@$CIPHER_TEXT" + + assertThat(actual).isEqualTo(expected) + } + + @Test fun serializeMap() { + val map = HashMap() + map["key"] = "value" + val actual = serializer.serialize>(CIPHER_TEXT, map) + val expected = String::class.java.name + "#" + String::class.java.name + "#2V@" + CIPHER_TEXT + + assertThat(actual).isEqualTo(expected) + } + + @Test fun deserializeMap() { + val clazz = "java.lang.String" + val info = "2V" + val cipher = "cipher" + val dataInfo = serializer.deserialize("$clazz#$clazz#$info@$cipher") + + assertThat(dataInfo.keyClazz.name).isEqualTo(clazz) + assertThat(dataInfo.valueClazz.name).isEqualTo(clazz) + assertThat(dataInfo.dataType).isEqualTo(DataInfo.TYPE_MAP) + assertThat(dataInfo.cipherText).isEqualTo(cipher) + } + + @Test fun serializeEmptySet() { + val set = HashSet() + val actual = serializer.serialize>(CIPHER_TEXT, set) + val expected = "##3V@$CIPHER_TEXT" + + assertThat(actual).isEqualTo(expected) + } + + @Test fun serializeSet() { + val set = HashSet() + set.add("test") + val actual = serializer.serialize>(CIPHER_TEXT, set) + val expected = String::class.java.name + "##3V@" + CIPHER_TEXT + + assertThat(actual).isEqualTo(expected) + } + + @Test fun deserializeSet() { + val clazz = "java.lang.String" + val info = "3V" + val cipher = "cipher" + val dataInfo = serializer.deserialize("$clazz##$info@$cipher") + + assertThat(dataInfo.keyClazz.name).isEqualTo(clazz) + assertThat(dataInfo.valueClazz).isNull() + assertThat(dataInfo.dataType).isEqualTo(DataInfo.TYPE_SET) + assertThat(dataInfo.cipherText).isEqualTo(cipher) + } +} \ No newline at end of file diff --git a/hawk/src/test/java/com/orhanobut/hawk/HawkTest.java b/hawk/src/test/java/com/orhanobut/hawk/HawkTest.java deleted file mode 100644 index 4dca8fa..0000000 --- a/hawk/src/test/java/com/orhanobut/hawk/HawkTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.orhanobut.hawk; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; - -import static com.google.common.truth.Truth.assertThat; -import static junit.framework.Assert.fail; -import static org.mockito.Mockito.verify; -import static org.mockito.MockitoAnnotations.initMocks; - -public class HawkTest { - - @Mock HawkFacade hawkFacade; - @Mock Context context; - - @Before public void setup() { - initMocks(this); - - Hawk.hawkFacade = hawkFacade; - } - - @After public void tearDown() { - Hawk.destroy(); - } - - @Test public void testInit() { - try { - Hawk.init(null); - fail("context should not be null"); - } catch (Exception e) { - assertThat(e).hasMessage("Context should not be null"); - } - } - - @Test public void put() { - Hawk.put("key", "value"); - - verify(hawkFacade).put("key", "value"); - } - - @Test public void get() { - Hawk.get("key"); - - verify(hawkFacade).get("key"); - } - - @Test public void getWithDefault() { - Hawk.get("key", "default"); - - verify(hawkFacade).get("key", "default"); - } - - @Test public void count() { - Hawk.count(); - - verify(hawkFacade).count(); - } - - @Test public void deleteAll() { - Hawk.deleteAll(); - - verify(hawkFacade).deleteAll(); - } - - @Test public void delete() { - Hawk.delete("key"); - - verify(hawkFacade).delete("key"); - } - - @Test public void contains() { - Hawk.contains("key"); - - verify(hawkFacade).contains("key"); - } - - @Test public void isBuilt() { - Hawk.isBuilt(); - - verify(hawkFacade).isBuilt(); - } - -} diff --git a/hawk/src/test/java/com/orhanobut/hawk/HawkTest.kt b/hawk/src/test/java/com/orhanobut/hawk/HawkTest.kt new file mode 100644 index 0000000..b783883 --- /dev/null +++ b/hawk/src/test/java/com/orhanobut/hawk/HawkTest.kt @@ -0,0 +1,84 @@ +package com.orhanobut.hawk + +import com.google.common.truth.Truth.assertThat +import junit.framework.Assert.fail +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.mockito.Mock +import org.mockito.Mockito.verify +import org.mockito.MockitoAnnotations.initMocks + +class HawkTest { + + @Mock private lateinit var hawkFacade: HawkFacade + + @Before fun setup() { + initMocks(this) + + Hawk.hawkFacade = hawkFacade + } + + @After fun tearDown() { + Hawk.destroy() + } + + @Test fun testInit() { + try { + Hawk.init(null) + fail("context should not be null") + } catch (e: Exception) { + assertThat(e).hasMessage("Context should not be null") + } + + } + + @Test fun put() { + Hawk.put("key", "value") + + verify(hawkFacade).put("key", "value") + } + + @Test fun get() { + Hawk.get("key") + + verify(hawkFacade).get("key") + } + + @Test fun getWithDefault() { + Hawk.get("key", "default") + + verify(hawkFacade).get("key", "default") + } + + @Test fun count() { + Hawk.count() + + verify(hawkFacade).count() + } + + @Test fun deleteAll() { + Hawk.deleteAll() + + verify(hawkFacade).deleteAll() + } + + @Test fun delete() { + Hawk.delete("key") + + verify(hawkFacade).delete("key") + } + + @Test fun contains() { + Hawk.contains("key") + + verify(hawkFacade).contains("key") + } + + @Test fun isBuilt() { + Hawk.isBuilt() + + verify(hawkFacade).isBuilt + } + +} diff --git a/hawk/src/test/java/com/orhanobut/hawk/HawkUtilsTest.java b/hawk/src/test/java/com/orhanobut/hawk/HawkUtilsTest.java deleted file mode 100644 index 7d5382f..0000000 --- a/hawk/src/test/java/com/orhanobut/hawk/HawkUtilsTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.orhanobut.hawk; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.annotation.Config; - -import static com.google.common.truth.Truth.assertThat; -import static junit.framework.Assert.fail; - - -@RunWith(RobolectricTestRunner.class) -@Config(sdk = 21, constants = BuildConfig.class) -public class HawkUtilsTest { - - @Test public void checkNullShouldDoNothing() { - try { - HawkUtils.checkNull("foo", "test"); - } catch (Exception e) { - fail("it should not throw exception"); - } - } - - @Test public void checkNullShouldThrowException() throws Exception { - try { - HawkUtils.checkNull("foo", null); - fail("should throw exception"); - } catch (Exception e) { - assertThat(e).hasMessage("foo should not be null"); - } - } - - @Test public void checkNullOrEmptyThrowException() throws Exception { - try { - HawkUtils.checkNullOrEmpty("foo", null); - fail("should throw exception"); - } catch (Exception e) { - assertThat(e).hasMessage("foo should not be null or empty"); - } - } - - @Test public void checkNullOrEmptyShouldDoNothing() throws Exception { - try { - HawkUtils.checkNullOrEmpty("foo", "bar"); - } catch (Exception e) { - fail("should not throw exception"); - } - } - - @Test public void isEmpty() throws Exception { - assertThat(HawkUtils.isEmpty(null)).isTrue(); - assertThat(HawkUtils.isEmpty("")).isTrue(); - assertThat(HawkUtils.isEmpty(" ")).isTrue(); - assertThat(HawkUtils.isEmpty("foo")).isFalse(); - } -} \ No newline at end of file diff --git a/hawk/src/test/java/com/orhanobut/hawk/HawkUtilsTest.kt b/hawk/src/test/java/com/orhanobut/hawk/HawkUtilsTest.kt new file mode 100644 index 0000000..a672771 --- /dev/null +++ b/hawk/src/test/java/com/orhanobut/hawk/HawkUtilsTest.kt @@ -0,0 +1,54 @@ +package com.orhanobut.hawk + +import com.google.common.truth.Truth.assertThat +import junit.framework.Assert.fail +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + + +@RunWith(RobolectricTestRunner::class) +class HawkUtilsTest { + + @Test fun checkNullShouldDoNothing() { + try { + HawkUtils.checkNull("foo", "test") + } catch (e: Exception) { + fail("it should not throw exception") + } + + } + + @Test fun checkNullShouldThrowException() { + try { + HawkUtils.checkNull("foo", null) + fail("should throw exception") + } catch (e: Exception) { + assertThat(e).hasMessage("foo should not be null") + } + } + + @Test fun checkNullOrEmptyThrowException() { + try { + HawkUtils.checkNullOrEmpty("foo", null) + fail("should throw exception") + } catch (e: Exception) { + assertThat(e).hasMessage("foo should not be null or empty") + } + } + + @Test fun checkNullOrEmptyShouldDoNothing() { + try { + HawkUtils.checkNullOrEmpty("foo", "bar") + } catch (e: Exception) { + fail("should not throw exception") + } + } + + @Test fun isEmpty() { + assertThat(HawkUtils.isEmpty(null)).isTrue() + assertThat(HawkUtils.isEmpty("")).isTrue() + assertThat(HawkUtils.isEmpty(" ")).isTrue() + assertThat(HawkUtils.isEmpty("foo")).isFalse() + } +} \ No newline at end of file diff --git a/hawk/src/test/java/com/orhanobut/hawk/NoEncryptionTest.java b/hawk/src/test/java/com/orhanobut/hawk/NoEncryptionTest.java deleted file mode 100644 index 261d875..0000000 --- a/hawk/src/test/java/com/orhanobut/hawk/NoEncryptionTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.orhanobut.hawk; - -import android.util.Base64; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Spy; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.annotation.Config; - -import static com.google.common.truth.Truth.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.MockitoAnnotations.initMocks; - -@RunWith(RobolectricTestRunner.class) -@Config(sdk = 21, constants = BuildConfig.class) -public class NoEncryptionTest { - - @Spy NoEncryption encryption; - - @Before public void setup() { - encryption = new NoEncryption(); - - initMocks(this); - } - - @Test public void init() throws Exception { - assertThat(encryption.init()).isTrue(); - } - - @Test public void encrypt() throws Exception { - encryption.encrypt("key", "value"); - - verify(encryption).encodeBase64(any(byte[].class)); - } - - @Test public void decrypt() throws Exception { - encryption.decrypt("key", "test"); - - verify(encryption).decrypt("key", "test"); - } - - @Test public void encodeBase64() { - String text = "hawk"; - String expected = Base64.encodeToString(text.getBytes(), Base64.DEFAULT); - String actual = encryption.encodeBase64(text.getBytes()); - - assertThat(actual).isNotNull(); - assertThat(actual).isEqualTo(expected); - } - - @Test public void decodeBase64() { - String text = "hawk"; - byte[] expected = Base64.decode(text, Base64.DEFAULT); - byte[] actual = encryption.decodeBase64(text); - - assertThat(actual).isNotNull(); - assertThat(actual).isEqualTo(expected); - } -} \ No newline at end of file diff --git a/hawk/src/test/java/com/orhanobut/hawk/NoEncryptionTest.kt b/hawk/src/test/java/com/orhanobut/hawk/NoEncryptionTest.kt new file mode 100644 index 0000000..01ea6da --- /dev/null +++ b/hawk/src/test/java/com/orhanobut/hawk/NoEncryptionTest.kt @@ -0,0 +1,61 @@ +package com.orhanobut.hawk + +import android.util.Base64 + +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Spy +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +import com.google.common.truth.Truth.assertThat +import org.mockito.Matchers.any +import org.mockito.Mockito.verify +import org.mockito.MockitoAnnotations.initMocks + +@RunWith(RobolectricTestRunner::class) +class NoEncryptionTest { + + @Spy private lateinit var encryption: NoEncryption + + @Before fun setup() { + encryption = NoEncryption() + + initMocks(this) + } + + @Test fun init() { + assertThat(encryption.init()).isTrue() + } + + @Test fun encrypt() { + encryption.encrypt("key", "value") + + verify(encryption).encodeBase64(any(ByteArray::class.java)) + } + + @Test fun decrypt() { + encryption.decrypt("key", "test") + + verify(encryption).decrypt("key", "test") + } + + @Test fun encodeBase64() { + val text = "hawk" + val expected = Base64.encodeToString(text.toByteArray(), Base64.DEFAULT) + val actual = encryption.encodeBase64(text.toByteArray()) + + assertThat(actual).isNotNull() + assertThat(actual).isEqualTo(expected) + } + + @Test fun decodeBase64() { + val text = "hawk" + val expected = Base64.decode(text, Base64.DEFAULT) + val actual = encryption.decodeBase64(text) + + assertThat(actual).isNotNull() + assertThat(actual).isEqualTo(expected) + } +} \ No newline at end of file diff --git a/hawk/src/test/java/com/orhanobut/hawk/SharedPreferencesStorageTest.java b/hawk/src/test/java/com/orhanobut/hawk/SharedPreferencesStorageTest.java deleted file mode 100644 index 4083c6e..0000000 --- a/hawk/src/test/java/com/orhanobut/hawk/SharedPreferencesStorageTest.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.orhanobut.hawk; - -import android.content.SharedPreferences; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.annotation.Config; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import static com.google.common.truth.Truth.assertThat; -import static junit.framework.Assert.fail; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; - -@RunWith(RobolectricTestRunner.class) -@Config(manifest = Config.NONE) -public class SharedPreferencesStorageTest { - - private SharedPreferencesStorage storage; - private SharedPreferences.Editor editor; - private SharedPreferences preferences; - - @Before public void setup() { - editor = spy(new SharedPreferences.Editor() { - @Override public SharedPreferences.Editor putString(String key, String value) { - return this; - } - - @Override public SharedPreferences.Editor putStringSet(String key, Set values) { - return this; - } - - @Override public SharedPreferences.Editor putInt(String key, int value) { - return this; - } - - @Override public SharedPreferences.Editor putLong(String key, long value) { - return this; - } - - @Override public SharedPreferences.Editor putFloat(String key, float value) { - return this; - } - - @Override public SharedPreferences.Editor putBoolean(String key, boolean value) { - return this; - } - - @Override public SharedPreferences.Editor remove(String key) { - return this; - } - - @Override public SharedPreferences.Editor clear() { - return this; - } - - @Override public boolean commit() { - return true; - } - - @Override public void apply() { - } - }); - preferences = spy(new SharedPreferences() { - @Override public Map getAll() { - Map map = new HashMap<>(); - map.put("key", "value"); - return map; - } - - @Override public String getString(String key, String defValue) { - return null; - } - - @Override public Set getStringSet(String key, Set defValues) { - return null; - } - - @Override public int getInt(String key, int defValue) { - return 0; - } - - @Override public long getLong(String key, long defValue) { - return 0; - } - - @Override public float getFloat(String key, float defValue) { - return 0; - } - - @Override public boolean getBoolean(String key, boolean defValue) { - return false; - } - - @Override public boolean contains(String key) { - return false; - } - - @Override public Editor edit() { - return editor; - } - - @Override public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { - - } - - @Override public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { - - } - }); - storage = new SharedPreferencesStorage(preferences); - } - - @Test public void putObject() throws Exception { - storage.put("key", "value"); - - verify(preferences).edit(); - verify(editor).putString("key", "value"); - verify(editor).commit(); - } - - @Test public void throwExceptionOnNullKeysPassedOnPut() { - try { - storage.put(null, "value"); - fail("key should not be null"); - } catch (Exception e) { - assertThat(e).hasMessage("key should not be null"); - } - } - - @Test public void get() throws Exception { - storage.get("key"); - - verify(preferences).getString("key", null); - } - - @Test public void remove() throws Exception { - storage.delete("key"); - - verify(preferences).edit(); - verify(editor).remove("key"); - verify(editor).commit(); - } - - @Test public void contains() throws Exception { - storage.contains("key"); - - verify(preferences).contains("key"); - } - - @Test public void deleteAll() throws Exception { - storage.deleteAll(); - - verify(preferences).edit(); - verify(editor).clear(); - verify(editor).commit(); - } - - @Test public void count() throws Exception { - long count = storage.count(); - - verify(preferences).getAll(); - assertThat(count).isEqualTo(1); - } -} \ No newline at end of file diff --git a/hawk/src/test/java/com/orhanobut/hawk/SharedPreferencesStorageTest.kt b/hawk/src/test/java/com/orhanobut/hawk/SharedPreferencesStorageTest.kt new file mode 100644 index 0000000..fcfa6ff --- /dev/null +++ b/hawk/src/test/java/com/orhanobut/hawk/SharedPreferencesStorageTest.kt @@ -0,0 +1,167 @@ +package com.orhanobut.hawk + +import android.content.SharedPreferences + +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +import java.util.HashMap + +import com.google.common.truth.Truth.assertThat +import junit.framework.Assert.fail +import org.mockito.Mockito.spy +import org.mockito.Mockito.verify + +@RunWith(RobolectricTestRunner::class) +class SharedPreferencesStorageTest { + + private lateinit var storage: SharedPreferencesStorage + private lateinit var editor: SharedPreferences.Editor + private lateinit var preferences: SharedPreferences + + @Before fun setup() { + editor = spy(object : SharedPreferences.Editor { + override fun putString(key: String, value: String?): SharedPreferences.Editor { + return this + } + + override fun putStringSet(key: String, values: Set?): SharedPreferences.Editor { + return this + } + + override fun putInt(key: String, value: Int): SharedPreferences.Editor { + return this + } + + override fun putLong(key: String, value: Long): SharedPreferences.Editor { + return this + } + + override fun putFloat(key: String, value: Float): SharedPreferences.Editor { + return this + } + + override fun putBoolean(key: String, value: Boolean): SharedPreferences.Editor { + return this + } + + override fun remove(key: String): SharedPreferences.Editor { + return this + } + + override fun clear(): SharedPreferences.Editor { + return this + } + + override fun commit(): Boolean { + return true + } + + override fun apply() {} + }) + preferences = spy(object : SharedPreferences { + override fun getAll(): Map { + val map = HashMap() + map["key"] = "value" + return map + } + + override fun getString(key: String, defValue: String?): String? { + return null + } + + override fun getStringSet(key: String, defValues: Set?): Set? { + return null + } + + override fun getInt(key: String, defValue: Int): Int { + return 0 + } + + override fun getLong(key: String, defValue: Long): Long { + return 0 + } + + override fun getFloat(key: String, defValue: Float): Float { + return 0f + } + + override fun getBoolean(key: String, defValue: Boolean): Boolean { + return false + } + + override fun contains(key: String): Boolean { + return false + } + + override fun edit(): SharedPreferences.Editor? { + return editor + } + + override fun registerOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) { + + } + + override fun unregisterOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) { + + } + }) + storage = SharedPreferencesStorage(preferences) + } + + @Test fun putObject() { + storage.put("key", "value") + + verify(preferences).edit() + verify(editor).putString("key", "value") + verify(editor).commit() + } + + @Test fun throwExceptionOnNullKeysPassedOnPut() { + try { + storage.put(null, "value") + fail("key should not be null") + } catch (e: Exception) { + assertThat(e).hasMessage("key should not be null") + } + + } + + @Test fun get() { + storage.get("key") + + verify(preferences).getString("key", null) + } + + @Test fun remove() { + storage.delete("key") + + verify(preferences).edit() + verify(editor).remove("key") + verify(editor).commit() + } + + @Test fun contains() { + storage.contains("key") + + verify(preferences).contains("key") + } + + @Test fun deleteAll() { + storage.deleteAll() + + verify(preferences).edit() + verify(editor).clear() + verify(editor).commit() + } + + @Test fun count() { + val count = storage.count() + + verify(preferences).all + assertThat(count).isEqualTo(1) + } +} \ No newline at end of file diff --git a/hawk/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/hawk/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker new file mode 100644 index 0000000..ca6ee9c --- /dev/null +++ b/hawk/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker @@ -0,0 +1 @@ +mock-maker-inline \ No newline at end of file