diff --git a/.travis.yml b/.travis.yml index dc4c9691..6e0beddd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,14 +1,30 @@ language: android +jdk: oraclejdk7 +env: + global: + - TERM=dumb android: components: - sys-img-armeabi-v7a-android-23 - tools - - build-tools-23.0.2 + - build-tools-23.0.3 - android-23 - + - extra-android-m2repository +before_script: + - sudo service postgresql stop || true + - sudo service mysql stop || true + - sudo service memcached stop || true + - sudo service bootlogd stop || true + - sudo service elasticsearch stop || true + - sudo service mongodb stop || true + - sudo service neo4j stop || true + - sudo service cassandra stop || true + - sudo service riak stop || true + - sudo service rsync stop || true + - sudo service x11-common stop || true script: - - gradle clean build connectedCheck coveralls + - ./gradlew clean build connectedCheck coveralls cache: directories: diff --git a/CHANGELOG.md b/CHANGELOG.md index 3507a180..7015053d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,12 @@ # Sugar Releases ## [Unreleased] + + +## v1.5 ### Added +* [#328](https://github.com/satyan/sugar/pull/328) @jedid auto add new columns during database upgrade, fix [#299](https://github.com/satyan/sugar/issues/299) and [#151](https://github.com/satyan/sugar/issues/151) +* [#389](https://github.com/satyan/sugar/pull/389) @alfmatos MultiUnique DSL to handle MultiColumn Unique Table constraint * @sibeliusseraphini update, updateInTx methods based on Unique values of SugarRecord * [#155](https://github.com/satyan/sugar/issues/155) @benohalloran adding Cursors for Cursor Adapters [Pull 312](https://github.com/satyan/sugar/pull/312) * [#430](https://github.com/satyan/sugar/pull/430) @sibeliusseraphini update to roboelectric 3.0 and target android-32 @@ -11,6 +16,8 @@ * [#423](https://github.com/satyan/sugar/pull/423) @sibeliusseraphini moving changelog of README.md to CHANGELOG.md ### Fixed +* [#362](https://github.com/satyan/sugar/pull/362) @mitchyboy9 fixed NoClassDefFoundError +* [#455](https://github.com/satyan/sugar/pull/455) @nurolopher fixed travis and coveralls config * [#434](https://github.com/satyan/sugar/pull/434) @bendaniel10 fix multi-dex * [#410](https://github.com/satyan/sugar/pull/410) [#408](https://github.com/satyan/sugar/pull/408) @RoyMontoya simplify code * [#327](https://github.com/satyan/sugar/pull/327) @tracytheron support multi-dex diff --git a/README.md b/README.md index f4d129a5..d4d7c79d 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,15 @@ -# Sugar ORM [![Build Status](https://travis-ci.org/satyan/sugar.svg?branch=master)](https://travis-ci.org/satyan/sugar) [![Coverage Status](https://coveralls.io/repos/satyan/sugar/badge.svg?branch=master)](https://coveralls.io/r/satyan/sugar?branch=master) +# Sugar ORM [![Build Status](https://travis-ci.org/satyan/sugar.svg?branch=master)](https://travis-ci.org/satyan/sugar) [![Coverage Status](https://coveralls.io/repos/satyan/sugar/badge.svg?branch=master)](https://coveralls.io/r/satyan/sugar?branch=master) [![Code Triagers Badge](http://www.codetriage.com/satyan/sugar/badges/users.svg)](http://www.codetriage.com/satyan/sugar) + +[![Join the chat at https://gitter.im/satyan/sugar](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/satyan/sugar?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) Insanely easy way to work with Android databases. -Official documentation can be found [here](http://satyan.github.io/sugar). The example application is provided in the **example** folder in the source. +Official documentation can be found [here](http://satyan.github.io/sugar) - Check some examples below. The example application is provided in the **example** folder in the source. + +## Looking for contributors +We need contributors to help maintain this project, ask @satyan for repo permission + +Otherwise you can use another ORM, like https://github.com/requery/requery or https://realm.io/ ## Features @@ -21,7 +28,7 @@ There are four ways to install Sugar: This is the preferred way. Simply add: ```groovy -compile 'com.github.satyan:sugar:1.4' +compile 'com.github.satyan:sugar:1.5' ``` to your project dependencies and run `gradle build` or `gradle assemble`. @@ -34,7 +41,7 @@ Declare the dependency in Maven: com.github.satyan sugar - 1.4 + 1.5 ``` @@ -46,13 +53,52 @@ Download the source code and import it as a library project in Eclipse. The proj Visit the [releases](https://github.com/satyan/sugar/releases) page to download jars directly. You can drop them into your `libs` folder and configure the Java build path to include the library. See this [tutorial](http://www.vogella.com/tutorials/AndroidLibraryProjects/article.html) for an excellent guide on how to do this. + +### How to use master version +First, download sugar repository +``` +git clone git@github.com:satyan/sugar.git +``` + +include this in your **settings.gradle** +```gradle +include ':app' // your module app +include ':sugar' + +def getLocalProperty(prop) { + Properties properties = new Properties() + properties.load(new File(rootDir.absolutePath + '/local.properties').newDataInputStream()) + return properties.getProperty(prop, '') +} + +project(':sugar').projectDir = new File(getLocalProperty('sugar.dir')) + +``` + +include this in your **local.properties** +``` +sugar.dir=/path/to/sugar/library +``` + +add sugar project to the dependencies of your main project (build.gradle) +```gradle +dependencies { + compile project(':sugar') +} +``` + +You should also comment this line just comment this line (library/build.gradle): https://github.com/satyan/sugar/blob/master/library%2Fbuild.gradle#L2 + +```gradle +// apply from: '../maven_push.gradle' +``` =================== -After installing, check out how to set up your first database and models [here](http://satyan.github.io/sugar/getting-started.html). +After installing, check out how to set up your first database and models [here](http://satyan.github.io/sugar/getting-started.html) **Outdated**. Check examples of 1.4 and master below: ## Examples ### SugarRecord -``` +```java public class Book extends SugarRecord { @Unique String isbn; @@ -72,38 +118,49 @@ public class Book extends SugarRecord { } ``` or -``` +```java @Table public class Book { ... } ``` ### Save Entity -``` +```java Book book = new Book("isbn123", "Title here", "2nd edition") book.save(); ``` -### Load Entity +or +```java +SugarRecord.save(book); // if using the @Table annotation ``` + +### Load Entity +```java Book book = Book.findById(Book.class, 1); ``` ### Update Entity -``` +```java Book book = Book.findById(Book.class, 1); book.title = "updated title here"; // modify the values book.edition = "3rd edition"; book.save(); // updates the previous entry with new values. ``` + ### Delete Entity -``` +```java Book book = Book.findById(Book.class, 1); book.delete(); ``` -### Update Entity based on Unique values +or +```java +SugarRecord.delete(book); // if using the @Table annotation ``` + +### Update Entity based on Unique values +```java Book book = new Book("isbn123", "Title here", "2nd edition") book.save(); @@ -114,8 +171,13 @@ sameBook.update(); book.getId() == sameBook.getId(); // true ``` -### Bulk Insert +or +```java +SugarRecord.update(sameBook); // if using the @Table annotation ``` + +### Bulk Insert +```java List books = new ArrayList<>(); books.add(new Book("isbn123", "Title here", "2nd edition")) books.add(new Book("isbn456", "Title here 2", "3nd edition")) @@ -123,6 +185,14 @@ books.add(new Book("isbn789", "Title here 3", "4nd edition")) SugarRecord.saveInTx(books); ``` +### When using ProGuard +```java +# Ensures entities remain un-obfuscated so table and columns are named correctly +-keep class com.yourpackage.yourapp.domainclasspackage.** { *; } +``` + +## [CHANGELOG](https://github.com/satyan/sugar/blob/master/CHANGELOG.md) + ## Contributing Please fork this repository and contribute back using [pull requests](https://github.com/satyan/sugar/pulls). Features can be requested using [issues](https://github.com/satyan/sugar/issues). All code, comments, and critiques are greatly appreciated. diff --git a/build.gradle b/build.gradle index c6970775..030e1cb3 100644 --- a/build.gradle +++ b/build.gradle @@ -1,12 +1,13 @@ apply plugin: 'jacoco' apply plugin: 'com.github.kt3k.coveralls' +apply plugin: 'java' buildscript { repositories { mavenCentral() } dependencies { - classpath 'com.android.tools.build:gradle:1.3.0' + classpath 'com.android.tools.build:gradle:2.0.0' classpath 'org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.3.1' } } @@ -14,7 +15,11 @@ buildscript { def isReleaseBuild() { return version.contains("SNAPSHOT") == false } - +test{ + testLogging{ + exceptionFormat = 'full' + } +} allprojects { version = VERSION_NAME group = GROUP @@ -33,7 +38,7 @@ subprojects { proj -> version "0.7.1.201405082137" } - task jacocoTestReport(type: JacocoReport, dependsOn: "testDebug") { + task jacocoTestReport(type: JacocoReport) { group = "Reporting" description = "Generate Jacoco coverage reports after running tests." reports { @@ -45,7 +50,7 @@ subprojects { proj -> excludes: ['**/R*.class', '**/BuildConfig*']) sourceDirectories = files('src/main/java') - executionData = files('build/jacoco/testDebug.exec') + executionData = files('build/jacoco/testDebugUnitTest.exec') doFirst { files('build/intermediates/classes/debug').getFiles().each { file -> if (file.name.contains('$$')) { @@ -65,9 +70,9 @@ task jacocoRootReport(type: JacocoReport, group: 'Coverage reports') { description = 'Generates an aggregate report from all subprojects' dependsOn(subprojects.jacocoTestReport) - additionalSourceDirs = files('example/src/main/java') + files('library/src/main/java') - sourceDirectories = files('example/src/main/java') + files('library/src/main/java') - classDirectories = files('example/build/intermediates/classes/debug') + files('library/build/intermediates/classes/debug') + additionalSourceDirs = files('library/src/main/java') + sourceDirectories = files('library/src/main/java') + classDirectories = files('library/build/intermediates/classes/debug') executionData = files(subprojects.jacocoTestReport.executionData) reports { @@ -75,13 +80,17 @@ task jacocoRootReport(type: JacocoReport, group: 'Coverage reports') { xml.enabled = true } + onlyIf = { + true + } + doFirst { executionData = files(executionData.findAll { it.exists() }) } } coveralls { - sourceDirs = files('example/src/main/java').flatten() + files('library/src/main/java').flatten() + sourceDirs = files('library/src/main/java').flatten() jacocoReportPath = "${buildDir}/reports/jacoco/jacocoRootReport/jacocoRootReport.xml" } @@ -91,4 +100,4 @@ tasks.coveralls { dependsOn jacocoRootReport onlyIf { System.env.'CI' } -} +} \ No newline at end of file diff --git a/example/build.gradle b/example/build.gradle index 129eb11e..a8b90f05 100644 --- a/example/build.gradle +++ b/example/build.gradle @@ -2,44 +2,24 @@ apply plugin: 'com.android.application' android { compileSdkVersion 23 - buildToolsVersion "23.0.2" + buildToolsVersion "23.0.3" defaultConfig { applicationId "com.example" minSdkVersion 9 targetSdkVersion 23 } - buildTypes { release { minifyEnabled false } } + lintOptions { + abortOnError false + } } dependencies { compile project (':library') - compile 'com.android.support:appcompat-v7:23.1.1' - testCompile 'org.robolectric:robolectric:3.0' - testCompile 'junit:junit:4.12' + compile 'com.android.support:appcompat-v7:23.3.0' } - -//robolectric { -// // Configure includes / excludes -// include '**/*Tests.class' -// exclude '**/espresso/**/*.class' -// -// // Configure max heap size of the test JVM -// maxHeapSize = '2048m' -// -// // Configure the test JVM arguments - Does not apply to Java 8 -// jvmArgs '-XX:MaxPermSize=512m', '-XX:-UseSplitVerifier' -// -// // configure whether failing tests should fail the build -// ignoreFailures true -// -// // use afterTest to listen to the test execution results -// afterTest { descriptor, result -> -// println "Executing test for ${descriptor.name} with result: ${result.resultType}" -// } -//} diff --git a/example/src/main/java/com/example/activities/SugarActivity.java b/example/src/main/java/com/example/activities/SugarActivity.java index 197314a0..81044546 100644 --- a/example/src/main/java/com/example/activities/SugarActivity.java +++ b/example/src/main/java/com/example/activities/SugarActivity.java @@ -1,7 +1,6 @@ package com.example.activities; import android.app.Activity; -import android.content.Intent; import android.os.Bundle; import com.example.R; diff --git a/example/src/test/java/com/example/sugartest/BigDecimalFieldTests.java b/example/src/test/java/com/example/sugartest/BigDecimalFieldTests.java deleted file mode 100644 index 9e4b36bb..00000000 --- a/example/src/test/java/com/example/sugartest/BigDecimalFieldTests.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.example.sugartest; - - -import com.example.models.BigDecimalFieldAnnotatedModel; -import com.example.models.BigDecimalFieldExtendedModel; -import com.orm.SugarRecord; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.annotation.Config; - -import java.math.BigDecimal; - -import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -@RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class BigDecimalFieldTests { - @Test - public void nullBigDecimalExtendedTest() { - save(new BigDecimalFieldExtendedModel()); - BigDecimalFieldExtendedModel model = - SugarRecord.findById(BigDecimalFieldExtendedModel.class, 1); - assertNull(model.getBigDecimal()); - } - - @Test - public void nullBigDecimalAnnotatedTest() { - save(new BigDecimalFieldAnnotatedModel()); - BigDecimalFieldAnnotatedModel model = - SugarRecord.findById(BigDecimalFieldAnnotatedModel.class, 1); - assertNull(model.getBigDecimal()); - } - - @Test - public void bigDecimalExtendedTest() { - BigDecimal decimal = new BigDecimal(1234.5678901234567890123456789); - save(new BigDecimalFieldExtendedModel(decimal)); - BigDecimalFieldExtendedModel model = SugarRecord.findById(BigDecimalFieldExtendedModel.class, 1); - assertEquals(decimal, model.getBigDecimal()); - } - - @Test - public void bigDecimalAnnotatedTest() { - BigDecimal decimal = new BigDecimal(1234.5678901234567890123456789); - save(new BigDecimalFieldAnnotatedModel(decimal)); - BigDecimalFieldAnnotatedModel model = - SugarRecord.findById(BigDecimalFieldAnnotatedModel.class, 1); - assertEquals(decimal, model.getBigDecimal()); - } -} diff --git a/example/src/test/java/com/example/sugartest/BooleanFieldTests.java b/example/src/test/java/com/example/sugartest/BooleanFieldTests.java deleted file mode 100644 index a117af6c..00000000 --- a/example/src/test/java/com/example/sugartest/BooleanFieldTests.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.example.sugartest; - - -import com.example.models.BooleanFieldAnnotatedModel; -import com.example.models.BooleanFieldExtendedModel; -import com.orm.SugarRecord; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.annotation.Config; - -import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -@RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class BooleanFieldTests { - @Test - public void nullBooleanExtendedTest() { - save(new BooleanFieldExtendedModel()); - BooleanFieldExtendedModel model = SugarRecord.findById(BooleanFieldExtendedModel.class, 1); - assertNull(model.getBoolean()); - } - - @Test - public void nullRawBooleanExtendedTest() { - save(new BooleanFieldExtendedModel()); - BooleanFieldExtendedModel model = SugarRecord.findById(BooleanFieldExtendedModel.class, 1); - assertEquals(false, model.getRawBoolean()); - } - - @Test - public void nullBooleanAnnotatedTest() { - save(new BooleanFieldAnnotatedModel()); - BooleanFieldAnnotatedModel model = SugarRecord.findById(BooleanFieldAnnotatedModel.class, 1); - assertNull(model.getBoolean()); - } - - @Test - public void nullRawBooleanAnnotatedTest() { - save(new BooleanFieldAnnotatedModel()); - BooleanFieldAnnotatedModel model = SugarRecord.findById(BooleanFieldAnnotatedModel.class, 1); - assertEquals(false, model.getRawBoolean()); - } - - @Test - public void objectBooleanExtendedTest() { - Boolean objectBoolean = new Boolean(true); - save(new BooleanFieldExtendedModel(objectBoolean)); - BooleanFieldExtendedModel model = SugarRecord.findById(BooleanFieldExtendedModel.class, 1); - assertEquals(objectBoolean, model.getBoolean()); - } - - @Test - public void rawBooleanExtendedTest() { - save(new BooleanFieldExtendedModel(true)); - BooleanFieldExtendedModel model = SugarRecord.findById(BooleanFieldExtendedModel.class, 1); - assertEquals(true, model.getRawBoolean()); - } - - @Test - public void objectBooleanAnnotatedTest() { - Boolean objectBoolean = new Boolean(true); - save(new BooleanFieldAnnotatedModel(objectBoolean)); - BooleanFieldAnnotatedModel model = SugarRecord.findById(BooleanFieldAnnotatedModel.class, 1); - assertEquals(objectBoolean, model.getBoolean()); - } - - @Test - public void rawBooleanAnnotatedTest() { - save(new BooleanFieldAnnotatedModel(true)); - BooleanFieldAnnotatedModel model = SugarRecord.findById(BooleanFieldAnnotatedModel.class, 1); - assertEquals(true, model.getRawBoolean()); - } -} diff --git a/example/src/test/java/com/example/sugartest/FirstAndLastTests.java b/example/src/test/java/com/example/sugartest/FirstAndLastTests.java deleted file mode 100644 index d095578f..00000000 --- a/example/src/test/java/com/example/sugartest/FirstAndLastTests.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.example.sugartest; - - -import com.example.models.FloatFieldAnnotatedModel; -import com.example.models.FloatFieldExtendedModel; -import com.orm.SugarRecord; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.annotation.Config; - -import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -@RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class FirstAndLastTests { - @Test - public void firstExtendedTest() { - Float firstObjectFloat = new Float(25F); - Float lastObjectFloat = new Float(50F); - save(new FloatFieldExtendedModel(firstObjectFloat)); - save(new FloatFieldExtendedModel(lastObjectFloat)); - FloatFieldExtendedModel model = SugarRecord.first(FloatFieldExtendedModel.class); - assertEquals(firstObjectFloat, model.getFloat()); - } - - @Test - public void firstDeletedRecordExtendedTest() { - Float firstObjectFloat = new Float(15F); - Float secondObjectFloat = new Float(25F); - Float thirdObjectFloat = new Float(35F); - Float fourthObjectFloat = new Float(45F); - save(new FloatFieldExtendedModel(firstObjectFloat)); - save(new FloatFieldExtendedModel(secondObjectFloat)); - save(new FloatFieldExtendedModel(thirdObjectFloat)); - save(new FloatFieldExtendedModel(fourthObjectFloat)); - FloatFieldExtendedModel firstRecord = SugarRecord.findById(FloatFieldExtendedModel.class, 1); - firstRecord.delete(); - FloatFieldExtendedModel model = SugarRecord.first(FloatFieldExtendedModel.class); - assertEquals(secondObjectFloat, model.getFloat()); - } - - @Test - public void lastExtendedTest() { - Float firstObjectFloat = new Float(25F); - Float lastObjectFloat = new Float(50F); - save(new FloatFieldExtendedModel(firstObjectFloat)); - save(new FloatFieldExtendedModel(lastObjectFloat)); - FloatFieldExtendedModel model = SugarRecord.last(FloatFieldExtendedModel.class); - assertEquals(lastObjectFloat, model.getFloat()); - } - - @Test - public void lastDeletedRecordExtendedTest() { - Float firstObjectFloat = new Float(15F); - Float secondObjectFloat = new Float(25F); - Float thirdObjectFloat = new Float(35F); - Float fourthObjectFloat = new Float(45F); - save(new FloatFieldExtendedModel(firstObjectFloat)); - save(new FloatFieldExtendedModel(secondObjectFloat)); - save(new FloatFieldExtendedModel(thirdObjectFloat)); - save(new FloatFieldExtendedModel(fourthObjectFloat)); - FloatFieldExtendedModel lastRecord = SugarRecord.findById(FloatFieldExtendedModel.class, 4); - lastRecord.delete(); - FloatFieldExtendedModel model = SugarRecord.last(FloatFieldExtendedModel.class); - assertEquals(thirdObjectFloat, model.getFloat()); - } - - @Test - public void nullFirstExtendedTest() { - assertNull(SugarRecord.first(FloatFieldExtendedModel.class)); - } - - @Test - public void nullLastExtendedTest() { - assertNull(SugarRecord.last(FloatFieldExtendedModel.class)); - } - - @Test - public void oneItemExtendedTest() { - save(new FloatFieldExtendedModel(new Float(25F))); - FloatFieldExtendedModel firstModel = SugarRecord.first(FloatFieldExtendedModel.class); - FloatFieldExtendedModel lastModel = SugarRecord.last(FloatFieldExtendedModel.class); - assertEquals(firstModel.getFloat(), lastModel.getFloat()); - } - - @Test - public void firstAnnotatedTest() { - Float firstObjectFloat = new Float(25F); - Float lastObjectFloat = new Float(50F); - save(new FloatFieldAnnotatedModel(firstObjectFloat)); - save(new FloatFieldAnnotatedModel(lastObjectFloat)); - FloatFieldAnnotatedModel model = SugarRecord.first(FloatFieldAnnotatedModel.class); - assertEquals(firstObjectFloat, model.getFloat()); - } - - @Test - public void firstDeletedRecordAnnotatedTest() { - Float firstObjectFloat = new Float(15F); - Float secondObjectFloat = new Float(25F); - Float thirdObjectFloat = new Float(35F); - Float fourthObjectFloat = new Float(45F); - save(new FloatFieldAnnotatedModel(firstObjectFloat)); - save(new FloatFieldAnnotatedModel(secondObjectFloat)); - save(new FloatFieldAnnotatedModel(thirdObjectFloat)); - save(new FloatFieldAnnotatedModel(fourthObjectFloat)); - FloatFieldAnnotatedModel firstRecord = SugarRecord.findById(FloatFieldAnnotatedModel.class, 1); - SugarRecord.delete(firstRecord); - FloatFieldAnnotatedModel model = SugarRecord.first(FloatFieldAnnotatedModel.class); - assertEquals(secondObjectFloat, model.getFloat()); - } - - @Test - public void lastAnnotatedTest() { - Float firstObjectFloat = new Float(25F); - Float lastObjectFloat = new Float(50F); - save(new FloatFieldAnnotatedModel(firstObjectFloat)); - save(new FloatFieldAnnotatedModel(lastObjectFloat)); - FloatFieldAnnotatedModel model = SugarRecord.last(FloatFieldAnnotatedModel.class); - assertEquals(lastObjectFloat, model.getFloat()); - } - - @Test - public void lastDeletedRecordAnnotatedTest() { - Float firstObjectFloat = new Float(15F); - Float secondObjectFloat = new Float(25F); - Float thirdObjectFloat = new Float(35F); - Float fourthObjectFloat = new Float(45F); - save(new FloatFieldAnnotatedModel(firstObjectFloat)); - save(new FloatFieldAnnotatedModel(secondObjectFloat)); - save(new FloatFieldAnnotatedModel(thirdObjectFloat)); - save(new FloatFieldAnnotatedModel(fourthObjectFloat)); - FloatFieldAnnotatedModel lastRecord = SugarRecord.findById(FloatFieldAnnotatedModel.class, 4); - SugarRecord.delete(lastRecord); - FloatFieldAnnotatedModel model = SugarRecord.last(FloatFieldAnnotatedModel.class); - assertEquals(thirdObjectFloat, model.getFloat()); - } - - @Test - public void nullFirstAnnotatedTest() { - assertNull(SugarRecord.first(FloatFieldAnnotatedModel.class)); - } - - @Test - public void nullLastAnnotatedTest() { - assertNull(SugarRecord.last(FloatFieldAnnotatedModel.class)); - } - - @Test - public void oneItemAnnotatedTest() { - save(new FloatFieldAnnotatedModel(new Float(25F))); - FloatFieldAnnotatedModel firstModel = SugarRecord.first(FloatFieldAnnotatedModel.class); - FloatFieldAnnotatedModel lastModel = SugarRecord.last(FloatFieldAnnotatedModel.class); - assertEquals(firstModel.getFloat(), lastModel.getFloat()); - } -} diff --git a/example/src/test/java/com/example/sugartest/FloatFieldTests.java b/example/src/test/java/com/example/sugartest/FloatFieldTests.java deleted file mode 100644 index 16f52bbc..00000000 --- a/example/src/test/java/com/example/sugartest/FloatFieldTests.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.example.sugartest; - - -import com.example.models.FloatFieldAnnotatedModel; -import com.example.models.FloatFieldExtendedModel; -import com.orm.SugarRecord; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.annotation.Config; - -import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -@RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class FloatFieldTests { - @Test - public void nullFloatExtendedTest() { - save(new FloatFieldExtendedModel()); - FloatFieldExtendedModel model = SugarRecord.findById(FloatFieldExtendedModel.class, 1); - assertNull(model.getFloat()); - } - - @Test - public void nullRawFloatExtendedTest() { - save(new FloatFieldExtendedModel()); - FloatFieldExtendedModel model = SugarRecord.findById(FloatFieldExtendedModel.class, 1); - assertEquals(0F, model.getRawFloat(), 0.0000000001F); - } - - @Test - public void nullFloatAnnotatedTest() { - save(new FloatFieldAnnotatedModel()); - FloatFieldAnnotatedModel model = SugarRecord.findById(FloatFieldAnnotatedModel.class, 1); - assertNull(model.getFloat()); - } - - @Test - public void nullRawFloatAnnotatedTest() { - save(new FloatFieldAnnotatedModel()); - FloatFieldAnnotatedModel model = SugarRecord.findById(FloatFieldAnnotatedModel.class, 1); - assertEquals(0F, model.getRawFloat(), 0.0000000001F); - } - - @Test - public void objectFloatExtendedTest() { - Float objectFloat = new Float(25F); - save(new FloatFieldExtendedModel(objectFloat)); - FloatFieldExtendedModel model = SugarRecord.findById(FloatFieldExtendedModel.class, 1); - assertEquals(objectFloat, model.getFloat()); - } - - @Test - public void rawFloatExtendedTest() { - save(new FloatFieldExtendedModel(25F)); - FloatFieldExtendedModel model = SugarRecord.findById(FloatFieldExtendedModel.class, 1); - assertEquals(25F, model.getRawFloat(), 0.0000000001F); - } - - @Test - public void objectFloatAnnotatedTest() { - Float objectFloat = new Float(25F); - save(new FloatFieldAnnotatedModel(objectFloat)); - FloatFieldAnnotatedModel model = SugarRecord.findById(FloatFieldAnnotatedModel.class, 1); - assertEquals(objectFloat, model.getFloat()); - } - - @Test - public void rawFloatAnnotatedTest() { - save(new FloatFieldAnnotatedModel(25F)); - FloatFieldAnnotatedModel model = SugarRecord.findById(FloatFieldAnnotatedModel.class, 1); - assertEquals(25F, model.getRawFloat(), 0.0000000001F); - } -} diff --git a/example/src/test/java/com/example/sugartest/IntegerFieldTests.java b/example/src/test/java/com/example/sugartest/IntegerFieldTests.java deleted file mode 100644 index 25dbd0bd..00000000 --- a/example/src/test/java/com/example/sugartest/IntegerFieldTests.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.example.sugartest; - - -import com.example.models.IntegerFieldAnnotatedModel; -import com.example.models.IntegerFieldExtendedModel; -import com.orm.SugarRecord; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.annotation.Config; - -import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -@RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class IntegerFieldTests { - @Test - public void nullIntegerExtendedTest() { - save(new IntegerFieldExtendedModel()); - IntegerFieldExtendedModel model = SugarRecord.findById(IntegerFieldExtendedModel.class, 1); - assertNull(model.getInteger()); - } - - @Test - public void nullIntExtendedTest() { - save(new IntegerFieldExtendedModel()); - IntegerFieldExtendedModel model = SugarRecord.findById(IntegerFieldExtendedModel.class, 1); - assertEquals(0, model.getInt()); - } - - @Test - public void nullIntegerAnnotatedTest() { - save(new IntegerFieldAnnotatedModel()); - IntegerFieldAnnotatedModel model = SugarRecord.findById(IntegerFieldAnnotatedModel.class, 1); - assertNull(model.getInteger()); - } - - @Test - public void nullIntAnnotatedTest() { - save(new IntegerFieldAnnotatedModel()); - IntegerFieldAnnotatedModel model = SugarRecord.findById(IntegerFieldAnnotatedModel.class, 1); - assertEquals(0, model.getInt()); - } - - @Test - public void integerExtendedTest() { - Integer integer = new Integer(25); - save(new IntegerFieldExtendedModel(integer)); - IntegerFieldExtendedModel model = SugarRecord.findById(IntegerFieldExtendedModel.class, 1); - assertEquals(integer, model.getInteger()); - } - - @Test - public void intExtendedTest() { - save(new IntegerFieldExtendedModel(25)); - IntegerFieldExtendedModel model = SugarRecord.findById(IntegerFieldExtendedModel.class, 1); - assertEquals(25, model.getInt()); - } - - @Test - public void integerAnnotatedTest() { - Integer integer = new Integer(25); - save(new IntegerFieldAnnotatedModel(integer)); - IntegerFieldAnnotatedModel model = SugarRecord.findById(IntegerFieldAnnotatedModel.class, 1); - assertEquals(integer, model.getInteger()); - } - - @Test - public void intAnnotatedTest() { - save(new IntegerFieldAnnotatedModel(25)); - IntegerFieldAnnotatedModel model = SugarRecord.findById(IntegerFieldAnnotatedModel.class, 1); - assertEquals(25, model.getInt()); - } -} diff --git a/example/src/test/java/com/example/sugartest/ListAllOrderByTests.java b/example/src/test/java/com/example/sugartest/ListAllOrderByTests.java deleted file mode 100644 index 014c989d..00000000 --- a/example/src/test/java/com/example/sugartest/ListAllOrderByTests.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.example.sugartest; - - -import com.example.models.IntegerFieldExtendedModel; -import com.orm.SugarRecord; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.annotation.Config; - -import java.util.List; - -import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - - -@RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class ListAllOrderByTests { - @Test - public void listAllOrderByEmptyTest() { - assertEquals(0L, SugarRecord.listAll(IntegerFieldExtendedModel.class, "id").size()); - } - - @Test - public void listAllOrderByIdTest() { - for(int i = 1; i <= 100; i++) { - save(new IntegerFieldExtendedModel(i)); - } - List models = - SugarRecord.listAll(IntegerFieldExtendedModel.class, "id"); - assertEquals(100L, models.size()); - Long id = models.get(0).getId(); - for(int i = 1; i < 100; i++) { - assertTrue(id models = - SugarRecord.listAll(IntegerFieldExtendedModel.class, "raw_integer"); - assertEquals(100L, models.size()); - int raw = models.get(0).getInt(); - for(int i = 1; i < 100; i++) { - assertTrue(raw < models.get(i).getInt()); - } - } -} diff --git a/example/src/test/java/com/example/sugartest/LongFieldTests.java b/example/src/test/java/com/example/sugartest/LongFieldTests.java deleted file mode 100644 index b99e7537..00000000 --- a/example/src/test/java/com/example/sugartest/LongFieldTests.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.example.sugartest; - - -import com.example.models.LongFieldAnnotatedModel; -import com.example.models.LongFieldExtendedModel; -import com.orm.SugarRecord; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.annotation.Config; - -import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -@RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class LongFieldTests { - @Test - public void nullLongExtendedTest() { - save(new LongFieldExtendedModel()); - LongFieldExtendedModel model = SugarRecord.findById(LongFieldExtendedModel.class, 1); - assertNull(model.getLong()); - } - - @Test - public void nullRawLongExtendedTest() { - save(new LongFieldExtendedModel()); - LongFieldExtendedModel model = SugarRecord.findById(LongFieldExtendedModel.class, 1); - assertEquals(0L, model.getRawLong()); - } - - @Test - public void nullLongAnnotatedTest() { - save(new LongFieldAnnotatedModel()); - LongFieldAnnotatedModel model = SugarRecord.findById(LongFieldAnnotatedModel.class, 1); - assertNull(model.getLong()); - } - - @Test - public void nullRawLongAnnotatedTest() { - save(new LongFieldAnnotatedModel()); - LongFieldAnnotatedModel model = SugarRecord.findById(LongFieldAnnotatedModel.class, 1); - assertEquals(0L, model.getRawLong()); - } - - @Test - public void objectLongExtendedTest() { - Long objectLong = new Long(25L); - save(new LongFieldExtendedModel(objectLong)); - LongFieldExtendedModel model = SugarRecord.findById(LongFieldExtendedModel.class, 1); - assertEquals(objectLong, model.getLong()); - } - - @Test - public void rawLongExtendedTest() { - save(new LongFieldExtendedModel(25L)); - LongFieldExtendedModel model = SugarRecord.findById(LongFieldExtendedModel.class, 1); - assertEquals(25L, model.getRawLong()); - } - - @Test - public void objectLongAnnotatedTest() { - Long objectLong = new Long(25L); - save(new LongFieldAnnotatedModel(objectLong)); - LongFieldAnnotatedModel model = SugarRecord.findById(LongFieldAnnotatedModel.class, 1); - assertEquals(objectLong, model.getLong()); - } - - @Test - public void rawLongAnnotatedTest() { - save(new LongFieldAnnotatedModel(25L)); - LongFieldAnnotatedModel model = SugarRecord.findById(LongFieldAnnotatedModel.class, 1); - assertEquals(25L, model.getRawLong()); - } -} diff --git a/example/src/test/java/com/example/sugartest/MultipleSaveTests.java b/example/src/test/java/com/example/sugartest/MultipleSaveTests.java deleted file mode 100644 index 58c669c5..00000000 --- a/example/src/test/java/com/example/sugartest/MultipleSaveTests.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.example.sugartest; - - -import com.example.models.StringFieldAnnotatedModel; -import com.example.models.StringFieldAnnotatedNoIdModel; -import com.example.models.StringFieldExtendedModel; -import com.orm.SugarRecord; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.annotation.Config; - -import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -@RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class MultipleSaveTests { - @Test - public void stringMultipleSaveOriginalExtendedTest() { - String string = "Test String"; - StringFieldExtendedModel model = new StringFieldExtendedModel(string); - long id = save(model); - StringFieldExtendedModel query = SugarRecord.findById(StringFieldExtendedModel.class, id); - assertEquals(string, query.getString()); - model.setString("Another test"); - assertEquals(id, save(model)); - assertNull(SugarRecord.findById(StringFieldExtendedModel.class, 2)); - } - - @Test - public void stringMultipleSaveQueriedExtendedTest() { - String string = "Test String"; - StringFieldExtendedModel model = new StringFieldExtendedModel(string); - long id = save(model); - StringFieldExtendedModel query = SugarRecord.findById(StringFieldExtendedModel.class, id); - assertEquals(string, query.getString()); - query.setString("Another test"); - assertEquals(id, save(query)); - assertNull(SugarRecord.findById(StringFieldExtendedModel.class, 2)); - } - - @Test - public void stringMultipleSaveOriginalAnnotatedTest() { - String string = "Test String"; - StringFieldAnnotatedModel model = new StringFieldAnnotatedModel(string); - long id = save(model); - StringFieldAnnotatedModel query = SugarRecord.findById(StringFieldAnnotatedModel.class, id); - assertEquals(string, query.getString()); - model.setString("Another test"); - assertEquals(id, save(model)); - assertNull(SugarRecord.findById(StringFieldAnnotatedModel.class, 2)); - } - - @Test - public void stringMultipleSaveQueriedAnnotatedTest() { - String string = "Test String"; - StringFieldAnnotatedModel model = new StringFieldAnnotatedModel(string); - long id = save(model); - StringFieldAnnotatedModel query = SugarRecord.findById(StringFieldAnnotatedModel.class, id); - assertEquals(string, query.getString()); - query.setString("Another test"); - assertEquals(id, save(query)); - assertNull(SugarRecord.findById(StringFieldAnnotatedModel.class, 2)); - } - - @Test - public void stringMultipleSaveOriginalAnnotatedNoIdTest() { - String string = "Test String"; - StringFieldAnnotatedNoIdModel model = new StringFieldAnnotatedNoIdModel(string); - long id = save(model); - StringFieldAnnotatedNoIdModel query = - SugarRecord.findById(StringFieldAnnotatedNoIdModel.class, id); - assertEquals(string, query.getString()); - model.setString("Another test"); - assertEquals(id, save(model)); - assertNull(SugarRecord.findById(StringFieldAnnotatedNoIdModel.class, 2)); - } - - @Test - public void stringMultipleSaveQueriedAnnotatedNoIdTest() { - String string = "Test String"; - StringFieldAnnotatedNoIdModel model = new StringFieldAnnotatedNoIdModel(string); - long id = save(model); - StringFieldAnnotatedNoIdModel query = - SugarRecord.findById(StringFieldAnnotatedNoIdModel.class, id); - assertEquals(string, query.getString()); - query.setString("Another test"); - assertEquals(id, save(query)); - assertNull(SugarRecord.findById(StringFieldAnnotatedNoIdModel.class, 2)); - } -} diff --git a/example/src/test/java/com/example/sugartest/NoSugarModelTests.java b/example/src/test/java/com/example/sugartest/NoSugarModelTests.java deleted file mode 100644 index dbab8103..00000000 --- a/example/src/test/java/com/example/sugartest/NoSugarModelTests.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.example.sugartest; - -import com.example.models.NoSugarModel; -import com.orm.SugarRecord; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.annotation.Config; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - - -@RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class NoSugarModelTests { - @Test - public void deleteTest() throws Exception { - NoSugarModel model = new NoSugarModel(); - assertFalse(SugarRecord.delete(model)); - } - - @Test - public void saveInTransactionTest() throws Exception { - SugarRecord.saveInTx(new NoSugarModel(), new NoSugarModel()); - assertEquals(-1L, SugarRecord.count(NoSugarModel.class)); - } -} diff --git a/example/src/test/java/com/example/sugartest/RelationshipMixedATests.java b/example/src/test/java/com/example/sugartest/RelationshipMixedATests.java deleted file mode 100644 index 7ecb6751..00000000 --- a/example/src/test/java/com/example/sugartest/RelationshipMixedATests.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.example.sugartest; - -import com.example.models.RelationshipMixedAModel; -import com.example.models.SimpleAnnotatedModel; -import com.orm.SugarRecord; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.annotation.Config; - -import java.util.List; - -import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; - - -@RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class RelationshipMixedATests { - @Test - public void emptyDatabaseTest() throws Exception { - assertEquals(0L, SugarRecord.count(RelationshipMixedAModel.class)); - assertEquals(0L, SugarRecord.count(SimpleAnnotatedModel.class)); - } - - @Test - public void oneSaveTest() throws Exception { - SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); - save(simple); - save(new RelationshipMixedAModel(simple)); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipMixedAModel.class)); - } - - @Test - public void twoSameSaveTest() throws Exception { - SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); - save(simple); - save(new RelationshipMixedAModel(simple)); - save(new RelationshipMixedAModel(simple)); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(2L, SugarRecord.count(RelationshipMixedAModel.class)); - } - - @Test - public void twoDifferentSaveTest() throws Exception { - SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); - save(simple); - SimpleAnnotatedModel another_simple = new SimpleAnnotatedModel(); - save(another_simple); - save(new RelationshipMixedAModel(simple)); - save(new RelationshipMixedAModel(another_simple)); - assertEquals(2L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(2L, SugarRecord.count(RelationshipMixedAModel.class)); - } - - @Test - public void manySameSaveTest() throws Exception { - SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); - save(simple); - for (int i = 1; i <= 100; i++) { - save(new RelationshipMixedAModel(simple)); - } - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(100L, SugarRecord.count(RelationshipMixedAModel.class)); - } - - @Test - public void manyDifferentSaveTest() throws Exception { - for (int i = 1; i <= 100; i++) { - SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); - save(simple); - save(new RelationshipMixedAModel(simple)); - } - assertEquals(100L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(100L, SugarRecord.count(RelationshipMixedAModel.class)); - } - - @Test - public void listAllSameTest() throws Exception { - SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); - save(simple); - for (int i = 1; i <= 100; i++) { - save(new RelationshipMixedAModel(simple)); - } - List models = - SugarRecord.listAll(RelationshipMixedAModel.class); - assertEquals(100, models.size()); - for (RelationshipMixedAModel model : models) { - assertEquals(simple.getId(), model.getSimple().getId()); - } - } - - @Test - public void listAllDifferentTest() throws Exception { - for (int i = 1; i <= 100; i++) { - SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); - save(simple); - save(new RelationshipMixedAModel(simple)); - } - List models = - SugarRecord.listAll(RelationshipMixedAModel.class); - assertEquals(100, models.size()); - for (RelationshipMixedAModel model : models) { - assertEquals(model.getId(), model.getSimple().getId()); - } - } -} diff --git a/example/src/test/java/com/example/sugartest/RobolectricGradleTestRunner.java b/example/src/test/java/com/example/sugartest/RobolectricGradleTestRunner.java deleted file mode 100644 index 4f7bc39d..00000000 --- a/example/src/test/java/com/example/sugartest/RobolectricGradleTestRunner.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.example.sugartest; - -import com.example.ClientApp; - -import org.junit.runners.model.InitializationError; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.annotation.Config; -import org.robolectric.manifest.AndroidManifest; -import org.robolectric.res.Fs; - -public class RobolectricGradleTestRunner extends RobolectricTestRunner { - public RobolectricGradleTestRunner(Class testClass) throws InitializationError { - super(testClass); - } - - @Override protected AndroidManifest getAppManifest(Config config) { - String myAppPath = ClientApp.class.getProtectionDomain().getCodeSource().getLocation().getPath(); - String manifestPath = myAppPath + "../../../../src/main/AndroidManifest.xml"; - String resPath = myAppPath + "../../../../src/main/res"; - String assetPath = myAppPath + "../../../../src/main/assets"; - String packageName = "com.example"; - return createAppManifest(Fs.fileFromPath(manifestPath), Fs.fileFromPath(resPath), Fs.fileFromPath(assetPath), packageName); - } -} \ No newline at end of file diff --git a/example/src/test/java/com/example/sugartest/ShortFieldTests.java b/example/src/test/java/com/example/sugartest/ShortFieldTests.java deleted file mode 100644 index 3c428752..00000000 --- a/example/src/test/java/com/example/sugartest/ShortFieldTests.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.example.sugartest; - - -import com.example.models.ShortFieldAnnotatedModel; -import com.example.models.ShortFieldExtendedModel; -import com.orm.SugarRecord; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.annotation.Config; - -import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -@RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class ShortFieldTests { - @Test - public void nullShortExtendedTest() { - save(new ShortFieldExtendedModel()); - ShortFieldExtendedModel model = SugarRecord.findById(ShortFieldExtendedModel.class, 1); - assertNull(model.getShort()); - } - - @Test - public void nullRawShortExtendedTest() { - save(new ShortFieldExtendedModel()); - ShortFieldExtendedModel model = SugarRecord.findById(ShortFieldExtendedModel.class, 1); - assertEquals((short) 0, model.getRawShort()); - } - - @Test - public void nullShortAnnotatedTest() { - save(new ShortFieldAnnotatedModel()); - ShortFieldAnnotatedModel model = SugarRecord.findById(ShortFieldAnnotatedModel.class, 1); - assertNull(model.getShort()); - } - - @Test - public void nullRawShortAnnotatedTest() { - save(new ShortFieldAnnotatedModel()); - ShortFieldAnnotatedModel model = SugarRecord.findById(ShortFieldAnnotatedModel.class, 1); - assertEquals((short) 0, model.getRawShort()); - } - - @Test - public void objectShortExtendedTest() { - Short objectShort = new Short((short) 25); - save(new ShortFieldExtendedModel(objectShort)); - ShortFieldExtendedModel model = SugarRecord.findById(ShortFieldExtendedModel.class, 1); - assertEquals(objectShort, model.getShort()); - } - - @Test - public void rawShortExtendedTest() { - save(new ShortFieldExtendedModel((short) 25)); - ShortFieldExtendedModel model = SugarRecord.findById(ShortFieldExtendedModel.class, 1); - assertEquals((short) 25, model.getRawShort()); - } - - @Test - public void objectShortAnnotatedTest() { - Short objectShort = new Short((short) 25); - save(new ShortFieldAnnotatedModel(objectShort)); - ShortFieldAnnotatedModel model = SugarRecord.findById(ShortFieldAnnotatedModel.class, 1); - assertEquals(objectShort, model.getShort()); - } - - @Test - public void rawShortAnnotatedTest() { - save(new ShortFieldAnnotatedModel((short) 25)); - ShortFieldAnnotatedModel model = SugarRecord.findById(ShortFieldAnnotatedModel.class, 1); - assertEquals((short) 25, model.getRawShort()); - } -} diff --git a/gradle.properties b/gradle.properties index b1d9b965..35b4c26f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -16,6 +16,7 @@ # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true +org.gradle.daemon=true VERSION_NAME=2 VERSION_CODE=2 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 0c71e760..b0bb3ffb 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Wed Apr 10 15:27:10 PDT 2013 +#Sat Apr 09 17:51:14 ART 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip diff --git a/library/build.gradle b/library/build.gradle index d9a42c18..907162ee 100644 --- a/library/build.gradle +++ b/library/build.gradle @@ -3,22 +3,28 @@ apply from: '../maven_push.gradle' android { compileSdkVersion 23 - buildToolsVersion "23.0.2" + buildToolsVersion "23.0.3" defaultConfig { minSdkVersion 9 targetSdkVersion 23 } - buildTypes { release { minifyEnabled false } } + testOptions { + unitTests.returnDefaultValues = true + } + lintOptions { + abortOnError false + } } dependencies { testCompile 'junit:junit:4.12' + testCompile 'org.robolectric:robolectric:3.0' } task libraryJar(type: Jar) { diff --git a/library/src/main/java/com/orm/SchemaGenerator.java b/library/src/main/java/com/orm/SchemaGenerator.java index 91f80e1b..c25407fc 100644 --- a/library/src/main/java/com/orm/SchemaGenerator.java +++ b/library/src/main/java/com/orm/SchemaGenerator.java @@ -1,15 +1,19 @@ package com.orm; -import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.util.Log; -import com.orm.dsl.Column; -import com.orm.dsl.NotNull; -import com.orm.dsl.Unique; -import com.orm.util.NamingHelper; +import com.orm.annotation.Column; +import com.orm.annotation.MultiUnique; +import com.orm.annotation.NotNull; +import com.orm.annotation.Unique; +import com.orm.dsl.BuildConfig; +import com.orm.helper.ManifestHelper; +import com.orm.util.KeyWordUtil; +import com.orm.util.MigrationFileParser; +import com.orm.helper.NamingHelper; import com.orm.util.NumberComparator; import com.orm.util.QueryBuilder; import com.orm.util.ReflectionUtil; @@ -19,48 +23,75 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Field; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import static com.orm.util.ReflectionUtil.getDomainClasses; +import static com.orm.util.ContextUtil.getAssets; public class SchemaGenerator { - - private Context context; - public static final String NULL = " NULL"; public static final String NOT_NULL = " NOT NULL"; public static final String UNIQUE = " UNIQUE"; public static final String SUGAR = "Sugar"; - public SchemaGenerator(Context context) { - this.context = context; + //Prevent instantiation + private SchemaGenerator() { } + + public static SchemaGenerator getInstance() { + return new SchemaGenerator(); } public void createDatabase(SQLiteDatabase sqLiteDatabase) { - List domainClasses = getDomainClasses(context); + List domainClasses = getDomainClasses(); for (Class domain : domainClasses) { createTable(domain, sqLiteDatabase); + afterTableCreated(domain,sqLiteDatabase); } + + } + + public void afterTableCreated(Class table, SQLiteDatabase sqLiteDatabase) { + String fileName = table.getSimpleName() + ".sql"; + executeScript(sqLiteDatabase,"sugar_after_create/" ,fileName); + } public void doUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { - List domainClasses = getDomainClasses(context); + List domainClasses = getDomainClasses(); String sql = "select count(*) from sqlite_master where type='table' and name='%s';"; + for (Class domain : domainClasses) { - Cursor cursor = sqLiteDatabase.rawQuery(String.format(sql, NamingHelper.toSQLName(domain)), null); - if (cursor.moveToFirst() && cursor.getInt(0) == 0) { - createTable(domain, sqLiteDatabase); + String tableName = NamingHelper.toTableName(domain); + Cursor c = sqLiteDatabase.rawQuery(String.format(sql, tableName), null); + if (c.moveToFirst() && c.getInt(0) == 0) { + createTable(domain, sqLiteDatabase); + } else { + addColumns(domain, sqLiteDatabase); } } executeSugarUpgrade(sqLiteDatabase, oldVersion, newVersion); } + protected ArrayList getColumnNames(SQLiteDatabase sqLiteDatabase, String tableName) { + Cursor resultsQuery = sqLiteDatabase.query(tableName, null, null, null, null, null, null); + //Check if columns match vs the one on the domain class + ArrayList columnNames = new ArrayList<>(); + for (int i = 0; i < resultsQuery.getColumnCount(); i++) { + String columnName = resultsQuery.getColumnName(i); + columnNames.add(columnName); + } + resultsQuery.close(); + return columnNames; + } + + public void deleteTables(SQLiteDatabase sqLiteDatabase) { - List tables = getDomainClasses(context); + List tables = getDomainClasses(); for (Class table : tables) { - sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + NamingHelper.toSQLName(table)); + sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + NamingHelper.toTableName(table)); } } @@ -68,55 +99,125 @@ private boolean executeSugarUpgrade(SQLiteDatabase db, int oldVersion, int newVe boolean isSuccess = false; try { - List files = Arrays.asList(this.context.getAssets().list("sugar_upgrades")); + List files = Arrays.asList(getAssets().list("sugar_upgrades")); Collections.sort(files, new NumberComparator()); for (String file : files) { - Log.i(SUGAR, "filename : " + file); + if(ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, "filename : " + file); + } try { int version = Integer.valueOf(file.replace(".sql", "")); if ((version > oldVersion) && (version <= newVersion)) { - executeScript(db, file); + executeScript(db,"sugar_upgrades/" ,file); isSuccess = true; } } catch (NumberFormatException e) { - Log.i(SUGAR, "not a sugar script. ignored." + file); + if(ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, "not a sugar script. ignored." + file); + } } } } catch (IOException e) { - Log.e(SUGAR, e.getMessage()); + if(ManifestHelper.isDebugEnabled()) { + Log.e(SUGAR, e.getMessage()); + } } return isSuccess; } - private void executeScript(SQLiteDatabase db, String file) { + private void executeScript(SQLiteDatabase db,String path ,String file) { try { - InputStream is = this.context.getAssets().open("sugar_upgrades/" + file); + InputStream is = getAssets().open(path + file); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); + StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { - Log.i("Sugar script", line); - db.execSQL(line); + sb.append(line); + } + MigrationFileParser migrationFileParser = new MigrationFileParser(sb.toString()); + for(String statement: migrationFileParser.getStatements()){ + if(ManifestHelper.isDebugEnabled()) { + Log.i("Sugar script", statement); + } + if (!statement.isEmpty()) { + db.execSQL(statement); + } } + } catch (IOException e) { - Log.e(SUGAR, e.getMessage()); + if(ManifestHelper.isDebugEnabled()) { + Log.e(SUGAR, e.getMessage()); + } } - Log.i(SUGAR, "Script executed"); + if(ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, "Script executed"); + } } - private void createTable(Class table, SQLiteDatabase sqLiteDatabase) { - Log.i(SUGAR, "Create table if not exists"); + private void addColumns(Class table, SQLiteDatabase sqLiteDatabase) { List fields = ReflectionUtil.getTableFields(table); - String tableName = NamingHelper.toSQLName(table); + String tableName = NamingHelper.toTableName(table); + ArrayList presentColumns = getColumnNames(sqLiteDatabase, tableName); + ArrayList alterCommands = new ArrayList<>(); + + for (Field column : fields) { + String columnName = NamingHelper.toColumnName(column); + String columnType = QueryBuilder.getColumnType(column.getType()); + + if (column.isAnnotationPresent(Column.class)) { + Column columnAnnotation = column.getAnnotation(Column.class); + columnName = columnAnnotation.name(); + } + + if (!presentColumns.contains(columnName)) { + StringBuilder sb = new StringBuilder("ALTER TABLE "); + sb.append(tableName).append(" ADD COLUMN ").append(columnName).append(" ").append(columnType); + if (column.isAnnotationPresent(NotNull.class)) { + if (columnType.endsWith(" NULL")) { + sb.delete(sb.length() - 5, sb.length()); + } + sb.append(" NOT NULL"); + } + + // Unique is not working on ALTER TABLE +// if (column.isAnnotationPresent(Unique.class)) { +// sb.append(" UNIQUE"); +// } + alterCommands.add(sb.toString()); + } + } + + for (String command : alterCommands) { + if(ManifestHelper.isDebugEnabled()) { + Log.i("Sugar", command); + } + sqLiteDatabase.execSQL(command); + } + } + + protected String createTableSQL(Class table) { + if(ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, "Create table if not exists"); + } + List fields = ReflectionUtil.getTableFields(table); + String tableName = NamingHelper.toTableName(table); + + if(KeyWordUtil.isKeyword(tableName)) { + if(ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, "ERROR, SQLITE RESERVED WORD USED IN " + tableName); + } + } + StringBuilder sb = new StringBuilder("CREATE TABLE IF NOT EXISTS "); sb.append(tableName).append(" ( ID INTEGER PRIMARY KEY AUTOINCREMENT "); for (Field column : fields) { - String columnName = NamingHelper.toSQLName(column); + String columnName = NamingHelper.toColumnName(column); String columnType = QueryBuilder.getColumnType(column.getType()); if (columnType != null) { @@ -158,12 +259,38 @@ private void createTable(Class table, SQLiteDatabase sqLiteDatabase) { } } + if (table.isAnnotationPresent(MultiUnique.class)) { + String constraint = table.getAnnotation(MultiUnique.class).value(); + + sb.append(", UNIQUE("); + + String[] constraintFields = constraint.split(","); + for(int i = 0; i < constraintFields.length; i++) { + String columnName = NamingHelper.toSQLNameDefault(constraintFields[i]); + sb.append(columnName); + + if(i < (constraintFields.length -1)) { + sb.append(","); + } + } + + sb.append(") ON CONFLICT REPLACE"); + } + sb.append(" ) "); - Log.i(SUGAR, "Creating table " + tableName); + if(ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, "Creating table " + tableName); + } + + return sb.toString(); + } + + protected void createTable(Class table, SQLiteDatabase sqLiteDatabase) { + String createSQL = createTableSQL(table); - if (!sb.toString().isEmpty()) { + if (!createSQL.isEmpty()) { try { - sqLiteDatabase.execSQL(sb.toString()); + sqLiteDatabase.execSQL(createSQL); } catch (SQLException e) { e.printStackTrace(); } diff --git a/library/src/main/java/com/orm/SugarApp.java b/library/src/main/java/com/orm/SugarApp.java index 5140e1ee..cab35ca7 100644 --- a/library/src/main/java/com/orm/SugarApp.java +++ b/library/src/main/java/com/orm/SugarApp.java @@ -1,7 +1,5 @@ package com.orm; -import com.orm.SugarContext; - import android.app.Application; public class SugarApp extends Application { diff --git a/library/src/main/java/com/orm/SugarContext.java b/library/src/main/java/com/orm/SugarContext.java index 6190b1aa..61609986 100644 --- a/library/src/main/java/com/orm/SugarContext.java +++ b/library/src/main/java/com/orm/SugarContext.java @@ -2,20 +2,21 @@ import android.content.Context; +import com.orm.util.ContextUtil; + import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; public class SugarContext { + private static SugarDbConfiguration dbConfiguration = null; private static SugarContext instance = null; private SugarDb sugarDb; - private Context context; private Map entitiesMap; - private SugarContext(Context context) { - this.context = context; - this.sugarDb = new SugarDb(context); + private SugarContext() { + this.sugarDb = SugarDb.getInstance(); this.entitiesMap = Collections.synchronizedMap(new WeakHashMap()); } @@ -27,14 +28,23 @@ public static SugarContext getSugarContext() { } public static void init(Context context) { - instance = new SugarContext(context); + ContextUtil.init(context); + instance = new SugarContext(); + dbConfiguration = null; + } + + public static void init(Context context, SugarDbConfiguration configuration) { + init(context); + dbConfiguration = configuration; } + public static void terminate() { if (instance == null) { return; } instance.doTerminate(); + ContextUtil.terminate(); } /* @@ -49,11 +59,15 @@ private void doTerminate() { } } - protected SugarDb getSugarDb() { + public static SugarDbConfiguration getDbConfiguration() { + return dbConfiguration; + } + + public SugarDb getSugarDb() { return sugarDb; } - Map getEntitiesMap() { + public Map getEntitiesMap() { return entitiesMap; } } diff --git a/library/src/main/java/com/orm/SugarDataSource.java b/library/src/main/java/com/orm/SugarDataSource.java new file mode 100644 index 00000000..d2d9aa2c --- /dev/null +++ b/library/src/main/java/com/orm/SugarDataSource.java @@ -0,0 +1,441 @@ +package com.orm; + +import android.database.Cursor; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; + +import static com.orm.util.ThreadUtil.*; + +/** + * SugarDataSource provides basic crud operations and simplifies SugarRecord by using callbacks and + * performing Asynchronous execution to run queries. + * + * @author jonatan.salas + */ +@SuppressWarnings("all") +public final class SugarDataSource { + private final Class sClass; + + /** + * SugarDataSource constructor with params + * + * @param tClass class argument used then to run SugarRecord class queries + */ + private SugarDataSource(Class tClass) { + if (null == tClass) { + throw new IllegalArgumentException("sClass shouldn't be null!"); + } + + this.sClass = tClass; + } + + /** + * SugarDataSource static method to construct an Instance of this class. + * + * @param sClass class argument used then to run SugarRecord class queries + * @param generic argument that must be a SugarRecord extended class or @Table annotated class + * @return an instance of SugarDataSource + */ + public static SugarDataSource getInstance(Class sClass) { + return new SugarDataSource<>(sClass); + } + + /** + * Method used to perform an Asynchronous insert. It works on top of SugarRecord class, executes the + * insert query using Futures. + * + * @param object the object you want to insert. It must be a SugarRecord extended class or @Table annotated class + * @param successCallback the callback for a successful insert operation + * @param errorCallback the callback for an error in insert operation + */ + public void insert(final T object, final SuccessCallback successCallback, final ErrorCallback errorCallback) { + checkNotNull(successCallback); + checkNotNull(errorCallback); + checkNotNull(object); + + final Callable call = new Callable() { + @Override + public Long call() throws Exception { + return SugarRecord.save(object); + } + }; + + final Future future = doInBackground(call); + Long id; + + try { + id = future.get(); + + if (null == id) { + errorCallback.onError(new Exception("Error when performing insert of " + object.toString())); + } else { + successCallback.onSuccess(id); + } + + } catch (Exception e) { + errorCallback.onError(e); + } + } + + /** + * Method that performs a bulk insert. It works on top of SugarRecord class, and executes the query + * asynchronously using Futures. + * + * @param objects the list of objects that you want to insert. They must be SugarRecord extended objects or @Table annotatd objects. + * @param successCallback the callback for successful bulk insert operation + * @param errorCallback the callback for an error in bulk insert operation + */ + public void bulkInsert(final List objects, final SuccessCallback> successCallback, final ErrorCallback errorCallback) { + checkNotNull(successCallback); + checkNotNull(errorCallback); + checkNotNull(objects); + + final Callable> call = new Callable>() { + @Override + public List call() throws Exception { + List ids = new ArrayList<>(objects.size()); + + for (int i = 0; i < objects.size(); i++) { + Long id = SugarRecord.save(objects.get(i)); + ids.add(i, id); + } + + return ids; + } + }; + + final Future> future = doInBackground(call); + List ids; + + try { + ids = future.get(); + + if (null == ids || ids.isEmpty()) { + errorCallback.onError(new Exception("Error when performing bulk insert")); + } else { + successCallback.onSuccess(ids); + } + + } catch (Exception e) { + errorCallback.onError(e); + } + } + + /** + * Method that performs a findById, It works on top of SugarRecord class providing asynchronous + * execution with the use of Futures. + * + * @param id the id of the object you want to retrieve + * @param successCallback the callback to execute when the operation is successful + * @param errorCallback the callback to execute when the operation has a trouble + */ + public void findById(final Long id, final SuccessCallback successCallback, final ErrorCallback errorCallback) { + checkNotNull(successCallback); + checkNotNull(errorCallback); + checkNotNull(id); + + final Callable call = new Callable() { + @Override + public T call() throws Exception { + return SugarRecord.findById(getSugarClass(), id); + } + }; + + final Future future = doInBackground(call); + T object; + + try { + object = future.get(); + + if (null == object) { + errorCallback.onError(new Exception("The object with " + id.toString() + "doesn't exist in database")); + } else { + successCallback.onSuccess(object); + } + + } catch (Exception e) { + errorCallback.onError(e); + } + } + + /** + * Method that provides you the ability of perform a custom query and retrieve a cursor. It works on top of SugarRecord class, + * All the code is executed asynchronously with the usage of Futures and callbacks. + * + * @param whereClause the clause of the search + * @param whereArgs the arguments for the search + * @param groupBy the form that you want to group them + * @param orderBy the form that you want to order + * @param limit the limit of objects to want + * @param successCallback the callback to be executed if the operation is successful + * @param errorCallback the callback to be executed if the operation has an error + */ + public void query(final String whereClause, final String[] whereArgs, final String groupBy, final String orderBy, final String limit, final SuccessCallback successCallback, final ErrorCallback errorCallback) { + checkNotNull(successCallback); + checkNotNull(errorCallback); + + final Callable call = new Callable() { + @Override + public Cursor call() throws Exception { + return SugarRecord.getCursor(getSugarClass(), whereClause, whereArgs, groupBy, orderBy, limit); + } + }; + + final Future future = doInBackground(call); + Cursor cursor; + + try { + cursor = future.get(); + + if (null == cursor) { + errorCallback.onError(new Exception("Problem when trying to get the cursor")); + } else { + successCallback.onSuccess(cursor); + } + + } catch (Exception e) { + errorCallback.onError(e); + } + } + + /** + * Method that list all elements. It run a SugarRecord.listAll but it's code is performed asynchronously + * with the usage of Futures and callbacks. + * + * @param orderBy the way you want to order the objects you get + * @param successCallback the callback that is performed if the operation is successful + * @param errorCallback the callback that is performed if your code has an error + */ + public void listAll(final String orderBy, final SuccessCallback> successCallback, final ErrorCallback errorCallback) { + checkNotNull(successCallback); + checkNotNull(errorCallback); + + final Callable> call = new Callable>() { + @Override + public List call() throws Exception { + return SugarRecord.listAll(getSugarClass(), orderBy); + } + }; + + final Future> future = doInBackground(call); + List objects; + + try { + objects = future.get(); + + if (null == objects || objects.isEmpty()) { + errorCallback.onError(new Exception("There are no objects in the database")); + } else { + successCallback.onSuccess(objects); + } + + } catch (Exception e) { + errorCallback.onError(e); + } + } + + + /** + * Method that works on top of SugarRecord.update and runs the code asynchronously via Futures + * and callbacks. + * + * @param object the object you want to update + * @param successCallback the callback that will be performed if the update is successful + * @param errorCallback the callback that will be performed if the update has an error + */ + public void update(final T object, final SuccessCallback successCallback, final ErrorCallback errorCallback) { + checkNotNull(successCallback); + checkNotNull(errorCallback); + checkNotNull(object); + + final Callable call = new Callable() { + @Override + public Long call() throws Exception { + return SugarRecord.update(object); + } + }; + + final Future future = doInBackground(call); + Long id; + + try { + id = future.get(); + + if (null == id) { + errorCallback.onError(new Exception("Error when performing update of " + object.toString())); + } else { + successCallback.onSuccess(id); + } + + } catch (Exception e) { + errorCallback.onError(e); + } + } + + /** + * This method works on top of SugarRecord and provides asynchronous code execution via the usage of + * Futures and callbacks to handle success result and error. + * + * @param object the object you want to delete + * @param successCallback the callback to be performed when the operation is successful + * @param errorCallback the callback to be performed when the operation has an error + */ + public void delete(final T object, final SuccessCallback successCallback, final ErrorCallback errorCallback) { + checkNotNull(successCallback); + checkNotNull(errorCallback); + checkNotNull(object); + + final Callable call = new Callable() { + @Override + public Boolean call() throws Exception { + return SugarRecord.delete(object); + } + }; + + final Future future = doInBackground(call); + Boolean isDeleted; + + try { + isDeleted = future.get(); + + if (null == isDeleted || !isDeleted) { + errorCallback.onError(new Exception("Error when performing delete of " + object.toString())); + } else { + successCallback.onSuccess(isDeleted); + } + + } catch (Exception e) { + errorCallback.onError(e); + } + } + + /** + * Method that performs a selective delete. The code is executed asynchronously via the usage of Futures + * and result callbacks + * + * @param whereClause the clause for the search + * @param whereArgs the values + * @param successCallback the callback to be executed if there is no trouble + * @param errorCallback the callback to be executed if there is an error + */ + public void delete(final String whereClause, final String[] whereArgs, final SuccessCallback successCallback, final ErrorCallback errorCallback) { + checkNotNull(successCallback); + checkNotNull(errorCallback); + + final Callable call = new Callable() { + @Override + public Integer call() throws Exception { + return SugarRecord.deleteAll(getSugarClass(), whereClause, whereArgs); + } + }; + + final Future future = doInBackground(call); + Integer count; + + try { + count = future.get(); + + if (null == count) { + errorCallback.onError(new Exception("Error when performing delete of all elements")); + } else { + successCallback.onSuccess(count); + } + + } catch (Exception e) { + errorCallback.onError(e); + } + } + + /** + * Method that deletes all data in a SQLite table. + * + * @param successCallback the callback that is executed if the operation is succesful + * @param errorCallback the callback that is executed if there is an error + */ + public void deleteAll(final SuccessCallback successCallback, final ErrorCallback errorCallback) { + delete(null, null, successCallback, errorCallback); + } + + /** + * Method that performs a count + * + * @param successCallback the callback that is executed if this is successful + * @param errorCallback the callback that is executed if there is an error + */ + public void count(final SuccessCallback successCallback, final ErrorCallback errorCallback) { + checkNotNull(successCallback); + checkNotNull(errorCallback); + + final Callable call = new Callable() { + @Override + public Long call() throws Exception { + return SugarRecord.count(getSugarClass()); + } + }; + + final Future future = doInBackground(call); + Long count; + + try { + count = future.get(); + + if (null == count) { + errorCallback.onError(new Exception("Error when trying to get count")); + } else { + successCallback.onSuccess(count); + } + + } catch (Exception e) { + errorCallback.onError(e); + } + } + + /** + * Method that checks an object to be not null + * + * @param object the object to be checked + */ + protected void checkNotNull(Object object) { + if (null == object) { + throw new IllegalArgumentException("object shouldn't be null"); + } + } + + public Class getSugarClass() { + return sClass; + } + + /** + * The callback to be executed when some SugarDataSource operation is successful. + * + * @author jonatan.salas + * @param the parameter of the result that is passed to onSuccess method + */ + public interface SuccessCallback { + + /** + * This code is executed if there is no trouble on any SugarDataSource operation. + * + * @param result the result of some SugarDatasource operation + */ + void onSuccess(final S result); + } + + /** + * The callback to be executed when some SugarDataSource operation has an error. + * + * @author jonatan.salas + */ + public interface ErrorCallback { + + /** + * This method is executed if some trouble is detected when using some SugarDataSource method. + * + * @param e the exception thrown by the method of SugarDataSource you have invoked + */ + void onError(final Exception e); + } +} diff --git a/library/src/main/java/com/orm/SugarDb.java b/library/src/main/java/com/orm/SugarDb.java index a15110a3..bc71ba23 100644 --- a/library/src/main/java/com/orm/SugarDb.java +++ b/library/src/main/java/com/orm/SugarDb.java @@ -1,24 +1,33 @@ package com.orm; -import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; -import com.orm.util.ManifestHelper; +import com.orm.dsl.BuildConfig; +import com.orm.helper.ManifestHelper; import com.orm.util.SugarCursorFactory; -import static com.orm.util.ManifestHelper.getDatabaseVersion; -import static com.orm.util.ManifestHelper.getDebugEnabled; +import static com.orm.util.ContextUtil.getContext; +import static com.orm.helper.ManifestHelper.getDatabaseVersion; +import static com.orm.helper.ManifestHelper.getDbName; +import static com.orm.SugarContext.getDbConfiguration; public class SugarDb extends SQLiteOpenHelper { + private static final String LOG_TAG = "Sugar"; private final SchemaGenerator schemaGenerator; private SQLiteDatabase sqLiteDatabase; + private int openedConnections = 0; - public SugarDb(Context context) { - super(context, ManifestHelper.getDatabaseName(context), - new SugarCursorFactory(getDebugEnabled(context)), getDatabaseVersion(context)); - schemaGenerator = new SchemaGenerator(context); + //Prevent instantiation + private SugarDb() { + super(getContext(), getDbName(), new SugarCursorFactory(ManifestHelper.isDebugEnabled()), getDatabaseVersion()); + schemaGenerator = SchemaGenerator.getInstance(); + } + + public static SugarDb getInstance() { + return new SugarDb(); } @Override @@ -26,6 +35,19 @@ public void onCreate(SQLiteDatabase sqLiteDatabase) { schemaGenerator.createDatabase(sqLiteDatabase); } + @Override + public void onConfigure(SQLiteDatabase db) { + final SugarDbConfiguration configuration = getDbConfiguration(); + + if (null != configuration) { + db.setLocale(configuration.getDatabaseLocale()); + db.setMaximumSize(configuration.getMaxSize()); + db.setPageSize(configuration.getPageSize()); + } + + super.onConfigure(db); + } + @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { schemaGenerator.doUpgrade(sqLiteDatabase, oldVersion, newVersion); @@ -39,4 +61,26 @@ public synchronized SQLiteDatabase getDB() { return this.sqLiteDatabase; } + @Override + public synchronized SQLiteDatabase getReadableDatabase() { + if(ManifestHelper.isDebugEnabled()) { + Log.d(LOG_TAG, "getReadableDatabase"); + } + openedConnections++; + return super.getReadableDatabase(); + } + + @Override + public synchronized void close() { + if(ManifestHelper.isDebugEnabled()) { + Log.d(LOG_TAG, "getReadableDatabase"); + } + openedConnections--; + if(openedConnections == 0) { + if(ManifestHelper.isDebugEnabled()) { + Log.d(LOG_TAG, "closing"); + } + super.close(); + } + } } diff --git a/library/src/main/java/com/orm/SugarDbConfiguration.java b/library/src/main/java/com/orm/SugarDbConfiguration.java new file mode 100644 index 00000000..161fce26 --- /dev/null +++ b/library/src/main/java/com/orm/SugarDbConfiguration.java @@ -0,0 +1,62 @@ +package com.orm; + +import java.util.Locale; + +/** + * @author jonatan.salas + */ +public class SugarDbConfiguration { + + /** + * Tells SQLite which is the database default locale + */ + private Locale databaseLocale; + + /** + * Tells SQLite how much it can grow + */ + private Long maxSize; + + /** + * Tells SQLite the page size that have + */ + private Long pageSize; + + public SugarDbConfiguration() { } + + public Locale getDatabaseLocale() { + return databaseLocale; + } + + public SugarDbConfiguration setDatabaseLocale(Locale databaseLocale) { + this.databaseLocale = databaseLocale; + return this; + } + + public Long getMaxSize() { + return maxSize; + } + + public SugarDbConfiguration setMaxSize(Long maxSize) { + this.maxSize = maxSize; + return this; + } + + public Long getPageSize() { + return pageSize; + } + + public SugarDbConfiguration setPageSize(Long pageSize) { + this.pageSize = pageSize; + return this; + } + + @Override + public String toString() { + return "SugarDbConfiguration{" + + ", databaseLocale=" + databaseLocale + + ", maxSize=" + maxSize + + ", pageSize=" + pageSize + + '}'; + } +} diff --git a/library/src/main/java/com/orm/SugarRecord.java b/library/src/main/java/com/orm/SugarRecord.java index a51b71c4..9c1c6ec2 100644 --- a/library/src/main/java/com/orm/SugarRecord.java +++ b/library/src/main/java/com/orm/SugarRecord.java @@ -2,33 +2,31 @@ import android.content.ContentValues; import android.database.Cursor; +import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteStatement; import android.text.TextUtils; import android.util.Log; - -import com.orm.dsl.Table; -import com.orm.dsl.Unique; -import com.orm.util.NamingHelper; +import com.orm.annotation.Table; +import com.orm.annotation.Unique; +import com.orm.helper.ManifestHelper; +import com.orm.helper.NamingHelper; +import com.orm.inflater.EntityInflater; import com.orm.util.QueryBuilder; import com.orm.util.ReflectionUtil; import com.orm.util.SugarCursor; import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; +import java.sql.Statement; +import java.util.*; import static com.orm.SugarContext.getSugarContext; +import static com.orm.SugarContext.init; public class SugarRecord { - public static final String SUGAR = "Sugar"; + private Long id = null; private static SQLiteDatabase getSugarDataBase() { @@ -40,11 +38,11 @@ public static int deleteAll(Class type) { } public static int deleteAll(Class type, String whereClause, String... whereArgs) { - return getSugarDataBase().delete(NamingHelper.toSQLName(type), whereClause, whereArgs); + return getSugarDataBase().delete(NamingHelper.toTableName(type), whereClause, whereArgs); } public static Cursor getCursor(Class type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { - Cursor raw = getSugarDataBase().query(NamingHelper.toSQLName(type), null, whereClause, whereArgs, + Cursor raw = getSugarDataBase().query(NamingHelper.toTableName(type), null, whereClause, whereArgs, groupBy, null, orderBy, limit); return new SugarCursor(raw); } @@ -65,7 +63,9 @@ public static void saveInTx(Collection objects) { } sqLiteDatabase.setTransactionSuccessful(); } catch (Exception e) { - Log.i(SUGAR, "Error in saving in transaction " + e.getMessage()); + if (ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, "Error in saving in transaction " + e.getMessage()); + } } finally { sqLiteDatabase.endTransaction(); sqLiteDatabase.setLockingEnabled(true); @@ -88,7 +88,9 @@ public static void updateInTx(Collection objects) { } sqLiteDatabase.setTransactionSuccessful(); } catch (Exception e) { - Log.i(SUGAR, "Error in saving in transaction " + e.getMessage()); + if (ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, "Error in saving in transaction " + e.getMessage()); + } } finally { sqLiteDatabase.endTransaction(); sqLiteDatabase.setLockingEnabled(true); @@ -115,7 +117,9 @@ public static int deleteInTx(Collection objects) { sqLiteDatabase.setTransactionSuccessful(); } catch (Exception e) { deletedRows = 0; - Log.i(SUGAR, "Error in deleting in transaction " + e.getMessage()); + if(ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, "Error in deleting in transaction " + e.getMessage()); + } } finally { sqLiteDatabase.endTransaction(); sqLiteDatabase.setLockingEnabled(true); @@ -126,7 +130,7 @@ public static int deleteInTx(Collection objects) { public static List listAll(Class type) { return find(type, null, null, null, null, null); } - + public static List listAll(Class type, String orderBy) { return find(type, null, null, null, orderBy, null); } @@ -141,14 +145,14 @@ public static T findById(Class type, Integer id) { return findById(type, Long.valueOf(id)); } - public static List findById(Class type, String[] ids) { + public static List findById(Class type, String... ids) { String whereClause = "id IN (" + QueryBuilder.generatePlaceholders(ids.length) + ")"; return find(type, whereClause, ids); } public static T first(Classtype) { List list = findWithQuery(type, - "SELECT * FROM " + NamingHelper.toSQLName(type) + " ORDER BY ID ASC LIMIT 1"); + "SELECT * FROM " + NamingHelper.toTableName(type) + " ORDER BY ID ASC LIMIT 1"); if (list.isEmpty()) { return null; } @@ -157,7 +161,7 @@ public static T first(Classtype) { public static T last(Classtype) { List list = findWithQuery(type, - "SELECT * FROM " + NamingHelper.toSQLName(type) + " ORDER BY ID DESC LIMIT 1"); + "SELECT * FROM " + NamingHelper.toTableName(type) + " ORDER BY ID DESC LIMIT 1"); if (list.isEmpty()) { return null; } @@ -174,13 +178,13 @@ public static Iterator findAsIterator(Class type, String whereClause, public static Iterator findWithQueryAsIterator(Class type, String query, String... arguments) { Cursor cursor = getSugarDataBase().rawQuery(query, arguments); - return new CursorIterator(type, cursor); + return new CursorIterator<>(type, cursor); } public static Iterator findAsIterator(Class type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { - Cursor cursor = getSugarDataBase().query(NamingHelper.toSQLName(type), null, whereClause, whereArgs, + Cursor cursor = getSugarDataBase().query(NamingHelper.toTableName(type), null, whereClause, whereArgs, groupBy, null, orderBy, limit); - return new CursorIterator(type, cursor); + return new CursorIterator<>(type, cursor); } public static List find(Class type, String whereClause, String... whereArgs) { @@ -190,7 +194,7 @@ public static List find(Class type, String whereClause, String... wher public static List findWithQuery(Class type, String query, String... arguments) { Cursor cursor = getSugarDataBase().rawQuery(query, arguments); - return getEntitiesFromCursor(cursor, type); + return getEntitiesFromCursor(cursor, type); } public static void executeQuery(String query, String... arguments) { @@ -198,19 +202,43 @@ public static void executeQuery(String query, String... arguments) { } public static List find(Class type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { - Cursor cursor = getSugarDataBase().query(NamingHelper.toSQLName(type), null, whereClause, whereArgs, + + String args[]; + args = (whereArgs == null) ? null : replaceArgs(whereArgs); + + Cursor cursor = getSugarDataBase().query(NamingHelper.toTableName(type), null, whereClause, args, groupBy, null, orderBy, limit); return getEntitiesFromCursor(cursor, type); } + public static List findOneToMany(Class type, String relationFieldName, Object relationObject, Long relationObjectId) { + String args[] = { String.valueOf(relationObjectId) }; + String whereClause = NamingHelper.toSQLNameDefault(relationFieldName) + " = ?"; + + Cursor cursor = getSugarDataBase().query(NamingHelper.toTableName(type), null, whereClause, args, + null, null, null, null); + + return getEntitiesFromCursor(cursor, type, relationFieldName, relationObject); + } + public static List getEntitiesFromCursor(Cursor cursor, Class type){ + return getEntitiesFromCursor(cursor, type, null, null); + } + + public static List getEntitiesFromCursor(Cursor cursor, Class type, String relationFieldName, Object relationObject){ T entity; - List result = new ArrayList(); + List result = new ArrayList<>(); try { while (cursor.moveToNext()) { entity = type.getDeclaredConstructor().newInstance(); - inflate(cursor, entity, getSugarContext().getEntitiesMap()); + new EntityInflater() + .withCursor(cursor) + .withObject(entity) + .withEntitiesMap(getSugarContext().getEntitiesMap()) + .withRelationFieldName(relationFieldName) + .withRelationObject(relationObject) + .inflate(); result.add(entity); } } catch (Exception e) { @@ -222,20 +250,20 @@ public static List getEntitiesFromCursor(Cursor cursor, Class type){ return result; } - public static long count(Class type) { + public static long count(Class type) { return count(type, null, null, null, null, null); } - public static long count(Class type, String whereClause, String[] whereArgs) { + public static long count(Class type, String whereClause, String... whereArgs) { return count(type, whereClause, whereArgs, null, null, null); } - public static long count(Class type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { + public static long count(Class type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { long result = -1; String filter = (!TextUtils.isEmpty(whereClause)) ? " where " + whereClause : ""; SQLiteStatement sqliteStatement; try { - sqliteStatement = getSugarDataBase().compileStatement("SELECT count(*) FROM " + NamingHelper.toSQLName(type) + filter); + sqliteStatement = getSugarDataBase().compileStatement("SELECT count(*) FROM " + NamingHelper.toTableName(type) + filter); } catch (SQLiteException e) { e.printStackTrace(); return result; @@ -256,6 +284,130 @@ public static long count(Class type, String whereClause, String[] whereAr return result; } + public static long sum(Class type, String field) { + return sum(type, field, null, null); + } + + public static long sum(Class type, String field, String whereClause, String... whereArgs) { + long result = -1; + String filter = (!TextUtils.isEmpty(whereClause)) ? " where " + whereClause : ""; + SQLiteStatement sqLiteStatement; + try { + sqLiteStatement = getSugarDataBase().compileStatement("SELECT sum(" + field + ") FROM " + NamingHelper.toTableName(type) + filter); + } catch (SQLiteException e) { + e.printStackTrace(); + return result; + } + + if (whereArgs != null) { + for (int i = whereArgs.length; i != 0; i--) { + sqLiteStatement.bindString(i, whereArgs[i - 1]); + } + } + + try { + result = sqLiteStatement.simpleQueryForLong(); + } finally { + sqLiteStatement.close(); + } + + return result; + } + + public static float average(Class type, String field) { + return average(type, field, null, null); + } + + public static float average(Class type, String field, String whereClause, String... whereArgs) { + float result = -1; + Cursor cursor; + String filter = (!TextUtils.isEmpty(whereClause))? "where" + whereClause : ""; + String avgField = (!TextUtils.isEmpty(field))? "AVG( " + field + " ) " : ""; + + if (avgField.isEmpty()) throw new NullPointerException("field " + field + "is empty"); + try { + cursor = (whereArgs != null) ? getSugarDataBase().query(NamingHelper.toTableName(type), + new String[]{avgField}, whereClause, whereArgs, null, null, null) // default helper method + : getSugarDataBase().rawQuery("SELECT AVG( " + field + ") FROM " // raw query + + NamingHelper.toTableName(type) + filter, null); + } catch (SQLiteException e){ + e.printStackTrace(); + return result; + } + + try { + cursor.moveToFirst(); + result = cursor.getFloat(0); + } finally { + cursor.close(); + } + + return result; + } + + public static long max(Class type, String field) { + return max(type, field, null, null); + } + + public static long max(Class type, String field, String whereClause, String... whereArgs) { + // handles only single column max + long result = -1; + Cursor cursor; + String filter = (!TextUtils.isEmpty(whereClause))? "where" + whereClause : ""; + String maxField = (!TextUtils.isEmpty(field))? "AVG( " + field + " ) " : ""; + + if (maxField.isEmpty()) throw new NullPointerException("field" + field + "is empty"); + + try { + cursor = (whereArgs != null) ? getSugarDataBase().query(NamingHelper.toTableName(type), + new String[]{maxField}, whereClause, whereArgs, null, null, null) // default helper method + : getSugarDataBase().rawQuery("SELECT MAX( " + field + ") FROM " // raw query + + NamingHelper.toTableName(type) + filter, null); + } catch (SQLiteException e){ + e.printStackTrace(); + return result; + } + + try { + cursor.moveToFirst(); + result = cursor.getLong(0); + } finally { + cursor.close(); + } + return result; + } + + public static long min(Class type, String field){return min(type,field,null,null);} + + public static long min(Class type , String field , String whereClause, String... whereArgs){ + long result = -1; + Cursor cursor; + String filter = (!TextUtils.isEmpty(whereClause))? "where" + whereClause : ""; + String minField = (!TextUtils.isEmpty(field))? "AVG( " + field + " ) " : ""; + + if (minField.isEmpty()) throw new NullPointerException("field" + field + "is empty"); + + try { + cursor = (whereArgs != null) ? getSugarDataBase().query(NamingHelper.toTableName(type), + new String[]{minField}, whereClause, whereArgs, null, null, null) // default helper method + : getSugarDataBase().rawQuery("SELECT MIN( " + field + ") FROM " // raw query + + NamingHelper.toTableName(type) + filter, null); + } catch (SQLiteException e){ + e.printStackTrace(); + return result; + } + + try { + cursor.moveToFirst(); + result = cursor.getLong(0); + } finally { + cursor.close(); + } + return result; + } + + + public static long save(Object object) { return save(getSugarDataBase(), object); } @@ -277,14 +429,14 @@ static long save(SQLiteDatabase db, Object object) { values.put("id", entitiesMap.get(object)); } - long id = db.insertWithOnConflict(NamingHelper.toSQLName(object.getClass()), null, values, + long id = db.insertWithOnConflict(NamingHelper.toTableName(object.getClass()), null, values, SQLiteDatabase.CONFLICT_REPLACE); if (object.getClass().isAnnotationPresent(Table.class)) { if (idField != null) { idField.setAccessible(true); try { - idField.set(object, new Long(id)); + idField.set(object, id); } catch (IllegalAccessException e) { e.printStackTrace(); } @@ -295,7 +447,9 @@ static long save(SQLiteDatabase db, Object object) { ((SugarRecord) object).setId(id); } - Log.i(SUGAR, object.getClass().getSimpleName() + " saved : " + id); + if (ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, object.getClass().getSimpleName() + " saved : " + id); + } return id; } @@ -308,7 +462,6 @@ static long update(SQLiteDatabase db, Object object) { Map entitiesMap = getSugarContext().getEntitiesMap(); List columns = ReflectionUtil.getTableFields(object.getClass()); ContentValues values = new ContentValues(columns.size()); - Field idField = null; StringBuilder whereClause = new StringBuilder(); List whereArgs = new ArrayList<>(); @@ -317,7 +470,7 @@ static long update(SQLiteDatabase db, Object object) { if(column.isAnnotationPresent(Unique.class)) { try { column.setAccessible(true); - String columnName = NamingHelper.toSQLName(column); + String columnName = NamingHelper.toColumnName(column); Object columnValue = column.get(object); whereClause.append(columnName).append(" = ?"); @@ -334,51 +487,19 @@ static long update(SQLiteDatabase db, Object object) { String[] whereArgsArray = whereArgs.toArray(new String[whereArgs.size()]); // Get SugarRecord based on Unique values - long id = db.update(NamingHelper.toSQLName(object.getClass()), values, whereClause.toString(), whereArgsArray); + long rowsEffected = db.update(NamingHelper.toTableName(object.getClass()), values, whereClause.toString(), whereArgsArray); - return id; + if (rowsEffected == 0) { + return save(db, object); + } else { + return rowsEffected; + } } - - - public static boolean isSugarEntity(Class objectClass) { + public static boolean isSugarEntity(Class objectClass) { return objectClass.isAnnotationPresent(Table.class) || SugarRecord.class.isAssignableFrom(objectClass); } - private static void inflate(Cursor cursor, Object object, Map entitiesMap) { - List columns = ReflectionUtil.getTableFields(object.getClass()); - if (!entitiesMap.containsKey(object)) { - entitiesMap.put(object, cursor.getLong(cursor.getColumnIndex(("ID")))); - } - - for (Field field : columns) { - field.setAccessible(true); - Class fieldType = field.getType(); - if (isSugarEntity(fieldType)) { - try { - long id = cursor.getLong(cursor.getColumnIndex(NamingHelper.toSQLName(field))); - field.set(object, (id > 0) ? findById(fieldType, id) : null); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } else { - ReflectionUtil.setFieldValueFromCursor(cursor, field, object); - } - } - } - - public boolean delete() { - Long id = getId(); - Class type = getClass(); - if (id != null && id > 0L) { - Log.i(SUGAR, type.getSimpleName() + " deleted : " + id); - return getSugarDataBase().delete(NamingHelper.toSQLName(type), "Id=?", new String[]{id.toString()}) == 1; - } else { - Log.i(SUGAR, "Cannot delete object: " + type.getSimpleName() + " - object has not been saved"); - return false; - } - } - public static boolean delete(Object object) { Class type = object.getClass(); if (type.isAnnotationPresent(Table.class)) { @@ -387,24 +508,63 @@ public static boolean delete(Object object) { field.setAccessible(true); Long id = (Long) field.get(object); if (id != null && id > 0L) { - boolean deleted = getSugarDataBase().delete(NamingHelper.toSQLName(type), "Id=?", new String[]{id.toString()}) == 1; - Log.i(SUGAR, type.getSimpleName() + " deleted : " + id); + boolean deleted = getSugarDataBase().delete(NamingHelper.toTableName(type), "Id=?", new String[]{id.toString()}) == 1; + if (ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, type.getSimpleName() + " deleted : " + id); + } return deleted; } else { - Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - object has not been saved"); + if (ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - object has not been saved"); + } return false; } } catch (NoSuchFieldException e) { - Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - annotated object has no id"); + if (ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - annotated object has no id"); + } return false; } catch (IllegalAccessException e) { - Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - can't access id"); + if (ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - can't access id"); + } return false; } } else if (SugarRecord.class.isAssignableFrom(type)) { return ((SugarRecord) object).delete(); } else { - Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - not persisted"); + if(ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - not persisted"); + } + return false; + } + } + + public static String[] replaceArgs(String[] args) { + + String[] replace = new String[args.length]; + for (int i = 0; i < args.length; i++) { + + replace[i] = (args[i].equals("true")) ? replace[i] = "1" : (args[i].equals("false")) ? replace[i] = "0" : args[i]; + + } + + return replace; + + } + + public boolean delete() { + Long id = getId(); + Class type = getClass(); + if (id != null && id > 0L) { + if (ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, type.getSimpleName() + " deleted : " + id); + } + return getSugarDataBase().delete(NamingHelper.toTableName(type), "Id=?", new String[]{id.toString()}) == 1; + } else { + if(ManifestHelper.isDebugEnabled()) { + Log.i(SUGAR, "Cannot delete object: " + type.getSimpleName() + " - object has not been saved"); + } return false; } } @@ -419,7 +579,11 @@ public long update() { @SuppressWarnings("unchecked") void inflate(Cursor cursor) { - inflate(cursor, this, getSugarContext().getEntitiesMap()); + new EntityInflater() + .withCursor(cursor) + .withObject(this) + .withEntitiesMap(getSugarContext().getEntitiesMap()) + .inflate(); } public Long getId() { @@ -457,7 +621,11 @@ public E next() { try { entity = type.getDeclaredConstructor().newInstance(); - inflate(cursor, entity, getSugarContext().getEntitiesMap()); + new EntityInflater() + .withCursor(cursor) + .withObject(entity) + .withEntitiesMap(getSugarContext().getEntitiesMap()) + .inflate(); } catch (Exception e) { e.printStackTrace(); } finally { diff --git a/library/src/main/java/com/orm/SugarTransactionHelper.java b/library/src/main/java/com/orm/SugarTransactionHelper.java deleted file mode 100644 index 73440635..00000000 --- a/library/src/main/java/com/orm/SugarTransactionHelper.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.orm; - -import android.database.sqlite.SQLiteDatabase; -import android.util.Log; - -public class SugarTransactionHelper { - - public static void doInTransaction(SugarTransactionHelper.Callback callback) { - SQLiteDatabase database = SugarContext.getSugarContext().getSugarDb().getDB(); - database.beginTransaction(); - - try { - Log.d(SugarTransactionHelper.class.getSimpleName(), - "Callback executing within transaction"); - callback.manipulateInTransaction(); - database.setTransactionSuccessful(); - Log.d(SugarTransactionHelper.class.getSimpleName(), - "Callback successfully executed within transaction"); - } catch (Throwable e) { - Log.d(SugarTransactionHelper.class.getSimpleName(), - "Could execute callback within transaction", e); - } finally { - database.endTransaction(); - } - } - - public static interface Callback { - void manipulateInTransaction(); - } -} diff --git a/library/src/main/java/com/orm/dsl/Column.java b/library/src/main/java/com/orm/annotation/Column.java similarity index 64% rename from library/src/main/java/com/orm/dsl/Column.java rename to library/src/main/java/com/orm/annotation/Column.java index 2c47e3c0..ce4c2376 100644 --- a/library/src/main/java/com/orm/dsl/Column.java +++ b/library/src/main/java/com/orm/annotation/Column.java @@ -1,9 +1,12 @@ -package com.orm.dsl; +package com.orm.annotation; +import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) public @interface Column { String name(); boolean unique() default false; diff --git a/library/src/main/java/com/orm/dsl/Ignore.java b/library/src/main/java/com/orm/annotation/Ignore.java similarity index 53% rename from library/src/main/java/com/orm/dsl/Ignore.java rename to library/src/main/java/com/orm/annotation/Ignore.java index 9678d33a..d214a559 100644 --- a/library/src/main/java/com/orm/dsl/Ignore.java +++ b/library/src/main/java/com/orm/annotation/Ignore.java @@ -1,8 +1,11 @@ -package com.orm.dsl; +package com.orm.annotation; +import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) public @interface Ignore { } diff --git a/library/src/main/java/com/orm/annotation/MultiUnique.java b/library/src/main/java/com/orm/annotation/MultiUnique.java new file mode 100644 index 00000000..fbdaa0df --- /dev/null +++ b/library/src/main/java/com/orm/annotation/MultiUnique.java @@ -0,0 +1,15 @@ +package com.orm.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Inherited +public @interface MultiUnique { + String value(); +} + diff --git a/library/src/main/java/com/orm/dsl/NotNull.java b/library/src/main/java/com/orm/annotation/NotNull.java similarity index 53% rename from library/src/main/java/com/orm/dsl/NotNull.java rename to library/src/main/java/com/orm/annotation/NotNull.java index b2361851..f3a6f585 100644 --- a/library/src/main/java/com/orm/dsl/NotNull.java +++ b/library/src/main/java/com/orm/annotation/NotNull.java @@ -1,8 +1,11 @@ -package com.orm.dsl; +package com.orm.annotation; +import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) public @interface NotNull { } diff --git a/library/src/main/java/com/orm/annotation/OneToMany.java b/library/src/main/java/com/orm/annotation/OneToMany.java new file mode 100644 index 00000000..5423256b --- /dev/null +++ b/library/src/main/java/com/orm/annotation/OneToMany.java @@ -0,0 +1,16 @@ +package com.orm.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Created by Łukasz Wesołowski on 28.07.2016. + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface OneToMany { + String targetField(); +} diff --git a/library/src/main/java/com/orm/dsl/Table.java b/library/src/main/java/com/orm/annotation/Table.java similarity index 57% rename from library/src/main/java/com/orm/dsl/Table.java rename to library/src/main/java/com/orm/annotation/Table.java index 0dfaa18b..82ffc15b 100644 --- a/library/src/main/java/com/orm/dsl/Table.java +++ b/library/src/main/java/com/orm/annotation/Table.java @@ -1,9 +1,12 @@ -package com.orm.dsl; +package com.orm.annotation; +import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) public @interface Table { String name() default ""; } diff --git a/library/src/main/java/com/orm/dsl/Unique.java b/library/src/main/java/com/orm/annotation/Unique.java similarity index 53% rename from library/src/main/java/com/orm/dsl/Unique.java rename to library/src/main/java/com/orm/annotation/Unique.java index 7384b749..a6027e05 100644 --- a/library/src/main/java/com/orm/dsl/Unique.java +++ b/library/src/main/java/com/orm/annotation/Unique.java @@ -1,8 +1,11 @@ -package com.orm.dsl; +package com.orm.annotation; +import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) public @interface Unique { } diff --git a/library/src/main/java/com/orm/util/ManifestHelper.java b/library/src/main/java/com/orm/helper/ManifestHelper.java similarity index 53% rename from library/src/main/java/com/orm/util/ManifestHelper.java rename to library/src/main/java/com/orm/helper/ManifestHelper.java index fb65724c..cab85fd2 100644 --- a/library/src/main/java/com/orm/util/ManifestHelper.java +++ b/library/src/main/java/com/orm/helper/ManifestHelper.java @@ -1,39 +1,46 @@ -package com.orm.util; +package com.orm.helper; -import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.util.Log; +import static com.orm.util.ContextUtil.*; + /** * Helper class for accessing properties in the AndroidManifest */ -public class ManifestHelper { +public final class ManifestHelper { + private static final String LOG_TAG = "Sugar"; + private static Boolean debugEnabled = null; /** * Key for the database name meta data. */ public final static String METADATA_DATABASE = "DATABASE"; + /** - * Key for the database verison meta data. + * Key for the database version meta data. */ public final static String METADATA_VERSION = "VERSION"; public final static String METADATA_DOMAIN_PACKAGE_NAME = "DOMAIN_PACKAGE_NAME"; public final static String METADATA_QUERY_LOG = "QUERY_LOG"; + /** * The default name for the database unless specified in the AndroidManifest. */ public final static String DATABASE_DEFAULT_NAME = "Sugar.db"; + //Prevent instantiation + private ManifestHelper() { } + /** * Grabs the database version from the manifest. * - * @param context the {@link android.content.Context} of the Android application * @return the database version as specified by the {@link #METADATA_VERSION} version or 1 of * not present */ - public static int getDatabaseVersion(Context context) { - Integer databaseVersion = getMetaDataInteger(context, METADATA_VERSION); + public static int getDatabaseVersion() { + Integer databaseVersion = getMetaDataInteger(METADATA_VERSION); if ((databaseVersion == null) || (databaseVersion == 0)) { databaseVersion = 1; @@ -43,13 +50,12 @@ public static int getDatabaseVersion(Context context) { } /** - * Grabs the domain name of the model classes from the manifest. + * Grabs the domain name of the model classes from the manifest. * - * @param context the {@link android.content.Context} of the Android application * @return the package String that Sugar uses to search for model classes */ - public static String getDomainPackageName(Context context){ - String domainPackageName = getMetaDataString(context, METADATA_DOMAIN_PACKAGE_NAME); + public static String getDomainPackageName() { + String domainPackageName = getMetaDataString(METADATA_DOMAIN_PACKAGE_NAME); if (domainPackageName == null) { domainPackageName = ""; @@ -61,12 +67,11 @@ public static String getDomainPackageName(Context context){ /** * Grabs the name of the database file specified in the manifest. * - * @param context the {@link android.content.Context} of the Android application * @return the value for the {@value #METADATA_DATABASE} meta data in the AndroidManifest or * {@link #DATABASE_DEFAULT_NAME} if not present */ - public static String getDatabaseName(Context context) { - String databaseName = getMetaDataString(context, METADATA_DATABASE); + public static String getDatabaseName() { + String databaseName = getMetaDataString(METADATA_DATABASE); if (databaseName == null) { databaseName = DATABASE_DEFAULT_NAME; @@ -75,59 +80,62 @@ public static String getDatabaseName(Context context) { return databaseName; } + public static String getDbName() { + return getDatabaseName(); + } + /** * Grabs the debug flag from the manifest. * - * @param context the {@link android.content.Context} of the Android application * @return true if the debug flag is enabled */ - public static boolean getDebugEnabled(Context context) { - return getMetaDataBoolean(context, METADATA_QUERY_LOG); + public static boolean isDebugEnabled() { + return (null == debugEnabled) ? debugEnabled = getMetaDataBoolean(METADATA_QUERY_LOG) : debugEnabled; } - private static String getMetaDataString(Context context, String name) { + private static String getMetaDataString(String name) { + PackageManager pm = getPackageManager(); String value = null; - PackageManager pm = context.getPackageManager(); try { - ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), - PackageManager.GET_META_DATA); + ApplicationInfo ai = pm.getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA); value = ai.metaData.getString(name); } catch (Exception e) { - Log.d("sugar", "Couldn't find config value: " + name); + if (ManifestHelper.isDebugEnabled()) { + Log.d(LOG_TAG, "Couldn't find config value: " + name); + } } return value; } - private static Integer getMetaDataInteger(Context context, String name) { + private static Integer getMetaDataInteger(String name) { + PackageManager pm = getPackageManager(); Integer value = null; - PackageManager pm = context.getPackageManager(); try { - ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), - PackageManager.GET_META_DATA); + ApplicationInfo ai = pm.getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA); value = ai.metaData.getInt(name); } catch (Exception e) { - Log.d("sugar", "Couldn't find config value: " + name); + if (ManifestHelper.isDebugEnabled()) { + Log.d(LOG_TAG, "Couldn't find config value: " + name); + } } return value; } - private static Boolean getMetaDataBoolean(Context context, String name) { + private static Boolean getMetaDataBoolean(String name) { + PackageManager pm = getPackageManager(); Boolean value = false; - PackageManager pm = context.getPackageManager(); try { - ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), - PackageManager.GET_META_DATA); + ApplicationInfo ai = pm.getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA); value = ai.metaData.getBoolean(name); } catch (Exception e) { - Log.d("sugar", "Couldn't find config value: " + name); + Log.d(LOG_TAG, "Couldn't find config value: " + name); } return value; } - } diff --git a/library/src/main/java/com/orm/util/MultiDexHelper.java b/library/src/main/java/com/orm/helper/MultiDexHelper.java similarity index 59% rename from library/src/main/java/com/orm/util/MultiDexHelper.java rename to library/src/main/java/com/orm/helper/MultiDexHelper.java index 37b57894..588908cd 100644 --- a/library/src/main/java/com/orm/util/MultiDexHelper.java +++ b/library/src/main/java/com/orm/helper/MultiDexHelper.java @@ -1,4 +1,4 @@ -package com.orm.util; +package com.orm.helper; import android.content.Context; import android.content.SharedPreferences; @@ -14,48 +14,60 @@ import dalvik.system.DexFile; +import static com.orm.util.ContextUtil.getSharedPreferences; +import static com.orm.util.ContextUtil.getPackageManager; +import static com.orm.util.ContextUtil.getPackageName; + /** * Created by xudshen@hotmail.com on 14/11/13. */ - //http://stackoverflow.com/a/26892658 -public class MultiDexHelper { +public final class MultiDexHelper { private static final String EXTRACTED_NAME_EXT = ".classes"; private static final String EXTRACTED_SUFFIX = ".zip"; - - private static final String SECONDARY_FOLDER_NAME = "code_cache" + File.separator + - "secondary-dexes"; - + private static final String INSTANT_RUN_DEX_DIR_PATH = "files/instant-run/dex/"; + private static final String SECONDARY_FOLDER_NAME = "code_cache" + File.separator + "secondary-dexes"; private static final String PREFS_FILE = "multidex.version"; private static final String KEY_DEX_NUMBER = "dex.number"; - private static SharedPreferences getMultiDexPreferences(Context context) { - return context.getSharedPreferences(PREFS_FILE, - Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB - ? Context.MODE_PRIVATE - : Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); + //Prevent instantiation.. + private MultiDexHelper() { } + + @SuppressWarnings("all") + private static SharedPreferences getMultiDexPreferences() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { + return getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE); + } else { + return getSharedPreferences(PREFS_FILE, Context.MODE_MULTI_PROCESS); + } } /** * get all the dex path * - * @param context the application context - * @return all the dex path + * @return all the dex path, including the ones in the newly added instant-run folder * @throws PackageManager.NameNotFoundException * @throws IOException */ - public static List getSourcePaths(Context context) throws PackageManager.NameNotFoundException, IOException { - ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0); + public static List getSourcePaths() throws PackageManager.NameNotFoundException, IOException { + ApplicationInfo applicationInfo = getPackageManager().getApplicationInfo(getPackageName(), 0); File sourceApk = new File(applicationInfo.sourceDir); File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME); + File instantRunDir = new File(applicationInfo.dataDir, INSTANT_RUN_DEX_DIR_PATH); //default instant-run dir - List sourcePaths = new ArrayList(); + List sourcePaths = new ArrayList<>(); sourcePaths.add(applicationInfo.sourceDir); //add the default apk path + if (instantRunDir.exists()) { //check if app using instant run + for(final File dexFile : instantRunDir.listFiles()) { //add all sources from instan-run + sourcePaths.add(dexFile.getAbsolutePath()); + } + } + //the prefix of extracted file, ie: test.classes String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT; //the total dex numbers - int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1); + int totalDexNumber = getMultiDexPreferences().getInt(KEY_DEX_NUMBER, 1); for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) { //for each dex file, ie: test.classes2.zip, test.classes3.zip... @@ -64,9 +76,6 @@ public static List getSourcePaths(Context context) throws PackageManager if (extractedFile.isFile()) { sourcePaths.add(extractedFile.getAbsolutePath()); //we ignore the verify zip part - } else { - throw new IOException("Missing extracted secondary dex file '" + - extractedFile.getPath() + "'"); } } @@ -76,16 +85,15 @@ public static List getSourcePaths(Context context) throws PackageManager /** * get all the classes name in "classes.dex", "classes2.dex", .... * - * @param context the application context * @return all the classes name * @throws PackageManager.NameNotFoundException * @throws IOException */ - public static List getAllClasses(Context context) throws PackageManager.NameNotFoundException, IOException { - List classNames = new ArrayList(); - for (String path : getSourcePaths(context)) { + public static List getAllClasses() throws PackageManager.NameNotFoundException, IOException { + List classNames = new ArrayList<>(); + for (String path : getSourcePaths()) { try { - DexFile dexfile = null; + DexFile dexfile; if (path.endsWith(EXTRACTED_SUFFIX)) { //NOT use new DexFile(path), because it will throw "permission error in /data/dalvik-cache" dexfile = DexFile.loadDex(path, path + ".tmp", 0); @@ -97,10 +105,9 @@ public static List getAllClasses(Context context) throws PackageManager. classNames.add(dexEntries.nextElement()); } } catch (IOException e) { - throw new IOException("Error at loading dex file '" + - path + "'"); + throw new IOException("Error at loading dex file '" + path + "'"); } } return classNames; } -} \ No newline at end of file +} diff --git a/library/src/main/java/com/orm/util/NamingHelper.java b/library/src/main/java/com/orm/helper/NamingHelper.java similarity index 81% rename from library/src/main/java/com/orm/util/NamingHelper.java rename to library/src/main/java/com/orm/helper/NamingHelper.java index 734b4a56..0ae3128b 100644 --- a/library/src/main/java/com/orm/util/NamingHelper.java +++ b/library/src/main/java/com/orm/helper/NamingHelper.java @@ -1,16 +1,14 @@ -package com.orm.util; +package com.orm.helper; -import android.text.TextUtils; - -import com.orm.dsl.Column; -import com.orm.dsl.Table; +import com.orm.annotation.Column; +import com.orm.annotation.Table; import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -public class NamingHelper { +public final class NamingHelper { + + //Prevent instantiation + private NamingHelper() { } /** * Converts a given CamelCasedString to UPPER_CASE_UNDER_SCORE. @@ -58,11 +56,11 @@ public static String toSQLNameDefault(String camelCased) { * * @param field the {@link java.lang.reflect.Field} that will be mapped * @return the name of the given Field as represented in the database. If the Field is annotated - * with {@link com.orm.dsl.Column} then the {@link com.orm.dsl.Column#name()} will be + * with {@link com.orm.annotation.Column} then the {@link com.orm.annotation.Column#name()} will be * returned. Else, the Field's {@link java.lang.reflect.Field#getName()} will be * converted from CamelCase to UNDER_SCORE notation */ - public static String toSQLName(Field field) { + public static String toColumnName(Field field) { if (field.isAnnotationPresent(Column.class)) { Column annotation = field.getAnnotation(Column.class); return annotation.name(); @@ -74,12 +72,12 @@ public static String toSQLName(Field field) { /** * Maps a Java Class to the name of the class. * - * @param table the generic {@link java.lang.Class} that defines a database table - * @return if the given class is annotated with {@link com.orm.dsl.Table} then the value for - * {@link com.orm.dsl.Table#name()} will be returned. Else, the class' simple name will + * @param table the generic {@link java.lang.Class} that defines a database table + * @return if the given class is annotated with {@link com.orm.annotation.Table} then the value for + * {@link com.orm.annotation.Table#name()} will be returned. Else, the class' simple name will * be converted from CamelCase to UNDER_SCORE notation */ - public static String toSQLName(Class table) { + public static String toTableName(Class table) { if (table.isAnnotationPresent(Table.class)) { Table annotation = table.getAnnotation(Table.class); if ("".equals(annotation.name())) { diff --git a/library/src/main/java/com/orm/helper/SugarTransactionHelper.java b/library/src/main/java/com/orm/helper/SugarTransactionHelper.java new file mode 100644 index 00000000..dbb9ca26 --- /dev/null +++ b/library/src/main/java/com/orm/helper/SugarTransactionHelper.java @@ -0,0 +1,41 @@ +package com.orm.helper; + +import android.database.sqlite.SQLiteDatabase; +import android.util.Log; + +import static com.orm.SugarContext.getSugarContext; + +public final class SugarTransactionHelper { + private static final String LOG_TAG = SugarTransactionHelper.class.getSimpleName(); + + //Prevent instantiation.. + private SugarTransactionHelper() { } + + public static void doInTransaction(Callback callback) { + final SQLiteDatabase database = getSugarContext().getSugarDb().getDB(); + database.beginTransaction(); + + try { + if (ManifestHelper.isDebugEnabled()) { + Log.d(LOG_TAG, "Callback executing within transaction"); + } + + callback.manipulateInTransaction(); + database.setTransactionSuccessful(); + + if (ManifestHelper.isDebugEnabled()) { + Log.d(LOG_TAG, "Callback successfully executed within transaction"); + } + } catch (Throwable e) { + if (ManifestHelper.isDebugEnabled()) { + Log.d(LOG_TAG, "Could execute callback within transaction", e); + } + } finally { + database.endTransaction(); + } + } + + public interface Callback { + void manipulateInTransaction(); + } +} diff --git a/library/src/main/java/com/orm/inflater/EntityInflater.java b/library/src/main/java/com/orm/inflater/EntityInflater.java new file mode 100644 index 00000000..5d71e5df --- /dev/null +++ b/library/src/main/java/com/orm/inflater/EntityInflater.java @@ -0,0 +1,75 @@ +package com.orm.inflater; + +import android.database.Cursor; +import com.orm.SugarRecord; +import com.orm.inflater.field.*; +import com.orm.util.ReflectionUtil; + +import java.lang.reflect.Field; +import java.util.List; +import java.util.Map; + +/** + * Created by Łukasz Wesołowski on 03.08.2016. + */ +public class EntityInflater { + private Cursor cursor; + private Object object; + private Object relationObject; + private String relationFieldName; + private Map entitiesMap; + + public EntityInflater withCursor(Cursor cursor) { + this.cursor = cursor; + return this; + } + + public EntityInflater withObject(Object object) { + this.object = object; + return this; + } + + public EntityInflater withRelationObject(Object relationObject) { + this.relationObject = relationObject; + return this; + } + + public EntityInflater withRelationFieldName(String relationFieldName) { + this.relationFieldName = relationFieldName; + return this; + } + + public EntityInflater withEntitiesMap(Map entitiesMap) { + this.entitiesMap = entitiesMap; + return this; + } + + public void inflate() { + List columns = ReflectionUtil.getTableFields(object.getClass()); + Long objectId = cursor.getLong(cursor.getColumnIndex(("ID"))); + if (!entitiesMap.containsKey(object)) { + entitiesMap.put(object, objectId); + } + + FieldInflater fieldInflater; + + for (Field field : columns) { + field.setAccessible(true); + Class fieldType = field.getType(); + + if (SugarRecord.isSugarEntity(fieldType)) { + if (field.getName().equals(relationFieldName)) { + fieldInflater = new RelationEntityFieldInflater(field, cursor, object, fieldType, relationObject); + } else { + fieldInflater = new EntityFieldInflater(field, cursor, object, fieldType); + } + } else if (fieldType.equals(List.class)) { + fieldInflater = new ListFieldInflater(field, cursor, object, fieldType); + } else { + fieldInflater = new DefaultFieldInflater(field, cursor, object, fieldType); + } + + fieldInflater.inflate(); + } + } +} diff --git a/library/src/main/java/com/orm/inflater/field/DefaultFieldInflater.java b/library/src/main/java/com/orm/inflater/field/DefaultFieldInflater.java new file mode 100644 index 00000000..d1cd8542 --- /dev/null +++ b/library/src/main/java/com/orm/inflater/field/DefaultFieldInflater.java @@ -0,0 +1,21 @@ +package com.orm.inflater.field; + +import android.database.Cursor; +import com.orm.util.ReflectionUtil; + +import java.lang.reflect.Field; + +/** + * Created by Łukasz Wesołowski on 03.08.2016. + */ +public class DefaultFieldInflater extends FieldInflater { + + public DefaultFieldInflater(Field field, Cursor cursor, Object object, Class fieldType) { + super(field, cursor, object, fieldType); + } + + @Override + public void inflate() { + ReflectionUtil.setFieldValueFromCursor(cursor, field, object); + } +} diff --git a/library/src/main/java/com/orm/inflater/field/EntityFieldInflater.java b/library/src/main/java/com/orm/inflater/field/EntityFieldInflater.java new file mode 100644 index 00000000..9eda8f8e --- /dev/null +++ b/library/src/main/java/com/orm/inflater/field/EntityFieldInflater.java @@ -0,0 +1,29 @@ +package com.orm.inflater.field; + +import android.database.Cursor; +import android.util.Log; +import com.orm.SugarRecord; +import com.orm.helper.NamingHelper; + +import java.lang.reflect.Field; + +/** + * Created by Łukasz Wesołowski on 03.08.2016. + */ +public class EntityFieldInflater extends FieldInflater { + private static final String LOG_TAG = "EntityFieldInflater"; + + public EntityFieldInflater(Field field, Cursor cursor, Object object, Class fieldType) { + super(field, cursor, object, fieldType); + } + + @Override + public void inflate() { + try { + long id = cursor.getLong(cursor.getColumnIndex(NamingHelper.toColumnName(field))); + field.set(object, (id > 0) ? SugarRecord.findById(fieldType, id) : null); + } catch (IllegalAccessException e) { + Log.e(LOG_TAG, String.format("Error while inflating entity field %s", field), e); + } + } +} diff --git a/library/src/main/java/com/orm/inflater/field/FieldInflater.java b/library/src/main/java/com/orm/inflater/field/FieldInflater.java new file mode 100644 index 00000000..87795340 --- /dev/null +++ b/library/src/main/java/com/orm/inflater/field/FieldInflater.java @@ -0,0 +1,24 @@ +package com.orm.inflater.field; + +import android.database.Cursor; + +import java.lang.reflect.Field; + +/** + * Created by Łukasz Wesołowski on 03.08.2016. + */ +public abstract class FieldInflater { + protected Field field; + protected Cursor cursor; + protected Object object; + protected Class fieldType; + + public FieldInflater(Field field, Cursor cursor, Object object, Class fieldType) { + this.field = field; + this.cursor = cursor; + this.object = object; + this.fieldType = fieldType; + } + + public abstract void inflate(); +} diff --git a/library/src/main/java/com/orm/inflater/field/ListFieldInflater.java b/library/src/main/java/com/orm/inflater/field/ListFieldInflater.java new file mode 100644 index 00000000..5fa7496c --- /dev/null +++ b/library/src/main/java/com/orm/inflater/field/ListFieldInflater.java @@ -0,0 +1,38 @@ +package com.orm.inflater.field; + +import android.database.Cursor; +import android.util.Log; +import com.orm.SugarRecord; +import com.orm.annotation.OneToMany; + +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; + +/** + * Created by Łukasz Wesołowski on 03.08.2016. + */ +public class ListFieldInflater extends FieldInflater { + private static final String LOG_TAG = "ListFieldInflater"; + + public ListFieldInflater(Field field, Cursor cursor, Object object, Class fieldType) { + super(field, cursor, object, fieldType); + } + + @Override + public void inflate() { + if (field.isAnnotationPresent(OneToMany.class)) { + try { + Long objectId = cursor.getLong(cursor.getColumnIndex(("ID"))); + + ParameterizedType genericListType = (ParameterizedType) field.getGenericType(); + Class genericListClass = (Class) genericListType.getActualTypeArguments()[0]; + String targetName = field.getAnnotation(OneToMany.class).targetField(); + field.set(object, SugarRecord.findOneToMany(genericListClass, targetName, object, objectId)); + } catch (IllegalAccessException e) { + Log.e(LOG_TAG, String.format("Error while inflating list field %s", field), e); + } + } else { + Log.w(LOG_TAG, String.format("List field %s has not OneToMany annotation", field)); + } + } +} diff --git a/library/src/main/java/com/orm/inflater/field/RelationEntityFieldInflater.java b/library/src/main/java/com/orm/inflater/field/RelationEntityFieldInflater.java new file mode 100644 index 00000000..72df20f7 --- /dev/null +++ b/library/src/main/java/com/orm/inflater/field/RelationEntityFieldInflater.java @@ -0,0 +1,29 @@ +package com.orm.inflater.field; + +import android.database.Cursor; +import android.util.Log; + +import java.lang.reflect.Field; + +/** + * Created by Łukasz Wesołowski on 03.08.2016. + */ +public class RelationEntityFieldInflater extends EntityFieldInflater { + private static final String LOG_TAG = "RelEntityFieldInflater"; + + protected Object relationObject; + + public RelationEntityFieldInflater(Field field, Cursor cursor, Object object, Class fieldType, Object relationObject) { + super(field, cursor, object, fieldType); + this.relationObject = relationObject; + } + + @Override + public void inflate() { + try { + field.set(object, relationObject); + } catch (IllegalAccessException e) { + Log.e(LOG_TAG, String.format("Error while inflating %s field", field), e); + } + } +} diff --git a/library/src/main/java/com/orm/query/Select.java b/library/src/main/java/com/orm/query/Select.java index cadea7b3..cc57199d 100644 --- a/library/src/main/java/com/orm/query/Select.java +++ b/library/src/main/java/com/orm/query/Select.java @@ -3,29 +3,39 @@ import android.database.Cursor; import com.orm.SugarRecord; -import com.orm.util.NamingHelper; +import com.orm.helper.NamingHelper; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Select implements Iterable { + private static final String SPACE = " "; + private static final String SINGLE_QUOTE = "'"; + private static final String LEFT_PARENTHESIS = "("; + private static final String RIGHT_PARENTHESIS = ")"; + private static final String SELECT_FROM = "SELECT * FROM "; + private static final String WHERE = "WHERE "; + private static final String ORDER_BY = "ORDER BY "; + private static final String GROUP_BY = "GROUP BY "; + private static final String LIMIT = "LIMIT "; + private static final String OFFSET = "OFFSET "; private Class record; private String[] arguments; private String whereClause = ""; - private String orderBy; - private String groupBy; - private String limit; - private String offset; - private List args = new ArrayList(); + private String orderBy = ""; + private String groupBy = ""; + private String limit = ""; + private String offset = ""; + private List args = new ArrayList<>(); public Select(Class record) { this.record = record; } public static Select from(Class record) { - return new Select(record); + return new Select<>(record); } public Select orderBy(String prop) { @@ -43,6 +53,11 @@ public Select limit(String limit) { return this; } + public Select offset(String offset) { + this.offset = offset; + return this; + } + public Select where(String whereClause) { this.whereClause = whereClause; return this; @@ -56,10 +71,10 @@ public Select where(Condition... condition) { } private void mergeConditions(Condition[] conditions, Condition.Type type) { - StringBuilder toAppend = new StringBuilder(""); + StringBuilder toAppend = new StringBuilder(); for (Condition condition : conditions) { if (toAppend.length() != 0) { - toAppend.append(" ").append(type.name()).append(" "); + toAppend.append(SPACE).append(type.name()).append(SPACE); } if (Condition.Check.LIKE.equals(condition.getCheck()) || @@ -67,9 +82,9 @@ private void mergeConditions(Condition[] conditions, Condition.Type type) { toAppend .append(condition.getProperty()) .append(condition.getCheckSymbol()) - .append("'") + .append(SINGLE_QUOTE) .append(condition.getValue().toString()) - .append("'"); + .append(SINGLE_QUOTE); } else if (Condition.Check.IS_NULL.equals(condition.getCheck()) || Condition.Check.IS_NOT_NULL.equals(condition.getCheck())) { toAppend @@ -80,15 +95,15 @@ private void mergeConditions(Condition[] conditions, Condition.Type type) { .append(condition.getProperty()) .append(condition.getCheckSymbol()) .append("? "); - args.add(condition.getValue()); + args.add(condition.getValue().toString()); } } - if (!"".equals(whereClause)) { - whereClause += " " + type.name() + " "; + if (!whereClause.isEmpty()) { + whereClause += SPACE + type.name() + SPACE; } - whereClause += "(" + toAppend + ")"; + whereClause += LEFT_PARENTHESIS + toAppend + RIGHT_PARENTHESIS; } public Select whereOr(Condition... args) { @@ -142,22 +157,26 @@ public T first() { String toSql() { StringBuilder sql = new StringBuilder(); - sql.append("SELECT * FROM ").append(NamingHelper.toSQLName(this.record)).append(" "); + sql.append(SELECT_FROM).append(NamingHelper.toTableName(this.record)).append(SPACE); + + if (!whereClause.isEmpty()) { + sql.append(WHERE).append(whereClause).append(SPACE); + } - if (whereClause != null) { - sql.append("WHERE ").append(whereClause).append(" "); + if (!orderBy.isEmpty()) { + sql.append(ORDER_BY).append(orderBy).append(SPACE); } - if (orderBy != null) { - sql.append("ORDER BY ").append(orderBy).append(" "); + if (!groupBy.isEmpty()) { + sql.append(GROUP_BY).append(groupBy).append(SPACE); } - if (limit != null) { - sql.append("LIMIT ").append(limit).append(" "); + if (!limit.isEmpty()) { + sql.append(LIMIT).append(limit).append(SPACE); } - if (offset != null) { - sql.append("OFFSET ").append(offset).append(" "); + if (!offset.isEmpty()) { + sql.append(OFFSET).append(offset).append(SPACE); } return sql.toString(); @@ -171,14 +190,8 @@ String[] getArgs() { return convertArgs(args); } - private String[] convertArgs(List argsList) { - String[] argsArray = new String[argsList.size()]; - - for (int i = 0; i < argsList.size(); i++) { - argsArray[i] = argsList.get(i).toString(); - } - - return argsArray; + private String[] convertArgs(List argsList) { + return argsList.toArray(new String[argsList.size()]); } @Override diff --git a/library/src/main/java/com/orm/util/Collection.java b/library/src/main/java/com/orm/util/Collection.java deleted file mode 100644 index fe7a7e63..00000000 --- a/library/src/main/java/com/orm/util/Collection.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.orm.util; -import java.util.*; - -public class Collection { - - public static List list(T... args) { - return Arrays.asList(args); - } - - public static Set set(T... args) { - Set result = new HashSet(args.length); - result.addAll(Arrays.asList(args)); - return result; - } - - public static Map map(Entry... entries) { - Map result = new HashMap(entries.length); - - for (Entry entry : entries) - if (entry.value != null) - result.put(entry.key, entry.value); - - return result; - } - - public static Entry entry(K key, V value) { - return new Entry(key, value); - } - - public static class Entry { - K key; - V value; - - public Entry(K key, V value) { - this.key = key; - this.value = value; - } - } - -} diff --git a/library/src/main/java/com/orm/util/ContextUtil.java b/library/src/main/java/com/orm/util/ContextUtil.java new file mode 100644 index 00000000..3e6eff58 --- /dev/null +++ b/library/src/main/java/com/orm/util/ContextUtil.java @@ -0,0 +1,48 @@ +package com.orm.util; + +import android.content.Context; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.content.res.AssetManager; + +/** + * @author jonatan.salas + */ +public final class ContextUtil { + private static Context ctx; + + //Prevent instantiation + private ContextUtil() { } + + public static void init(Context context) { + if (null == context) { + throw new IllegalArgumentException("context shouldn't be null!"); + } + + ctx = context; + } + + public static void terminate() { + ctx = null; + } + + public static Context getContext() { + return ctx; + } + + public static AssetManager getAssets() { + return getContext().getAssets(); + } + + public static PackageManager getPackageManager() { + return getContext().getPackageManager(); + } + + public static String getPackageName() { + return getContext().getPackageName(); + } + + public static SharedPreferences getSharedPreferences(String name, int mode) { + return getContext().getSharedPreferences(name, mode); + } +} diff --git a/library/src/main/java/com/orm/util/KeyWordUtil.java b/library/src/main/java/com/orm/util/KeyWordUtil.java new file mode 100644 index 00000000..8983e7cf --- /dev/null +++ b/library/src/main/java/com/orm/util/KeyWordUtil.java @@ -0,0 +1,41 @@ +package com.orm.util; + +/** + * @author jonatan.salas + */ +public final class KeyWordUtil { + + private static final String[] KEY_WORDS = new String[] { + "", "ABORT", "ACTION", "ADD", "AFTER", "ALTER", "ANALYZE", "AND", "AS", "ASC", "ATTACH", + "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY", "CASCADE", "CASE", "CAST", "CHECK", + "COLLATE", "COLUMN", "COMMIT", "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE", + "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DELETE", + "DESC", "DETACH", "DISTINCT", "DROP", "EACH", "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", + "EXISTS", "EXPLAIN", "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", + "IF", "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER", "INSERT", "INSTEAD", + "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY", "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", + "NO", "NOT", "NOTNULL", "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA", + "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP", "REINDEX", "RELEASE", "RENAME", + "REPLACE", "RESTRICT", "RIGHT", "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP", + "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE", "UPDATE", "USING", "VACUUM", + "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE", "WITH", "WITHOUT" + }; + + //Prevent instantiation + private KeyWordUtil() { } + + public static boolean isKeyword(String word) { + if (null == word) { + return false; + } + + for (String keyWord: KEY_WORDS) { + if (keyWord.equals(word)) { + return true; + } + } + + return false; + } +} + diff --git a/library/src/main/java/com/orm/util/MigrationFileParser.java b/library/src/main/java/com/orm/util/MigrationFileParser.java new file mode 100644 index 00000000..1691a1eb --- /dev/null +++ b/library/src/main/java/com/orm/util/MigrationFileParser.java @@ -0,0 +1,21 @@ +package com.orm.util; + +/** + * Created by Nursultan Turdaliev on 12/4/15. + */ +public class MigrationFileParser { + + private String content; + + /** + * @param content + */ + public MigrationFileParser(String content){ + this.content = content.replaceAll("(\\/\\*([\\s\\S]*?)\\*\\/)|(--(.)*)|(\n)",""); + } + + public String[] getStatements(){ + return this.content.split(";"); + } + +} diff --git a/library/src/main/java/com/orm/util/NumberComparator.java b/library/src/main/java/com/orm/util/NumberComparator.java index b39ca9c9..a6a08053 100644 --- a/library/src/main/java/com/orm/util/NumberComparator.java +++ b/library/src/main/java/com/orm/util/NumberComparator.java @@ -2,9 +2,12 @@ import java.util.Comparator; +import static java.lang.Character.isDigit; +import static java.lang.Character.isSpaceChar; + public class NumberComparator implements Comparator { - private static char charAt(String s, int i) { + protected static char charAt(String s, int i) { if (i >= s.length()) { return '\000'; } @@ -12,7 +15,7 @@ private static char charAt(String s, int i) { return s.charAt(i); } - private int compareRight(String a, String b) { + protected int compareRight(String a, String b) { int bias = 0; int ia = 0; int ib = 0; @@ -20,13 +23,13 @@ private int compareRight(String a, String b) { char ca = charAt(a, ia); char cb = charAt(b, ib); - if ((!Character.isDigit(ca)) && (!Character.isDigit(cb))) { + if ((!isDigit(ca)) && (!isDigit(cb))) { return bias; } - if (!Character.isDigit(ca)) { + if (!isDigit(ca)) { return -1; } - if (!Character.isDigit(cb)) { + if (!isDigit(cb)) { return 1; } if (ca < cb) { @@ -49,15 +52,15 @@ public int compare(Object o1, Object o2) { int ia = 0; int ib = 0; - int nza = 0; - int nzb = 0; + int nza; + int nzb; while (true) { nza = nzb = 0; char ca = charAt(a, ia); char cb = charAt(b, ib); - while ((Character.isSpaceChar(ca)) || (ca == '0')) { + while ((isSpaceChar(ca)) || (ca == '0')) { if (ca == '0') { nza++; } else { @@ -67,7 +70,7 @@ public int compare(Object o1, Object o2) { ca = charAt(a, ++ia); } - while ((Character.isSpaceChar(cb)) || (cb == '0')) { + while ((isSpaceChar(cb)) || (cb == '0')) { if (cb == '0') { nzb++; } else { @@ -77,7 +80,7 @@ public int compare(Object o1, Object o2) { cb = charAt(b, ++ib); } int result; - if ((Character.isDigit(ca)) && (Character.isDigit(cb)) && + if ((isDigit(ca)) && (isDigit(cb)) && ((result = compareRight(a.substring(ia), b.substring(ib))) != 0)) { return result; } diff --git a/library/src/main/java/com/orm/util/ReflectionUtil.java b/library/src/main/java/com/orm/util/ReflectionUtil.java index d8492222..18943d09 100644 --- a/library/src/main/java/com/orm/util/ReflectionUtil.java +++ b/library/src/main/java/com/orm/util/ReflectionUtil.java @@ -1,14 +1,16 @@ package com.orm.util; import android.content.ContentValues; -import android.content.Context; import android.content.pm.PackageManager; import android.database.Cursor; import android.util.Log; import com.orm.SugarRecord; -import com.orm.dsl.Ignore; -import com.orm.dsl.Table; +import com.orm.annotation.Ignore; +import com.orm.annotation.Table; +import com.orm.helper.ManifestHelper; +import com.orm.helper.MultiDexHelper; +import com.orm.helper.NamingHelper; import java.io.File; import java.io.IOException; @@ -17,7 +19,6 @@ import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.net.URL; -import java.sql.Ref; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; @@ -27,22 +28,23 @@ import java.util.List; import java.util.Map; -import dalvik.system.DexFile; +public final class ReflectionUtil { -public class ReflectionUtil { - - private static final String TAG = ReflectionUtil.class.getSimpleName(); + //Prevent instantiation.. + private ReflectionUtil() { } public static List getTableFields(Class table) { List fieldList = SugarConfig.getFields(table); if (fieldList != null) return fieldList; - Log.d("Sugar", "Fetching properties"); - List typeFields = new ArrayList(); + if (ManifestHelper.isDebugEnabled()) { + Log.d("Sugar", "Fetching properties"); + } + List typeFields = new ArrayList<>(); getAllFields(typeFields, table); - List toStore = new ArrayList(); + List toStore = new ArrayList<>(); for (Field field : typeFields) { if (!field.isAnnotationPresent(Ignore.class) && !Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) { toStore.add(field); @@ -68,17 +70,19 @@ public static void addFieldValueToColumn(ContentValues values, Field column, Obj column.setAccessible(true); Class columnType = column.getType(); try { - String columnName = NamingHelper.toSQLName(column); + String columnName = NamingHelper.toColumnName(column); Object columnValue = column.get(object); if (columnType.isAnnotationPresent(Table.class)) { - Field field = null; + Field field; try { field = columnType.getDeclaredField("id"); field.setAccessible(true); - values.put(columnName, - (field != null) - ? String.valueOf(field.get(columnValue)) : "0"); + if(columnValue != null) { + values.put(columnName,String.valueOf(field.get(columnValue))); + } else { + values.putNull(columnName); + } } catch (NoSuchFieldException e) { if (entitiesMap.containsKey(columnValue)) { values.put(columnName, entitiesMap.get(columnValue)); @@ -132,6 +136,8 @@ public static void addFieldValueToColumn(ContentValues values, Field column, Obj } else { values.put(columnName, (byte[]) columnValue); } + } else if (columnType.equals(List.class)) { + //ignore } else { if (columnValue == null) { values.putNull(columnName); @@ -144,7 +150,9 @@ public static void addFieldValueToColumn(ContentValues values, Field column, Obj } } catch (IllegalAccessException e) { - Log.e("Sugar", e.getMessage()); + if (ManifestHelper.isDebugEnabled()) { + Log.e("Sugar", e.getMessage()); + } } } @@ -152,17 +160,25 @@ public static void setFieldValueFromCursor(Cursor cursor, Field field, Object ob field.setAccessible(true); try { Class fieldType = field.getType(); - String colName = NamingHelper.toSQLName(field); + String colName = NamingHelper.toColumnName(field); int columnIndex = cursor.getColumnIndex(colName); + //TODO auto upgrade to add new columns + if (columnIndex < 0) { + if (ManifestHelper.isDebugEnabled()) { + Log.e("SUGAR", "Invalid colName, you should upgrade database"); + } + return; + } + if (cursor.isNull(columnIndex)) { return; } if (colName.equalsIgnoreCase("id")) { long cid = cursor.getLong(columnIndex); - field.set(object, Long.valueOf(cid)); + field.set(object, cid); } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) { field.set(object, cursor.getLong(columnIndex)); @@ -212,26 +228,29 @@ public static void setFieldValueFromCursor(Cursor cursor, Field field, Object ob Object enumVal = valueOf.invoke(field.getType(), strVal); field.set(object, enumVal); } catch (Exception e) { - Log.e("Sugar", "Enum cannot be read from Sqlite3 database. Please check the type of field " + field.getName()); + if (ManifestHelper.isDebugEnabled()) { + Log.e("Sugar", "Enum cannot be read from Sqlite3 database. Please check the type of field " + field.getName()); + } } - } else - Log.e("Sugar", "Class cannot be read from Sqlite3 database. Please check the type of field " + field.getName() + "(" + field.getType().getName() + ")"); - } catch (IllegalArgumentException e) { - Log.e("field set error", e.getMessage()); - } catch (IllegalAccessException e) { - Log.e("field set error", e.getMessage()); + } else { + if (ManifestHelper.isDebugEnabled()) { + Log.e("Sugar", "Class cannot be read from Sqlite3 database. Please check the type of field " + field.getName() + "(" + field.getType().getName() + ")"); + } + } + } catch (IllegalArgumentException | IllegalAccessException e) { + if (ManifestHelper.isDebugEnabled()) { + Log.e("field set error", e.getMessage()); + } } } private static Field getDeepField(String fieldName, Class type) throws NoSuchFieldException { try { - Field field = type.getDeclaredField(fieldName); - return field; + return type.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { Class superclass = type.getSuperclass(); if (superclass != null) { - Field field = getDeepField(fieldName, superclass); - return field; + return getDeepField(fieldName, superclass); } else { throw e; } @@ -243,37 +262,37 @@ public static void setFieldValueForId(Object object, Long value) { Field field = getDeepField("id", object.getClass()); field.setAccessible(true); field.set(object, value); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (NoSuchFieldException e) { + } catch (Exception e) { e.printStackTrace(); } } - public static List getDomainClasses(Context context) { - List domainClasses = new ArrayList(); + public static List getDomainClasses() { + List domainClasses = new ArrayList<>(); try { - for (String className : getAllClasses(context)) { - Log.d(TAG, className); - Class domainClass = getDomainClass(className, context); + for (String className : getAllClasses()) { + Class domainClass = getDomainClass(className); if (domainClass != null) domainClasses.add(domainClass); } - } catch (IOException e) { - Log.e("Sugar", e.getMessage()); - } catch (PackageManager.NameNotFoundException e) { - Log.e("Sugar", e.getMessage()); + } catch (IOException | PackageManager.NameNotFoundException e) { + if (ManifestHelper.isDebugEnabled()) { + Log.e("Sugar", e.getMessage()); + } } return domainClasses; } - private static Class getDomainClass(String className, Context context) { + private static Class getDomainClass(String className) { Class discoveredClass = null; try { - discoveredClass = Class.forName(className, true, context.getClass().getClassLoader()); - } catch (ClassNotFoundException e) { - Log.e("Sugar", e.getMessage()); + discoveredClass = Class.forName(className, true, Thread.currentThread().getContextClassLoader()); + } catch (Throwable e) { + String error = (e.getMessage() == null) ? "getDomainClass " + className + " error" : e.getMessage(); + if (ManifestHelper.isDebugEnabled()) { + Log.e("Sugar", error); + } } if ((discoveredClass != null) && @@ -282,7 +301,9 @@ private static Class getDomainClass(String className, Context context) { discoveredClass.isAnnotationPresent(Table.class)) && !Modifier.isAbstract(discoveredClass.getModifiers())) { - Log.i("Sugar", "domain class : " + discoveredClass.getSimpleName()); + if (ManifestHelper.isDebugEnabled()) { + Log.i("Sugar", "domain class : " + discoveredClass.getSimpleName()); + } return discoveredClass; } else { @@ -291,11 +312,11 @@ private static Class getDomainClass(String className, Context context) { } - private static List getAllClasses(Context context) throws PackageManager.NameNotFoundException, IOException { - String packageName = ManifestHelper.getDomainPackageName(context); - List classNames = new ArrayList(); + private static List getAllClasses() throws PackageManager.NameNotFoundException, IOException { + String packageName = ManifestHelper.getDomainPackageName(); + List classNames = new ArrayList<>(); try { - List allClasses = MultiDexHelper.getAllClasses(context); + List allClasses = MultiDexHelper.getAllClasses(); for (String classString : allClasses) { if (classString.startsWith(packageName)) classNames.add(classString); } @@ -303,9 +324,10 @@ private static List getAllClasses(Context context) throws PackageManager ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration urls = classLoader.getResources(""); while (urls.hasMoreElements()) { - List fileNames = new ArrayList(); + List fileNames = new ArrayList<>(); String classDirectoryName = urls.nextElement().getFile(); - if (classDirectoryName.contains("bin") || classDirectoryName.contains("classes")) { + if (classDirectoryName.contains("bin") || classDirectoryName.contains("classes") + || classDirectoryName.contains("retrolambda")) { File classDirectory = new File(classDirectoryName); for (File filePath : classDirectory.listFiles()) { populateFiles(filePath, fileNames, ""); @@ -315,9 +337,11 @@ private static List getAllClasses(Context context) throws PackageManager } } } - } finally { -// if (null != dexfile) dexfile.close(); } +// } finally { +// if (null != dexfile) dexfile.close(); +// } + return classNames; } @@ -343,7 +367,7 @@ private static void populateFiles(File path, List fileNames, String pare } } - private static String getSourcePath(Context context) throws PackageManager.NameNotFoundException { - return context.getPackageManager().getApplicationInfo(context.getPackageName(), 0).sourceDir; + private static String getSourcePath() throws PackageManager.NameNotFoundException { + return ContextUtil.getPackageManager().getApplicationInfo(ContextUtil.getPackageName(), 0).sourceDir; } } diff --git a/library/src/main/java/com/orm/util/SugarConfig.java b/library/src/main/java/com/orm/util/SugarConfig.java index b93da25e..46ebd8da 100644 --- a/library/src/main/java/com/orm/util/SugarConfig.java +++ b/library/src/main/java/com/orm/util/SugarConfig.java @@ -1,20 +1,14 @@ package com.orm.util; -import android.content.Context; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.util.Log; - import java.lang.reflect.Field; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - public class SugarConfig { - static Map, List> fields = new HashMap, List>(); + static Map, List> fields = new HashMap<>(); public static void setFields(Class clazz, List fieldz) { fields.put(clazz, fieldz); @@ -31,7 +25,6 @@ public static List getFields(Class clazz) { public static void clearCache() { fields.clear(); - fields = new HashMap, List>(); + fields = new HashMap<>(); } - } diff --git a/library/src/main/java/com/orm/util/SugarCursor.java b/library/src/main/java/com/orm/util/SugarCursor.java index e326f49b..d058c5c1 100644 --- a/library/src/main/java/com/orm/util/SugarCursor.java +++ b/library/src/main/java/com/orm/util/SugarCursor.java @@ -4,6 +4,7 @@ import android.database.CursorWrapper; public class SugarCursor extends CursorWrapper { + public SugarCursor(Cursor cursor) { super(cursor); } diff --git a/library/src/main/java/com/orm/util/SugarCursorFactory.java b/library/src/main/java/com/orm/util/SugarCursorFactory.java index 12706516..3274fccc 100644 --- a/library/src/main/java/com/orm/util/SugarCursorFactory.java +++ b/library/src/main/java/com/orm/util/SugarCursorFactory.java @@ -16,7 +16,6 @@ public SugarCursorFactory() { } public SugarCursorFactory(boolean debugEnabled) { - this.debugEnabled = debugEnabled; } diff --git a/library/src/main/java/com/orm/util/ThreadUtil.java b/library/src/main/java/com/orm/util/ThreadUtil.java new file mode 100644 index 00000000..665e5c2d --- /dev/null +++ b/library/src/main/java/com/orm/util/ThreadUtil.java @@ -0,0 +1,34 @@ +package com.orm.util; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +/** + * Util class to deal with threads. + * + * @author jonatan.salas + */ +public final class ThreadUtil { + + //Prevent instantiation.. + private ThreadUtil() { } + + /** + * Submits a Callable object and returns a Future ready to use. + * + * @param callable the callable you want to submit + * @return a Future object + */ + public static Future doInBackground(Callable callable) { + final ExecutorService executor = Executors.newSingleThreadExecutor(); + Future future = executor.submit(callable); + + if(executor.isTerminated()) { + executor.shutdown(); + } + + return future; + } +} diff --git a/library/src/test/java/com/orm/NamingHelperTest.java b/library/src/test/java/com/orm/NamingHelperTest.java deleted file mode 100644 index 3166a107..00000000 --- a/library/src/test/java/com/orm/NamingHelperTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.orm; - -import com.orm.util.NamingHelper; - -import org.junit.Test; - -import static junit.framework.Assert.assertEquals; - -public class NamingHelperTest { - @Test - public void testToSQLNameCaseConversion() throws Exception { - assertToSqlNameEquals("TESTLOWERCASE", "testlowercase"); - assertToSqlNameEquals("TESTUPPERCASE", "TESTUPPERCASE"); - } - - @Test - public void testToSQLNameUnderscore() { - assertToSqlNameEquals("TEST_UNDERSCORE", "testUnderscore"); - assertToSqlNameEquals("AB_CD", "AbCd"); - assertToSqlNameEquals("AB_CD", "ABCd"); - assertToSqlNameEquals("AB_CD", "AbCD"); - assertToSqlNameEquals("SOME_DETAILS_OBJECT", "SomeDetailsObject"); - assertToSqlNameEquals("H_OL_A","hOlA"); - assertToSqlNameEquals("A","a"); - } - - /** - * Helper method that asserts a CamelCaseString is converted to UPPER_CASE_UNDER_SCORE. - * - * @param expected a CamelCaseString - * @param actual the expected UPPER_CASE_UNDER_SCORE string - */ - private static void assertToSqlNameEquals(String expected, String actual) { - assertEquals(expected, NamingHelper.toSQLNameDefault(actual)); - } - -} diff --git a/library/src/test/java/com/orm/SchemaGeneratorTest.java b/library/src/test/java/com/orm/SchemaGeneratorTest.java new file mode 100644 index 00000000..811d1aa1 --- /dev/null +++ b/library/src/test/java/com/orm/SchemaGeneratorTest.java @@ -0,0 +1,179 @@ +package com.orm; + +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.AllAnotatedModel; +import com.orm.model.EmptyModel; +import com.orm.model.IntUniqueModel; +import com.orm.model.MultiColumnUniqueModel; +import com.orm.model.StringFieldAnnotatedModel; +import com.orm.model.StringFieldExtendedModel; +import com.orm.model.StringFieldExtendedModelAnnotatedColumn; +import com.orm.helper.NamingHelper; +import com.orm.model.TestRecord; + +import junit.framework.Assert; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.util.List; + +import static junit.framework.Assert.assertEquals; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class SchemaGeneratorTest { + + @Test + public void testEmptyTableCreation() throws Exception { + SchemaGenerator schemaGenerator = SchemaGenerator.getInstance(); + String createSQL = schemaGenerator.createTableSQL(EmptyModel.class); + assertEquals( + "CREATE TABLE IF NOT EXISTS " + NamingHelper.toTableName(EmptyModel.class) + + " ( ID INTEGER PRIMARY KEY AUTOINCREMENT ) ", + createSQL); + } + + @Test + public void testSimpleColumnTableCreation() throws Exception { + SchemaGenerator schemaGenerator = SchemaGenerator.getInstance(); + String createSQL = schemaGenerator.createTableSQL(StringFieldExtendedModel.class); + assertEquals( + "CREATE TABLE IF NOT EXISTS " + NamingHelper.toTableName(StringFieldExtendedModel.class) + + " ( ID INTEGER PRIMARY KEY AUTOINCREMENT , " + + "STRING TEXT ) ", + createSQL); + + String createSQL2 = schemaGenerator.createTableSQL(StringFieldAnnotatedModel.class); + + assertEquals("CREATE TABLE IF NOT EXISTS " + NamingHelper.toTableName(StringFieldAnnotatedModel.class) + + " ( ID INTEGER PRIMARY KEY AUTOINCREMENT , " + + "STRING TEXT ) ", + createSQL2); + + String createSQL3 = schemaGenerator.createTableSQL(StringFieldExtendedModelAnnotatedColumn.class); + + assertEquals("CREATE TABLE IF NOT EXISTS " + NamingHelper.toTableName(StringFieldExtendedModelAnnotatedColumn.class) + + " ( ID INTEGER PRIMARY KEY AUTOINCREMENT , " + + "anyName TEXT ) ", + createSQL3); + } + + @Test + public void testUniqueTableCreation() { + SchemaGenerator schemaGenerator = SchemaGenerator.getInstance(); + String createSQL = schemaGenerator.createTableSQL(IntUniqueModel.class); + assertEquals( + "CREATE TABLE IF NOT EXISTS " + NamingHelper.toTableName(IntUniqueModel.class) + + " ( ID INTEGER PRIMARY KEY AUTOINCREMENT , " + + "VALUE INTEGER UNIQUE ) ", + createSQL); + } + + @Test + public void testMultiColumnUniqueTableCreation() { + SchemaGenerator schemaGenerator = SchemaGenerator.getInstance(); + String createSQL = schemaGenerator.createTableSQL(MultiColumnUniqueModel.class); + assertEquals( + "CREATE TABLE IF NOT EXISTS " + NamingHelper.toTableName(MultiColumnUniqueModel.class) + + " ( ID INTEGER PRIMARY KEY AUTOINCREMENT , " + + "A INTEGER, B INTEGER, " + + "UNIQUE(A, B) ON CONFLICT REPLACE ) ", + createSQL); + } + + @Test + public void testTableCreation() { + SQLiteDatabase sqLiteDatabase = SugarContext.getSugarContext().getSugarDb().getDB(); + SchemaGenerator schemaGenerator = SchemaGenerator.getInstance(); + schemaGenerator.createTable(TestRecord.class, sqLiteDatabase); + String sql = "select count(*) from sqlite_master where type='table' and name='%s';"; + + String tableName = NamingHelper.toTableName(TestRecord.class); + Cursor c = sqLiteDatabase.rawQuery(String.format(sql, tableName), null); + + if (c.moveToFirst()) { + Assert.assertEquals(1, c.getInt(0)); + } + + if (!c.isClosed()) { + c.close(); + } + } + + @Test + public void testAnnotatedModelTableCreation() { + SQLiteDatabase sqLiteDatabase = SugarContext.getSugarContext().getSugarDb().getDB(); + SchemaGenerator schemaGenerator = SchemaGenerator.getInstance(); + schemaGenerator.createTable(AllAnotatedModel.class, sqLiteDatabase); + String sql = "select count(*) from sqlite_master where type='table' and name='%s';"; + + String tableName = NamingHelper.toTableName(AllAnotatedModel.class); + Cursor c = sqLiteDatabase.rawQuery(String.format(sql, tableName), null); + + if (c.moveToFirst()) { + Assert.assertEquals(1, c.getInt(0)); + } + + if (!c.isClosed()) { + c.close(); + } + } + + @Test + public void testAllTableCreation() { + SQLiteDatabase sqLiteDatabase = SugarContext.getSugarContext().getSugarDb().getDB(); + SchemaGenerator schemaGenerator = SchemaGenerator.getInstance(); + + schemaGenerator.createDatabase(sqLiteDatabase); + String sql = "select count(*) from sqlite_master where type='table';"; + + Cursor c = sqLiteDatabase.rawQuery(sql, null); + + if (c.moveToFirst()) { + Assert.assertEquals(48, c.getInt(0)); + } + + if (!c.isClosed()) { + c.close(); + } + } + + @Test + public void testDeleteAllTables() { + SQLiteDatabase sqLiteDatabase = SugarContext.getSugarContext().getSugarDb().getDB(); + SchemaGenerator schemaGenerator = SchemaGenerator.getInstance(); + + schemaGenerator.createDatabase(sqLiteDatabase); + schemaGenerator.deleteTables(sqLiteDatabase); + + String sql = "select count(*) from sqlite_master where type='table';"; + + Cursor c = sqLiteDatabase.rawQuery(sql, null); + + if (c.moveToFirst()) { + //Two tables are by default created by SQLite + Assert.assertEquals(2, c.getInt(0)); + } + + if (!c.isClosed()) { + c.close(); + } + } + + @Test + public void testGetColumnNames() { + SQLiteDatabase sqLiteDatabase = SugarContext.getSugarContext().getSugarDb().getDB(); + SchemaGenerator schemaGenerator = SchemaGenerator.getInstance(); + schemaGenerator.createTable(TestRecord.class, sqLiteDatabase); + + List columnNames = schemaGenerator.getColumnNames(sqLiteDatabase, NamingHelper.toTableName(TestRecord.class)); + Assert.assertEquals(2, columnNames.size()); + } +} diff --git a/library/src/test/java/com/orm/SugarAppTest.java b/library/src/test/java/com/orm/SugarAppTest.java new file mode 100644 index 00000000..0f247ae8 --- /dev/null +++ b/library/src/test/java/com/orm/SugarAppTest.java @@ -0,0 +1,31 @@ +package com.orm; + +import junit.framework.Assert; + +import org.junit.Test; + +/** + * @author jonatan.salas + */ +public final class SugarAppTest { + + @Test + public void testOnCreate() { + SugarApp app = new SugarApp(); + app.onCreate(); + + SugarContext context = SugarContext.getSugarContext(); + Assert.assertNotNull(context); + } + + + @Test(expected = NullPointerException.class) + public void testOnTerminate() { + SugarApp app = new SugarApp(); + app.onCreate(); + app.onTerminate(); + + SugarContext context = SugarContext.getSugarContext(); + Assert.assertNull(context); + } +} diff --git a/library/src/test/java/com/orm/SugarDataSourceTest.java b/library/src/test/java/com/orm/SugarDataSourceTest.java new file mode 100644 index 00000000..9f3d25ba --- /dev/null +++ b/library/src/test/java/com/orm/SugarDataSourceTest.java @@ -0,0 +1,543 @@ +package com.orm; + +import android.database.Cursor; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.TestRecord; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.util.ArrayList; +import java.util.List; + +import static junit.framework.Assert.*; + +/** + * @author jonatan.salas + */ +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class SugarDataSourceTest { + private SugarDataSource recordSugarDataSource; + + @Before + public void setUp() { + recordSugarDataSource = SugarDataSource.getInstance(TestRecord.class); + } + + @Test + public void testInsertAndDelete() { + final TestRecord record = new TestRecord(); + record.setName("lalala"); + + recordSugarDataSource.insert( + record, + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Long id) { + record.setId(id); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + assertNotNull(record.getId()); + + recordSugarDataSource.delete( + record, + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Boolean result) { + assertNotNull(result); + assertEquals(true, result.booleanValue()); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + } + + @Test + public void testInsertAndFindById() { + final TestRecord record = new TestRecord(); + record.setName("lalala"); + + recordSugarDataSource.insert( + record, + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Long id) { + record.setId(id); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + recordSugarDataSource.findById( + record.getId(), + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(TestRecord result) { + assertEquals(record.getId(), result.getId()); + assertEquals(record.getName(), result.getName()); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + } + + @Test + public void testInsertUpdateAndFindById() { + final TestRecord record = new TestRecord(); + record.setName("lalala"); + + recordSugarDataSource.insert( + record, + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Long id) { + record.setId(id); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + record.setName("fulano"); + recordSugarDataSource.update( + record, + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Long id) { + assertEquals(record.getId(), id); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + recordSugarDataSource.findById( + record.getId(), + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(TestRecord result) { + assertEquals(record.getId(), result.getId()); + assertEquals("fulano", result.getName()); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + } + + @Test + public void testInsertAndListAll() { + final TestRecord record = new TestRecord(); + record.setName("lalala"); + + recordSugarDataSource.insert( + record, + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Long id) { + record.setId(id); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + final TestRecord record1 = new TestRecord(); + record1.setName("fulano"); + + recordSugarDataSource.insert( + record1, + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Long id) { + record1.setId(id); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + final TestRecord record2 = new TestRecord(); + record2.setName("mengano"); + + recordSugarDataSource.insert( + record2, + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Long id) { + record2.setId(id); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + recordSugarDataSource.listAll( + null, + new SugarDataSource.SuccessCallback>() { + @Override + public void onSuccess(List list) { + assertEquals(3, list.size()); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + recordSugarDataSource.deleteAll( + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Integer count) { + assertEquals(3, count.intValue()); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + } + + @Test + public void testInsertAndCount() { + final TestRecord record = new TestRecord(); + record.setName("lalala"); + + recordSugarDataSource.insert( + record, + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Long id) { + record.setId(id); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + final TestRecord record1 = new TestRecord(); + record1.setName("fulano"); + + recordSugarDataSource.insert( + record1, + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Long id) { + record1.setId(id); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + + final TestRecord record2 = new TestRecord(); + record2.setName("mengano"); + + recordSugarDataSource.insert( + record2, + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Long id) { + record2.setId(id); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + recordSugarDataSource.count( + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Long count) { + assertEquals(3, count.longValue()); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + } + + @Test + public void testInsertAndGetCursor() { + final TestRecord record = new TestRecord(); + record.setName("lalala"); + + recordSugarDataSource.insert( + record, + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Long id) { + record.setId(id); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + final TestRecord record1 = new TestRecord(); + record1.setName("fulano"); + + recordSugarDataSource.insert( + record1, + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Long id) { + record1.setId(id); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + + final TestRecord record2 = new TestRecord(); + record2.setName("mengano"); + + recordSugarDataSource.insert( + record2, + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Long id) { + record2.setId(id); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + recordSugarDataSource.listAll( + null, + new SugarDataSource.SuccessCallback>() { + @Override + public void onSuccess(List list) { + assertEquals(3, list.size()); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + recordSugarDataSource.query( + null, + null, + null, + null, + null, + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(Cursor cursor) { + assertNotNull(cursor); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + } + + @Test + public void bulkInsertAndListAllTest() { + final TestRecord record = new TestRecord(); + record.setName("lalala"); + + final TestRecord record1 = new TestRecord(); + record1.setName("fulano"); + + final TestRecord record2 = new TestRecord(); + record2.setName("mengano"); + + final List list = new ArrayList<>(); + list.add(record); + list.add(record1); + list.add(record2); + + recordSugarDataSource.bulkInsert( + list, + new SugarDataSource.SuccessCallback>() { + @Override + public void onSuccess(List ids) { + for (int i = 0; i < list.size(); i++) { + list.get(i).setId(ids.get(i)); + } + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + + recordSugarDataSource.listAll( + null, + new SugarDataSource.SuccessCallback>() { + @Override + public void onSuccess(List testRecords) { + for (int i = 0; i < list.size(); i++) { + TestRecord record1 = list.get(i); + TestRecord record2 = testRecords.get(i); + + assertEquals(record1.getId(), record2.getId()); + assertEquals(record1.getName(), record2.getName()); + } + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + e.printStackTrace(); + } + } + ); + } + + @Test + public void nullFindById() { + TestRecord record = new TestRecord(); + record.setId(0L); + + recordSugarDataSource.findById( + record.getId(), + new SugarDataSource.SuccessCallback() { + @Override + public void onSuccess(TestRecord object) { + assertNull(object); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + assertNotNull(e.getMessage()); + } + } + ); + } + + @Test + public void testNullListAll() { + recordSugarDataSource.listAll( + null, + new SugarDataSource.SuccessCallback>() { + @Override + public void onSuccess(List object) { + assertNull(object); + } + }, + new SugarDataSource.ErrorCallback() { + @Override + public void onError(Exception e) { + assertNotNull(e.getMessage()); + } + } + ); + } + + @Test(expected = IllegalArgumentException.class) + @SuppressWarnings("all") + public void testNullConstructor() { + SugarDataSource dataSource = SugarDataSource.getInstance(null); + } + + @Test(expected = IllegalArgumentException.class) + @SuppressWarnings("all") + public void testCheckNotNull() { + TestRecord record = null; + recordSugarDataSource.checkNotNull(record); + } +} diff --git a/library/src/test/java/com/orm/SugarDbConfigurationTest.java b/library/src/test/java/com/orm/SugarDbConfigurationTest.java new file mode 100644 index 00000000..64d50df6 --- /dev/null +++ b/library/src/test/java/com/orm/SugarDbConfigurationTest.java @@ -0,0 +1,64 @@ +package com.orm; + +import com.orm.dsl.BuildConfig; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.RuntimeEnvironment; +import org.robolectric.annotation.Config; + +import java.util.Locale; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +/** + * @author jonatan.salas + */ +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 16, constants = BuildConfig.class) +public final class SugarDbConfigurationTest { + + @Test + public void testNotNullConfiguration() { + SugarDbConfiguration configuration = new SugarDbConfiguration() + .setDatabaseLocale(Locale.getDefault()) + .setMaxSize(1024L) + .setPageSize(400L); + + SugarContext.init(RuntimeEnvironment.application, configuration); + + final SugarDbConfiguration config = SugarContext.getDbConfiguration(); + + assertEquals(configuration.getDatabaseLocale(), config.getDatabaseLocale()); + assertEquals(configuration.getMaxSize(), config.getMaxSize()); + assertEquals(configuration.getPageSize(), config.getPageSize()); + } + + @Test + public void testNullConfiguration() { + SugarContext.init(RuntimeEnvironment.application); + assertNull(SugarContext.getDbConfiguration()); + } + +// @Test +// public void testNotNullConfigurationWithSugarDb() { +// SugarDbConfiguration configuration = new SugarDbConfiguration() +// .setDatabaseLocale(Locale.getDefault()) +// .setMaxSize(100000L) +// .setPageSize(100000L); +// +// SugarContext.init(RuntimeEnvironment.application, configuration); +// +// SQLiteDatabase database = SugarContext.getSugarContext().getSugarDb().getDB(); +// SQLiteDatabase sqLiteDatabase = SugarDb.getInstance().getDB(); +// +// assertEquals(database.getMaximumSize(), sqLiteDatabase.getMaximumSize()); +// assertEquals(database.getPageSize(), sqLiteDatabase.getPageSize()); +// +// if (sqLiteDatabase.isOpen()) { +// sqLiteDatabase.close(); +// } +// } +} diff --git a/library/src/test/java/com/orm/SugarDbTest.java b/library/src/test/java/com/orm/SugarDbTest.java new file mode 100644 index 00000000..7ff5914a --- /dev/null +++ b/library/src/test/java/com/orm/SugarDbTest.java @@ -0,0 +1,41 @@ +package com.orm; + +import android.database.sqlite.SQLiteDatabase; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import static org.junit.Assert.assertEquals; + +/** + * @author jonatan.salas + */ +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class SugarDbTest { + private final SugarDb sugarDb = SugarDb.getInstance(); + + @Test + //TODO check this better! + public void testGetReadableDatabase() { + final SQLiteDatabase db = sugarDb.getReadableDatabase(); + assertEquals(false, db.isReadOnly()); + } + + @Test + public void testGetWritableDatabase() { + final SQLiteDatabase db = sugarDb.getWritableDatabase(); + assertEquals(false, db.isReadOnly()); + } + + @Test + public void testGetDB() { + final SQLiteDatabase db = sugarDb.getDB(); + assertEquals(false, db.isReadOnly()); + } +} diff --git a/example/src/main/java/com/example/ClientApp.java b/library/src/test/java/com/orm/app/ClientApp.java similarity index 93% rename from example/src/main/java/com/example/ClientApp.java rename to library/src/test/java/com/orm/app/ClientApp.java index e546e11d..e9943aea 100644 --- a/example/src/main/java/com/example/ClientApp.java +++ b/library/src/test/java/com/orm/app/ClientApp.java @@ -1,10 +1,11 @@ -package com.example; +package com.orm.app; import android.app.Application; import com.orm.SugarContext; public class ClientApp extends Application { + @Override public void onCreate() { super.onCreate(); diff --git a/library/src/test/java/com/orm/helper/ManifestHelperTest.java b/library/src/test/java/com/orm/helper/ManifestHelperTest.java new file mode 100644 index 00000000..2fad344c --- /dev/null +++ b/library/src/test/java/com/orm/helper/ManifestHelperTest.java @@ -0,0 +1,60 @@ +package com.orm.helper; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.util.KeyWordUtil; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import static junit.framework.Assert.assertNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import static com.orm.helper.ManifestHelper.getDatabaseName; +import static com.orm.helper.ManifestHelper.getDatabaseVersion; +import static com.orm.helper.ManifestHelper.getDomainPackageName; +import static com.orm.helper.ManifestHelper.isDebugEnabled; +import static com.orm.helper.ManifestHelper.DATABASE_DEFAULT_NAME; + +/** + * @author jonatan.salas + */ +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class ManifestHelperTest { + + @Test(expected = IllegalAccessException.class) + public void testPrivateConstructor() throws Exception { + ManifestHelper helper = ManifestHelper.class.getDeclaredConstructor().newInstance(); + assertNull(helper); + } + + + @Test + public void testGetDbName() { + assertEquals(DATABASE_DEFAULT_NAME, getDatabaseName()); + } + + @Test + public void testGetDatabaseName() { + assertEquals(DATABASE_DEFAULT_NAME, getDatabaseName()); + } + + @Test + public void testGetDatabaseVersion() { + assertEquals(1, getDatabaseVersion()); + } + + @Test + public void testGetDomainPackageName() { + assertNotNull(getDomainPackageName()); + } + + @Test + public void testGetDebugEnabled() { + assertEquals(false, isDebugEnabled()); + } +} diff --git a/library/src/test/java/com/orm/helper/NamingHelperTest.java b/library/src/test/java/com/orm/helper/NamingHelperTest.java new file mode 100644 index 00000000..d53769ad --- /dev/null +++ b/library/src/test/java/com/orm/helper/NamingHelperTest.java @@ -0,0 +1,90 @@ +package com.orm.helper; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.TestRecord; +import com.orm.util.ReflectionUtil; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +import static com.orm.helper.NamingHelper.*; +import static junit.framework.Assert.*; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class NamingHelperTest { + + @Test(expected = IllegalAccessException.class) + public void testPrivateConstructor() throws Exception { + NamingHelper helper = NamingHelper.class.getDeclaredConstructor().newInstance(); + assertNull(helper); + } + + @Test + public void testToSQLNameFromField() { + List fieldList = ReflectionUtil.getTableFields(TestRecord.class); + + if (null != fieldList && !fieldList.isEmpty()) { + List columnList = new ArrayList<>(); + + for(Field field: fieldList) { + columnList.add(toColumnName(field)); + } + + boolean isIdInList = inList(columnList, "ID"); + boolean isNameInList = inList(columnList, "NAME"); + + assertTrue(isIdInList); + assertTrue(isNameInList); + } + } + + private boolean inList(List list, String searchValue) { + for (String val: list) { + if (val.equals(searchValue)) { + return true; + } + } + + return false; + } + + @Test + public void testToSQLNameFromClass() { + assertEquals("TEST_RECORD", toTableName(TestRecord.class)); + } + + @Test + public void testToSQLNameCaseConversion() throws Exception { + assertToSqlNameEquals("TESTLOWERCASE", "testlowercase"); + assertToSqlNameEquals("TESTUPPERCASE", "TESTUPPERCASE"); + } + + @Test + public void testToSQLNameUnderscore() { + assertToSqlNameEquals("TEST_UNDERSCORE", "testUnderscore"); + assertToSqlNameEquals("AB_CD", "AbCd"); + assertToSqlNameEquals("AB_CD", "ABCd"); + assertToSqlNameEquals("AB_CD", "AbCD"); + assertToSqlNameEquals("SOME_DETAILS_OBJECT", "SomeDetailsObject"); + assertToSqlNameEquals("H_OL_A","hOlA"); + assertToSqlNameEquals("A","a"); + } + + /** + * Helper method that asserts a CamelCaseString is converted to UPPER_CASE_UNDER_SCORE. + * + * @param expected a CamelCaseString + * @param actual the expected UPPER_CASE_UNDER_SCORE string + */ + private static void assertToSqlNameEquals(String expected, String actual) { + assertEquals(expected, toSQLNameDefault(actual)); + } + +} diff --git a/library/src/test/java/com/orm/helper/SugarTransactionHelperTest.java b/library/src/test/java/com/orm/helper/SugarTransactionHelperTest.java new file mode 100644 index 00000000..1fe73708 --- /dev/null +++ b/library/src/test/java/com/orm/helper/SugarTransactionHelperTest.java @@ -0,0 +1,84 @@ +package com.orm.helper; + +import com.orm.app.ClientApp; +import com.orm.SugarContext; +import com.orm.dsl.BuildConfig; +import com.orm.helper.SugarTransactionHelper; +import com.orm.model.TestRecord; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.RuntimeEnvironment; +import org.robolectric.annotation.Config; + +import java.util.ArrayList; +import java.util.List; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertNull; + +/** + * @author jonatan.salas + */ +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class SugarTransactionHelperTest { + private List recordList = new ArrayList<>(); + private TestRecord record1 = new TestRecord(); + private TestRecord record2 = new TestRecord(); + private TestRecord record3 = new TestRecord(); + + @Before + public void setUp() { + SugarContext.init(RuntimeEnvironment.application); + + record1.setId(1L); + record1.setName("lala"); + + record2.setId(2L); + record2.setName("fefe"); + + record3.setId(3L); + record3.setName("jaja"); + + recordList.add(record1); + recordList.add(record2); + recordList.add(record3); + } + + @Test(expected = IllegalAccessException.class) + public void testPrivateConstructor() throws Exception { + SugarTransactionHelper helper = SugarTransactionHelper.class.getDeclaredConstructor().newInstance(); + assertNull(helper); + } + + @Test + public void testDoInTransaction() { + SugarTransactionHelper.doInTransaction(new SugarTransactionHelper.Callback() { + @Override + public void manipulateInTransaction() { + for (TestRecord record: recordList) { + TestRecord.save(record); + } + } + }); + + final List results = TestRecord.listAll(TestRecord.class); + + assertEquals(true, inList(results, record1)); + assertEquals(true, inList(results, record2)); + assertEquals(true, inList(results, record3)); + } + + private boolean inList(List list, TestRecord testRecord) { + for (TestRecord record: list) { + if (record.getId().equals(testRecord.getId()) && + record.getName().equals(testRecord.getName())) { + return true; + } + } + return false; + } +} diff --git a/library/src/test/java/com/orm/model/AllAnotatedModel.java b/library/src/test/java/com/orm/model/AllAnotatedModel.java new file mode 100644 index 00000000..c2fb888d --- /dev/null +++ b/library/src/test/java/com/orm/model/AllAnotatedModel.java @@ -0,0 +1,25 @@ +package com.orm.model; + +import com.orm.annotation.Column; +import com.orm.annotation.Ignore; +import com.orm.annotation.NotNull; +import com.orm.annotation.Table; +import com.orm.annotation.Unique; + +/** + * @author jonatan.salas + */ +@Table +public class AllAnotatedModel { + + @NotNull @Unique + private Long id; + + @Column(notNull = true, name = "name", unique = true) + private String name; + + @Ignore + private String surname; + + public AllAnotatedModel() { } +} diff --git a/example/src/main/java/com/example/models/BigDecimalFieldAnnotatedModel.java b/library/src/test/java/com/orm/model/BigDecimalFieldAnnotatedModel.java similarity index 88% rename from example/src/main/java/com/example/models/BigDecimalFieldAnnotatedModel.java rename to library/src/test/java/com/orm/model/BigDecimalFieldAnnotatedModel.java index b3b60e98..f5529512 100644 --- a/example/src/main/java/com/example/models/BigDecimalFieldAnnotatedModel.java +++ b/library/src/test/java/com/orm/model/BigDecimalFieldAnnotatedModel.java @@ -1,6 +1,6 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; import java.math.BigDecimal; diff --git a/example/src/main/java/com/example/models/BigDecimalFieldExtendedModel.java b/library/src/test/java/com/orm/model/BigDecimalFieldExtendedModel.java similarity index 93% rename from example/src/main/java/com/example/models/BigDecimalFieldExtendedModel.java rename to library/src/test/java/com/orm/model/BigDecimalFieldExtendedModel.java index e258cf32..cbcdc3c9 100644 --- a/example/src/main/java/com/example/models/BigDecimalFieldExtendedModel.java +++ b/library/src/test/java/com/orm/model/BigDecimalFieldExtendedModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/example/src/main/java/com/example/models/BooleanFieldAnnotatedModel.java b/library/src/test/java/com/orm/model/BooleanFieldAnnotatedModel.java similarity index 90% rename from example/src/main/java/com/example/models/BooleanFieldAnnotatedModel.java rename to library/src/test/java/com/orm/model/BooleanFieldAnnotatedModel.java index d3a63edc..31a8668b 100644 --- a/example/src/main/java/com/example/models/BooleanFieldAnnotatedModel.java +++ b/library/src/test/java/com/orm/model/BooleanFieldAnnotatedModel.java @@ -1,6 +1,6 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class BooleanFieldAnnotatedModel { diff --git a/example/src/main/java/com/example/models/BooleanFieldExtendedModel.java b/library/src/test/java/com/orm/model/BooleanFieldExtendedModel.java similarity index 95% rename from example/src/main/java/com/example/models/BooleanFieldExtendedModel.java rename to library/src/test/java/com/orm/model/BooleanFieldExtendedModel.java index 972855cd..0c78c82a 100644 --- a/example/src/main/java/com/example/models/BooleanFieldExtendedModel.java +++ b/library/src/test/java/com/orm/model/BooleanFieldExtendedModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/example/src/main/java/com/example/models/ByteArrayAnnotatedModel.java b/library/src/test/java/com/orm/model/ByteArrayAnnotatedModel.java similarity index 86% rename from example/src/main/java/com/example/models/ByteArrayAnnotatedModel.java rename to library/src/test/java/com/orm/model/ByteArrayAnnotatedModel.java index da0b3ece..4a9f809c 100644 --- a/example/src/main/java/com/example/models/ByteArrayAnnotatedModel.java +++ b/library/src/test/java/com/orm/model/ByteArrayAnnotatedModel.java @@ -1,6 +1,6 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class ByteArrayAnnotatedModel { diff --git a/example/src/main/java/com/example/models/ByteArrayExtendedModel.java b/library/src/test/java/com/orm/model/ByteArrayExtendedModel.java similarity index 92% rename from example/src/main/java/com/example/models/ByteArrayExtendedModel.java rename to library/src/test/java/com/orm/model/ByteArrayExtendedModel.java index 7808c514..7e40208d 100644 --- a/example/src/main/java/com/example/models/ByteArrayExtendedModel.java +++ b/library/src/test/java/com/orm/model/ByteArrayExtendedModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/example/src/main/java/com/example/models/DoubleFieldAnnotatedModel.java b/library/src/test/java/com/orm/model/DoubleFieldAnnotatedModel.java similarity index 90% rename from example/src/main/java/com/example/models/DoubleFieldAnnotatedModel.java rename to library/src/test/java/com/orm/model/DoubleFieldAnnotatedModel.java index 2f5fd428..2c13e075 100644 --- a/example/src/main/java/com/example/models/DoubleFieldAnnotatedModel.java +++ b/library/src/test/java/com/orm/model/DoubleFieldAnnotatedModel.java @@ -1,6 +1,6 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class DoubleFieldAnnotatedModel { diff --git a/example/src/main/java/com/example/models/DoubleFieldExtendedModel.java b/library/src/test/java/com/orm/model/DoubleFieldExtendedModel.java similarity index 95% rename from example/src/main/java/com/example/models/DoubleFieldExtendedModel.java rename to library/src/test/java/com/orm/model/DoubleFieldExtendedModel.java index b0708b7c..1a000c3c 100644 --- a/example/src/main/java/com/example/models/DoubleFieldExtendedModel.java +++ b/library/src/test/java/com/orm/model/DoubleFieldExtendedModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/library/src/test/java/com/orm/model/EmptyModel.java b/library/src/test/java/com/orm/model/EmptyModel.java new file mode 100644 index 00000000..a98ab5e2 --- /dev/null +++ b/library/src/test/java/com/orm/model/EmptyModel.java @@ -0,0 +1,10 @@ +package com.orm.model; + +import com.orm.SugarRecord; + +/** + * Created by sibelius on 02/12/15. + */ +public class EmptyModel extends SugarRecord { + public EmptyModel() { } +} diff --git a/example/src/main/java/com/example/models/EnumFieldAnnotatedModel.java b/library/src/test/java/com/orm/model/EnumFieldAnnotatedModel.java similarity index 94% rename from example/src/main/java/com/example/models/EnumFieldAnnotatedModel.java rename to library/src/test/java/com/orm/model/EnumFieldAnnotatedModel.java index 34bf2f7e..abb3a63f 100644 --- a/example/src/main/java/com/example/models/EnumFieldAnnotatedModel.java +++ b/library/src/test/java/com/orm/model/EnumFieldAnnotatedModel.java @@ -1,6 +1,6 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class EnumFieldAnnotatedModel { diff --git a/example/src/main/java/com/example/models/EnumFieldExtendedModel.java b/library/src/test/java/com/orm/model/EnumFieldExtendedModel.java similarity index 97% rename from example/src/main/java/com/example/models/EnumFieldExtendedModel.java rename to library/src/test/java/com/orm/model/EnumFieldExtendedModel.java index df3a093b..24ec7725 100644 --- a/example/src/main/java/com/example/models/EnumFieldExtendedModel.java +++ b/library/src/test/java/com/orm/model/EnumFieldExtendedModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/example/src/main/java/com/example/models/FloatFieldAnnotatedModel.java b/library/src/test/java/com/orm/model/FloatFieldAnnotatedModel.java similarity index 89% rename from example/src/main/java/com/example/models/FloatFieldAnnotatedModel.java rename to library/src/test/java/com/orm/model/FloatFieldAnnotatedModel.java index 6d7f5e42..be2f01f5 100644 --- a/example/src/main/java/com/example/models/FloatFieldAnnotatedModel.java +++ b/library/src/test/java/com/orm/model/FloatFieldAnnotatedModel.java @@ -1,6 +1,6 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class FloatFieldAnnotatedModel { diff --git a/example/src/main/java/com/example/models/FloatFieldExtendedModel.java b/library/src/test/java/com/orm/model/FloatFieldExtendedModel.java similarity index 94% rename from example/src/main/java/com/example/models/FloatFieldExtendedModel.java rename to library/src/test/java/com/orm/model/FloatFieldExtendedModel.java index 0abf904b..e79f1a4b 100644 --- a/example/src/main/java/com/example/models/FloatFieldExtendedModel.java +++ b/library/src/test/java/com/orm/model/FloatFieldExtendedModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/example/src/main/java/com/example/models/IncompleteAnnotatedModel.java b/library/src/test/java/com/orm/model/IncompleteAnnotatedModel.java similarity index 76% rename from example/src/main/java/com/example/models/IncompleteAnnotatedModel.java rename to library/src/test/java/com/orm/model/IncompleteAnnotatedModel.java index e524d22f..64f8436b 100644 --- a/example/src/main/java/com/example/models/IncompleteAnnotatedModel.java +++ b/library/src/test/java/com/orm/model/IncompleteAnnotatedModel.java @@ -1,6 +1,6 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class IncompleteAnnotatedModel { diff --git a/library/src/test/java/com/orm/model/IntUniqueModel.java b/library/src/test/java/com/orm/model/IntUniqueModel.java new file mode 100644 index 00000000..7a03e3d0 --- /dev/null +++ b/library/src/test/java/com/orm/model/IntUniqueModel.java @@ -0,0 +1,19 @@ +package com.orm.model; + +import com.orm.SugarRecord; +import com.orm.annotation.Unique; + +/** + * Created by sibelius on 02/12/15. + */ +public class IntUniqueModel extends SugarRecord { + + @Unique + private int value; + + public IntUniqueModel() { } + + public IntUniqueModel(int value) { + this.value = value; + } +} diff --git a/example/src/main/java/com/example/models/IntegerFieldAnnotatedModel.java b/library/src/test/java/com/orm/model/IntegerFieldAnnotatedModel.java similarity index 89% rename from example/src/main/java/com/example/models/IntegerFieldAnnotatedModel.java rename to library/src/test/java/com/orm/model/IntegerFieldAnnotatedModel.java index 1b860ce1..e486d5db 100644 --- a/example/src/main/java/com/example/models/IntegerFieldAnnotatedModel.java +++ b/library/src/test/java/com/orm/model/IntegerFieldAnnotatedModel.java @@ -1,6 +1,6 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class IntegerFieldAnnotatedModel { diff --git a/example/src/main/java/com/example/models/IntegerFieldExtendedModel.java b/library/src/test/java/com/orm/model/IntegerFieldExtendedModel.java similarity index 94% rename from example/src/main/java/com/example/models/IntegerFieldExtendedModel.java rename to library/src/test/java/com/orm/model/IntegerFieldExtendedModel.java index b05df191..407979a3 100644 --- a/example/src/main/java/com/example/models/IntegerFieldExtendedModel.java +++ b/library/src/test/java/com/orm/model/IntegerFieldExtendedModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/example/src/main/java/com/example/models/LongFieldAnnotatedModel.java b/library/src/test/java/com/orm/model/LongFieldAnnotatedModel.java similarity index 89% rename from example/src/main/java/com/example/models/LongFieldAnnotatedModel.java rename to library/src/test/java/com/orm/model/LongFieldAnnotatedModel.java index c3986576..7f2cd539 100644 --- a/example/src/main/java/com/example/models/LongFieldAnnotatedModel.java +++ b/library/src/test/java/com/orm/model/LongFieldAnnotatedModel.java @@ -1,6 +1,6 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class LongFieldAnnotatedModel { diff --git a/example/src/main/java/com/example/models/LongFieldExtendedModel.java b/library/src/test/java/com/orm/model/LongFieldExtendedModel.java similarity index 94% rename from example/src/main/java/com/example/models/LongFieldExtendedModel.java rename to library/src/test/java/com/orm/model/LongFieldExtendedModel.java index 19ccdaa5..66bc7d6d 100644 --- a/example/src/main/java/com/example/models/LongFieldExtendedModel.java +++ b/library/src/test/java/com/orm/model/LongFieldExtendedModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/library/src/test/java/com/orm/model/MultiColumnUniqueModel.java b/library/src/test/java/com/orm/model/MultiColumnUniqueModel.java new file mode 100644 index 00000000..cea9cd92 --- /dev/null +++ b/library/src/test/java/com/orm/model/MultiColumnUniqueModel.java @@ -0,0 +1,21 @@ +package com.orm.model; + +import com.orm.SugarRecord; +import com.orm.annotation.MultiUnique; + +/** + * Created by sibelius on 02/12/15. + */ +@MultiUnique("a, b") +public class MultiColumnUniqueModel extends SugarRecord { + + private int a; + private int b; + + public MultiColumnUniqueModel() { } + + public MultiColumnUniqueModel(int a, int b) { + this.a = a; + this.b = b; + } +} \ No newline at end of file diff --git a/example/src/main/java/com/example/models/NestedAnnotatedModel.java b/library/src/test/java/com/orm/model/NestedAnnotatedModel.java similarity index 87% rename from example/src/main/java/com/example/models/NestedAnnotatedModel.java rename to library/src/test/java/com/orm/model/NestedAnnotatedModel.java index 8e834486..f57b2d7a 100644 --- a/example/src/main/java/com/example/models/NestedAnnotatedModel.java +++ b/library/src/test/java/com/orm/model/NestedAnnotatedModel.java @@ -1,6 +1,6 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class NestedAnnotatedModel { diff --git a/example/src/main/java/com/example/models/NestedExtendedModel.java b/library/src/test/java/com/orm/model/NestedExtendedModel.java similarity index 92% rename from example/src/main/java/com/example/models/NestedExtendedModel.java rename to library/src/test/java/com/orm/model/NestedExtendedModel.java index 369107c5..0b583d95 100644 --- a/example/src/main/java/com/example/models/NestedExtendedModel.java +++ b/library/src/test/java/com/orm/model/NestedExtendedModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/example/src/main/java/com/example/models/NestedMixedAAModel.java b/library/src/test/java/com/orm/model/NestedMixedAAModel.java similarity index 92% rename from example/src/main/java/com/example/models/NestedMixedAAModel.java rename to library/src/test/java/com/orm/model/NestedMixedAAModel.java index f5f70753..a96500f5 100644 --- a/example/src/main/java/com/example/models/NestedMixedAAModel.java +++ b/library/src/test/java/com/orm/model/NestedMixedAAModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/example/src/main/java/com/example/models/NestedMixedABModel.java b/library/src/test/java/com/orm/model/NestedMixedABModel.java similarity index 92% rename from example/src/main/java/com/example/models/NestedMixedABModel.java rename to library/src/test/java/com/orm/model/NestedMixedABModel.java index 045de69f..2cbae3db 100644 --- a/example/src/main/java/com/example/models/NestedMixedABModel.java +++ b/library/src/test/java/com/orm/model/NestedMixedABModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/example/src/main/java/com/example/models/NestedMixedBAModel.java b/library/src/test/java/com/orm/model/NestedMixedBAModel.java similarity index 87% rename from example/src/main/java/com/example/models/NestedMixedBAModel.java rename to library/src/test/java/com/orm/model/NestedMixedBAModel.java index 55a1e63b..82de9717 100644 --- a/example/src/main/java/com/example/models/NestedMixedBAModel.java +++ b/library/src/test/java/com/orm/model/NestedMixedBAModel.java @@ -1,7 +1,7 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class NestedMixedBAModel { diff --git a/example/src/main/java/com/example/models/NestedMixedBBModel.java b/library/src/test/java/com/orm/model/NestedMixedBBModel.java similarity index 87% rename from example/src/main/java/com/example/models/NestedMixedBBModel.java rename to library/src/test/java/com/orm/model/NestedMixedBBModel.java index b784f407..6a208b5b 100644 --- a/example/src/main/java/com/example/models/NestedMixedBBModel.java +++ b/library/src/test/java/com/orm/model/NestedMixedBBModel.java @@ -1,7 +1,7 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class NestedMixedBBModel { diff --git a/example/src/main/java/com/example/models/NoSugarModel.java b/library/src/test/java/com/orm/model/NoSugarModel.java similarity index 69% rename from example/src/main/java/com/example/models/NoSugarModel.java rename to library/src/test/java/com/orm/model/NoSugarModel.java index 0e2d55e8..617a99c4 100644 --- a/example/src/main/java/com/example/models/NoSugarModel.java +++ b/library/src/test/java/com/orm/model/NoSugarModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; public class NoSugarModel { diff --git a/example/src/main/java/com/example/models/RelationshipAnnotatedModel.java b/library/src/test/java/com/orm/model/RelationshipAnnotatedModel.java similarity index 87% rename from example/src/main/java/com/example/models/RelationshipAnnotatedModel.java rename to library/src/test/java/com/orm/model/RelationshipAnnotatedModel.java index aa0fff9c..42b9a4d9 100644 --- a/example/src/main/java/com/example/models/RelationshipAnnotatedModel.java +++ b/library/src/test/java/com/orm/model/RelationshipAnnotatedModel.java @@ -1,6 +1,6 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class RelationshipAnnotatedModel { diff --git a/example/src/main/java/com/example/models/RelationshipExtendedModel.java b/library/src/test/java/com/orm/model/RelationshipExtendedModel.java similarity index 92% rename from example/src/main/java/com/example/models/RelationshipExtendedModel.java rename to library/src/test/java/com/orm/model/RelationshipExtendedModel.java index afa2d105..1e4e99bc 100644 --- a/example/src/main/java/com/example/models/RelationshipExtendedModel.java +++ b/library/src/test/java/com/orm/model/RelationshipExtendedModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/example/src/main/java/com/example/models/RelationshipMixedAModel.java b/library/src/test/java/com/orm/model/RelationshipMixedAModel.java similarity index 92% rename from example/src/main/java/com/example/models/RelationshipMixedAModel.java rename to library/src/test/java/com/orm/model/RelationshipMixedAModel.java index f09dd5c0..1afa4a82 100644 --- a/example/src/main/java/com/example/models/RelationshipMixedAModel.java +++ b/library/src/test/java/com/orm/model/RelationshipMixedAModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/example/src/main/java/com/example/models/RelationshipMixedBModel.java b/library/src/test/java/com/orm/model/RelationshipMixedBModel.java similarity index 87% rename from example/src/main/java/com/example/models/RelationshipMixedBModel.java rename to library/src/test/java/com/orm/model/RelationshipMixedBModel.java index 9c9d2771..2197e62f 100644 --- a/example/src/main/java/com/example/models/RelationshipMixedBModel.java +++ b/library/src/test/java/com/orm/model/RelationshipMixedBModel.java @@ -1,7 +1,7 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class RelationshipMixedBModel { diff --git a/example/src/main/java/com/example/models/ShortFieldAnnotatedModel.java b/library/src/test/java/com/orm/model/ShortFieldAnnotatedModel.java similarity index 89% rename from example/src/main/java/com/example/models/ShortFieldAnnotatedModel.java rename to library/src/test/java/com/orm/model/ShortFieldAnnotatedModel.java index 8393974b..fea8e58e 100644 --- a/example/src/main/java/com/example/models/ShortFieldAnnotatedModel.java +++ b/library/src/test/java/com/orm/model/ShortFieldAnnotatedModel.java @@ -1,6 +1,6 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class ShortFieldAnnotatedModel { diff --git a/example/src/main/java/com/example/models/ShortFieldExtendedModel.java b/library/src/test/java/com/orm/model/ShortFieldExtendedModel.java similarity index 94% rename from example/src/main/java/com/example/models/ShortFieldExtendedModel.java rename to library/src/test/java/com/orm/model/ShortFieldExtendedModel.java index 5373bb23..5e90b9f6 100644 --- a/example/src/main/java/com/example/models/ShortFieldExtendedModel.java +++ b/library/src/test/java/com/orm/model/ShortFieldExtendedModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/example/src/main/java/com/example/models/SimpleAnnotatedModel.java b/library/src/test/java/com/orm/model/SimpleAnnotatedModel.java similarity index 73% rename from example/src/main/java/com/example/models/SimpleAnnotatedModel.java rename to library/src/test/java/com/orm/model/SimpleAnnotatedModel.java index 08d3b0fd..918840ed 100644 --- a/example/src/main/java/com/example/models/SimpleAnnotatedModel.java +++ b/library/src/test/java/com/orm/model/SimpleAnnotatedModel.java @@ -1,6 +1,6 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table diff --git a/example/src/main/java/com/example/models/SimpleExtendedModel.java b/library/src/test/java/com/orm/model/SimpleExtendedModel.java similarity index 81% rename from example/src/main/java/com/example/models/SimpleExtendedModel.java rename to library/src/test/java/com/orm/model/SimpleExtendedModel.java index 77f75b63..9040145d 100644 --- a/example/src/main/java/com/example/models/SimpleExtendedModel.java +++ b/library/src/test/java/com/orm/model/SimpleExtendedModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/example/src/main/java/com/example/models/SimpleModel.java b/library/src/test/java/com/orm/model/SimpleModel.java similarity index 95% rename from example/src/main/java/com/example/models/SimpleModel.java rename to library/src/test/java/com/orm/model/SimpleModel.java index dd482ee5..b2659084 100644 --- a/example/src/main/java/com/example/models/SimpleModel.java +++ b/library/src/test/java/com/orm/model/SimpleModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/example/src/main/java/com/example/models/StringFieldAnnotatedModel.java b/library/src/test/java/com/orm/model/StringFieldAnnotatedModel.java similarity index 87% rename from example/src/main/java/com/example/models/StringFieldAnnotatedModel.java rename to library/src/test/java/com/orm/model/StringFieldAnnotatedModel.java index 05420d44..e3220278 100644 --- a/example/src/main/java/com/example/models/StringFieldAnnotatedModel.java +++ b/library/src/test/java/com/orm/model/StringFieldAnnotatedModel.java @@ -1,6 +1,6 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class StringFieldAnnotatedModel { diff --git a/example/src/main/java/com/example/models/StringFieldAnnotatedNoIdModel.java b/library/src/test/java/com/orm/model/StringFieldAnnotatedNoIdModel.java similarity index 86% rename from example/src/main/java/com/example/models/StringFieldAnnotatedNoIdModel.java rename to library/src/test/java/com/orm/model/StringFieldAnnotatedNoIdModel.java index 1c12d581..4b458960 100644 --- a/example/src/main/java/com/example/models/StringFieldAnnotatedNoIdModel.java +++ b/library/src/test/java/com/orm/model/StringFieldAnnotatedNoIdModel.java @@ -1,6 +1,6 @@ -package com.example.models; +package com.orm.model; -import com.orm.dsl.Table; +import com.orm.annotation.Table; @Table public class StringFieldAnnotatedNoIdModel { diff --git a/example/src/main/java/com/example/models/StringFieldExtendedModel.java b/library/src/test/java/com/orm/model/StringFieldExtendedModel.java similarity index 93% rename from example/src/main/java/com/example/models/StringFieldExtendedModel.java rename to library/src/test/java/com/orm/model/StringFieldExtendedModel.java index 33bab4e9..9b79bc61 100644 --- a/example/src/main/java/com/example/models/StringFieldExtendedModel.java +++ b/library/src/test/java/com/orm/model/StringFieldExtendedModel.java @@ -1,4 +1,4 @@ -package com.example.models; +package com.orm.model; import com.orm.SugarRecord; diff --git a/library/src/test/java/com/orm/model/StringFieldExtendedModelAnnotatedColumn.java b/library/src/test/java/com/orm/model/StringFieldExtendedModelAnnotatedColumn.java new file mode 100644 index 00000000..674d53ba --- /dev/null +++ b/library/src/test/java/com/orm/model/StringFieldExtendedModelAnnotatedColumn.java @@ -0,0 +1,18 @@ +package com.orm.model; + +import com.orm.SugarRecord; +import com.orm.annotation.Column; + +/** + * Created by sibelius on 02/12/15. + */ +public class StringFieldExtendedModelAnnotatedColumn extends SugarRecord { + @Column(name="anyName") + public String name; + + public StringFieldExtendedModelAnnotatedColumn() { } + + public StringFieldExtendedModelAnnotatedColumn(String name) { + this.name = name; + } +} diff --git a/library/src/test/java/com/orm/model/TestRecord.java b/library/src/test/java/com/orm/model/TestRecord.java new file mode 100644 index 00000000..64fe7dba --- /dev/null +++ b/library/src/test/java/com/orm/model/TestRecord.java @@ -0,0 +1,21 @@ +package com.orm.model; + +import com.orm.SugarRecord; + +public class TestRecord extends SugarRecord { + + private String name; + + public TestRecord() { + super(); + } + + public TestRecord setName(String name) { + this.name = name; + return this; + } + + public String getName() { + return name; + } +} diff --git a/library/src/test/java/com/orm/model/foreignnull/OriginRecord.java b/library/src/test/java/com/orm/model/foreignnull/OriginRecord.java new file mode 100644 index 00000000..dbcd84bc --- /dev/null +++ b/library/src/test/java/com/orm/model/foreignnull/OriginRecord.java @@ -0,0 +1,20 @@ +package com.orm.model.foreignnull; + +import com.orm.annotation.Table; + +@Table +public class OriginRecord { + + private Long id; + private OriginRecord origin; + + public OriginRecord() { + } + + public OriginRecord(Long id, OriginRecord origin) { + this.id = id; + this.origin = origin; + } + + +} diff --git a/library/src/test/java/com/orm/model/onetomany/OneToManyModel.java b/library/src/test/java/com/orm/model/onetomany/OneToManyModel.java new file mode 100644 index 00000000..bb7bd96a --- /dev/null +++ b/library/src/test/java/com/orm/model/onetomany/OneToManyModel.java @@ -0,0 +1,29 @@ +package com.orm.model.onetomany; + +import com.orm.SugarRecord; +import com.orm.annotation.OneToMany; + +import java.util.List; + +/** + * Created by Łukasz Wesołowski on 28.07.2016. + */ +public class OneToManyModel extends SugarRecord { + @OneToMany(targetField = "model") + private List models; + + public OneToManyModel() { + } + + public OneToManyModel(Long id) { + setId(id); + } + + public List getModels() { + return models; + } + + public void setModels(List models) { + this.models = models; + } +} diff --git a/library/src/test/java/com/orm/model/onetomany/OneToManyRelationModel.java b/library/src/test/java/com/orm/model/onetomany/OneToManyRelationModel.java new file mode 100644 index 00000000..4c17ec56 --- /dev/null +++ b/library/src/test/java/com/orm/model/onetomany/OneToManyRelationModel.java @@ -0,0 +1,26 @@ +package com.orm.model.onetomany; + +import com.orm.SugarRecord; + +/** + * Created by Łukasz Wesołowski on 28.07.2016. + */ +public class OneToManyRelationModel extends SugarRecord { + private OneToManyModel model; + + public OneToManyRelationModel() { + } + + public OneToManyRelationModel(Long id, OneToManyModel model) { + setId(id); + this.model = model; + } + + public OneToManyModel getModel() { + return model; + } + + public void setModel(OneToManyModel model) { + this.model = model; + } +} diff --git a/library/src/test/java/com/orm/model/onetomany/WithoutOneToManyAnnotationModel.java b/library/src/test/java/com/orm/model/onetomany/WithoutOneToManyAnnotationModel.java new file mode 100644 index 00000000..d48e38f0 --- /dev/null +++ b/library/src/test/java/com/orm/model/onetomany/WithoutOneToManyAnnotationModel.java @@ -0,0 +1,27 @@ +package com.orm.model.onetomany; + +import com.orm.SugarRecord; + +import java.util.List; + +/** + * Created by Łukasz Wesołowski on 27.08.2016. + */ +public class WithoutOneToManyAnnotationModel extends SugarRecord { + private List models; + + public WithoutOneToManyAnnotationModel() { + } + + public WithoutOneToManyAnnotationModel(Long id) { + setId(id); + } + + public List getModels() { + return models; + } + + public void setModels(List models) { + this.models = models; + } +} diff --git a/library/src/test/java/com/orm/model/onetomany/WithoutOneToManyAnnotationRelationModel.java b/library/src/test/java/com/orm/model/onetomany/WithoutOneToManyAnnotationRelationModel.java new file mode 100644 index 00000000..34e1eb2a --- /dev/null +++ b/library/src/test/java/com/orm/model/onetomany/WithoutOneToManyAnnotationRelationModel.java @@ -0,0 +1,26 @@ +package com.orm.model.onetomany; + +import com.orm.SugarRecord; + +/** + * Created by Łukasz Wesołowski on 27.08.2016. + */ +public class WithoutOneToManyAnnotationRelationModel extends SugarRecord { + private WithoutOneToManyAnnotationModel model; + + public WithoutOneToManyAnnotationRelationModel() { + } + + public WithoutOneToManyAnnotationRelationModel(Long id, WithoutOneToManyAnnotationModel model) { + setId(id); + this.model = model; + } + + public WithoutOneToManyAnnotationModel getModel() { + return model; + } + + public void setModel(WithoutOneToManyAnnotationModel model) { + this.model = model; + } +} diff --git a/library/src/test/java/com/orm/query/DummyContext.java b/library/src/test/java/com/orm/query/DummyContext.java deleted file mode 100644 index 77a897ff..00000000 --- a/library/src/test/java/com/orm/query/DummyContext.java +++ /dev/null @@ -1,484 +0,0 @@ -package com.orm.query; - -import android.content.*; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.content.res.AssetManager; -import android.content.res.Configuration; -import android.content.res.Resources; -import android.database.DatabaseErrorHandler; -import android.database.sqlite.SQLiteDatabase; -import android.graphics.Bitmap; -import android.graphics.drawable.Drawable; -import android.net.Uri; -import android.os.Bundle; -import android.os.Handler; -import android.os.Looper; -import android.os.UserHandle; -import android.view.Display; - -import java.io.*; - -public class DummyContext extends Context { - @Override - public File getCodeCacheDir() { - return null; - } - - @Override - public File[] getExternalFilesDirs(String type) { - return null; - } - - @Override - public File[] getExternalCacheDirs() { - return null; - } - - @Override - public File getNoBackupFilesDir() { - return null; - } - - @Override - public File[] getObbDirs() { - return null; - } - - @Override - public File[] getExternalMediaDirs() { - return null; - } - - @Override - public AssetManager getAssets() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public Resources getResources() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public PackageManager getPackageManager() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public ContentResolver getContentResolver() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public Looper getMainLooper() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public Context getApplicationContext() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void setTheme(int i) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public Resources.Theme getTheme() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public ClassLoader getClassLoader() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public String getPackageName() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public ApplicationInfo getApplicationInfo() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public String getPackageResourcePath() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public String getPackageCodePath() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public SharedPreferences getSharedPreferences(String s, int i) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public FileInputStream openFileInput(String s) throws FileNotFoundException { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public FileOutputStream openFileOutput(String s, int i) throws FileNotFoundException { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public boolean deleteFile(String s) { - return false; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public File getFileStreamPath(String s) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public File getFilesDir() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public File getExternalFilesDir(String s) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public File getObbDir() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public File getCacheDir() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public File getExternalCacheDir() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public String[] fileList() { - return new String[0]; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public File getDir(String s, int i) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public SQLiteDatabase openOrCreateDatabase(String s, int i, SQLiteDatabase.CursorFactory cursorFactory) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public SQLiteDatabase openOrCreateDatabase(String s, int i, SQLiteDatabase.CursorFactory cursorFactory, DatabaseErrorHandler databaseErrorHandler) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public boolean deleteDatabase(String s) { - return false; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public File getDatabasePath(String s) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public String[] databaseList() { - return new String[0]; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public Drawable getWallpaper() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public Drawable peekWallpaper() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public int getWallpaperDesiredMinimumWidth() { - return 0; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public int getWallpaperDesiredMinimumHeight() { - return 0; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void setWallpaper(Bitmap bitmap) throws IOException { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void setWallpaper(InputStream inputStream) throws IOException { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void clearWallpaper() throws IOException { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void startActivity(Intent intent) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void startActivity(Intent intent, Bundle options) { - //To change body of implemented methods use File | Settings | File Templates. - } - - - @Override - public void startActivities(Intent[] intents) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void startActivities(Intent[] intents, Bundle options) { - //To change body of implemented methods use File | Settings | File Templates. - } - - - @Override - public void startIntentSender(IntentSender intentSender, Intent intent, int i, int i1, int i2) throws IntentSender.SendIntentException { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) throws IntentSender.SendIntentException { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void sendBroadcast(Intent intent) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void sendBroadcast(Intent intent, String s) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void sendOrderedBroadcast(Intent intent, String s) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void sendOrderedBroadcast(Intent intent, String s, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s1, Bundle bundle) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void sendBroadcastAsUser(Intent intent, UserHandle user) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void sendStickyBroadcast(Intent intent) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s, Bundle bundle) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void removeStickyBroadcast(Intent intent) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle user, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void removeStickyBroadcastAsUser(Intent intent, UserHandle user) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public Intent registerReceiver(BroadcastReceiver broadcastReceiver, IntentFilter intentFilter) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public Intent registerReceiver(BroadcastReceiver broadcastReceiver, IntentFilter intentFilter, String s, Handler handler) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void unregisterReceiver(BroadcastReceiver broadcastReceiver) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public ComponentName startService(Intent intent) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public boolean stopService(Intent intent) { - return false; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) { - return false; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void unbindService(ServiceConnection serviceConnection) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public boolean startInstrumentation(ComponentName componentName, String s, Bundle bundle) { - return false; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public Object getSystemService(String s) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public String getSystemServiceName(Class serviceClass) { - return null; - } - - @Override - public int checkPermission(String s, int i, int i1) { - return PackageManager.PERMISSION_GRANTED; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public int checkCallingPermission(String s) { - return PackageManager.PERMISSION_GRANTED; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public int checkCallingOrSelfPermission(String s) { - return PackageManager.PERMISSION_GRANTED; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public int checkSelfPermission(String permission) { - return PackageManager.PERMISSION_GRANTED; - } - - @Override - public void enforcePermission(String s, int i, int i1, String s1) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void enforceCallingPermission(String s, String s1) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void enforceCallingOrSelfPermission(String s, String s1) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void grantUriPermission(String s, Uri uri, int i) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void revokeUriPermission(Uri uri, int i) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public int checkUriPermission(Uri uri, int i, int i1, int i2) { - return 0; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public int checkCallingUriPermission(Uri uri, int i) { - return 0; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public int checkCallingOrSelfUriPermission(Uri uri, int i) { - return 0; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public int checkUriPermission(Uri uri, String s, String s1, int i, int i1, int i2) { - return 0; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void enforceUriPermission(Uri uri, int i, int i1, int i2, String s) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void enforceCallingUriPermission(Uri uri, int i, String s) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void enforceCallingOrSelfUriPermission(Uri uri, int i, String s) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void enforceUriPermission(Uri uri, String s, String s1, int i, int i1, int i2, String s2) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public Context createPackageContext(String s, int i) throws PackageManager.NameNotFoundException { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public Context createConfigurationContext(Configuration overrideConfiguration) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public Context createDisplayContext(Display display) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } -} diff --git a/library/src/test/java/com/orm/query/QueryBuilderTests.java b/library/src/test/java/com/orm/query/QueryBuilderTests.java index 96e3c79f..30b220df 100644 --- a/library/src/test/java/com/orm/query/QueryBuilderTests.java +++ b/library/src/test/java/com/orm/query/QueryBuilderTests.java @@ -6,7 +6,8 @@ import static junit.framework.Assert.assertEquals; -public class QueryBuilderTests { +public final class QueryBuilderTests { + @Test(expected=RuntimeException.class) public void noArgumentsTest() { QueryBuilder.generatePlaceholders(0); diff --git a/library/src/test/java/com/orm/query/SelectTest.java b/library/src/test/java/com/orm/query/SelectTest.java index 3ab345ae..ad0393bd 100644 --- a/library/src/test/java/com/orm/query/SelectTest.java +++ b/library/src/test/java/com/orm/query/SelectTest.java @@ -1,10 +1,19 @@ package com.orm.query; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.TestRecord; + import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; import static junit.framework.Assert.assertEquals; -public class SelectTest { +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class SelectTest { @Test public void testMergeCondition(){ @@ -20,7 +29,6 @@ public void testMergeCondition(){ assertEquals("2", where.getArgs()[1]); } - @Test public void testWhere(){ Select where = Select.from(TestRecord.class).where(Condition.prop("test").eq("satya")); @@ -35,6 +43,34 @@ public void testWhere(){ assertEquals("2", where.getArgs()[1]); } + @Test + public void toSqlAllClauses(){ + String toSql = Select.from(TestRecord.class) + .where("foo") + .orderBy("doe") + .groupBy("john") + .limit("5") + .offset("10") + .toSql(); + assertEquals("SELECT * FROM TEST_RECORD WHERE foo ORDER BY doe GROUP BY john LIMIT 5 OFFSET 10 ", toSql); + } + + @Test + public void toSqlNoClauses(){ + String toSql = Select.from(TestRecord.class) + .toSql(); + assertEquals("SELECT * FROM TEST_RECORD ", toSql); + } + + @Test + public void toSqlWhereLimitClauses(){ + String toSql = Select.from(TestRecord.class) + .where("foo") + .limit("10") + .toSql(); + assertEquals("SELECT * FROM TEST_RECORD WHERE foo LIMIT 10 ", toSql); + } + @Test public void testWhereOr(){ @@ -101,4 +137,4 @@ public void testIsNotNull() { assertEquals("(test IS NOT NULL )", where.getWhereCond()); assertEquals(0, where.getArgs().length); } -} +} \ No newline at end of file diff --git a/library/src/test/java/com/orm/query/TestRecord.java b/library/src/test/java/com/orm/query/TestRecord.java deleted file mode 100644 index 50997205..00000000 --- a/library/src/test/java/com/orm/query/TestRecord.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.orm.query; - -import android.content.Context; -import com.orm.SugarRecord; - -public class TestRecord extends SugarRecord { - - private String name; - - public TestRecord(Context context) { - super(); - } -} diff --git a/library/src/test/java/com/orm/record/BigDecimalFieldTests.java b/library/src/test/java/com/orm/record/BigDecimalFieldTests.java new file mode 100644 index 00000000..a877a6af --- /dev/null +++ b/library/src/test/java/com/orm/record/BigDecimalFieldTests.java @@ -0,0 +1,59 @@ +package com.orm.record; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.BigDecimalFieldAnnotatedModel; +import com.orm.model.BigDecimalFieldExtendedModel; + +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.math.BigDecimal; + +import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.findById; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertEquals; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class BigDecimalFieldTests { + private BigDecimal decimal = new BigDecimal(1234.5678901234567890123456789); + + @Test + public void nullBigDecimalExtendedTest() { + save(new BigDecimalFieldExtendedModel()); + BigDecimalFieldExtendedModel model = findById(BigDecimalFieldExtendedModel.class, 1); + assertNull(model.getBigDecimal()); + } + + @Test + public void nullBigDecimalAnnotatedTest() { + save(new BigDecimalFieldAnnotatedModel()); + BigDecimalFieldAnnotatedModel model = findById(BigDecimalFieldAnnotatedModel.class, 1); + assertNull(model.getBigDecimal()); + } + + @Test + public void bigDecimalExtendedTest() { + save(new BigDecimalFieldExtendedModel(decimal)); + BigDecimalFieldExtendedModel model = findById(BigDecimalFieldExtendedModel.class, 1); + assertEquals(decimal, model.getBigDecimal()); + } + + @Test + public void bigDecimalAnnotatedTest() { + save(new BigDecimalFieldAnnotatedModel(decimal)); + BigDecimalFieldAnnotatedModel model = findById(BigDecimalFieldAnnotatedModel.class, 1); + assertEquals(decimal, model.getBigDecimal()); + } + + @After + public void after() { + decimal = null; + } +} diff --git a/library/src/test/java/com/orm/record/BooleanFieldTests.java b/library/src/test/java/com/orm/record/BooleanFieldTests.java new file mode 100644 index 00000000..3a026a48 --- /dev/null +++ b/library/src/test/java/com/orm/record/BooleanFieldTests.java @@ -0,0 +1,83 @@ +package com.orm.record; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.BooleanFieldAnnotatedModel; +import com.orm.model.BooleanFieldExtendedModel; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.findById; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class BooleanFieldTests { + + @Test + public void nullBooleanExtendedTest() { + save(new BooleanFieldExtendedModel()); + BooleanFieldExtendedModel model = findById(BooleanFieldExtendedModel.class, 1); + assertNull(model.getBoolean()); + } + + @Test + public void nullRawBooleanExtendedTest() { + save(new BooleanFieldExtendedModel()); + BooleanFieldExtendedModel model = findById(BooleanFieldExtendedModel.class, 1); + assertEquals(false, model.getRawBoolean()); + } + + @Test + public void nullBooleanAnnotatedTest() { + save(new BooleanFieldAnnotatedModel()); + BooleanFieldAnnotatedModel model = findById(BooleanFieldAnnotatedModel.class, 1); + assertNull(model.getBoolean()); + } + + @Test + public void nullRawBooleanAnnotatedTest() { + save(new BooleanFieldAnnotatedModel()); + BooleanFieldAnnotatedModel model = findById(BooleanFieldAnnotatedModel.class, 1); + assertEquals(false, model.getRawBoolean()); + } + +////TODO check this method +// @Test +// public void objectBooleanExtendedTest() { +// save(new BooleanFieldExtendedModel(true)); +// BooleanFieldExtendedModel model = SugarRecord.findById(BooleanFieldExtendedModel.class, 1); +// assertEquals(true, model.getBoolean()); +// } + + @Test + public void rawBooleanExtendedTest() { + save(new BooleanFieldExtendedModel(true)); + BooleanFieldExtendedModel model = findById(BooleanFieldExtendedModel.class, 1); + assertEquals(true, model.getRawBoolean()); + } + +// //TODO check this +// @Test +// public void objectBooleanAnnotatedTest() { +// save(new BooleanFieldAnnotatedModel(true)); +// BooleanFieldAnnotatedModel model = SugarRecord.findById(BooleanFieldAnnotatedModel.class, 1); +// +// if (null != model) { +// assertEquals(true, model.getBoolean()); +// } +// } + + @Test + public void rawBooleanAnnotatedTest() { + save(new BooleanFieldAnnotatedModel(true)); + BooleanFieldAnnotatedModel model = findById(BooleanFieldAnnotatedModel.class, 1); + assertEquals(true, model.getRawBoolean()); + } +} diff --git a/example/src/test/java/com/example/sugartest/ByteArrayFieldTests.java b/library/src/test/java/com/orm/record/ByteArrayFieldTests.java similarity index 64% rename from example/src/test/java/com/example/sugartest/ByteArrayFieldTests.java rename to library/src/test/java/com/orm/record/ByteArrayFieldTests.java index 6f830960..450823f2 100644 --- a/example/src/test/java/com/example/sugartest/ByteArrayFieldTests.java +++ b/library/src/test/java/com/orm/record/ByteArrayFieldTests.java @@ -1,26 +1,30 @@ -package com.example.sugartest; +package com.orm.record; - -import com.example.models.ByteArrayAnnotatedModel; -import com.example.models.ByteArrayExtendedModel; -import com.orm.SugarRecord; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.ByteArrayAnnotatedModel; +import com.orm.model.ByteArrayExtendedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.findById; + import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class ByteArrayFieldTests { +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class ByteArrayFieldTests { + @Test public void nullByteArrayExtendedTest() { byte[] array = "".getBytes(); save(new ByteArrayExtendedModel()); - ByteArrayExtendedModel model = SugarRecord.findById(ByteArrayExtendedModel.class, 1); + ByteArrayExtendedModel model = findById(ByteArrayExtendedModel.class, 1); assertEquals(new String(array), new String(model.getByteArray())); assertArrayEquals(array, model.getByteArray()); } @@ -29,7 +33,7 @@ public void nullByteArrayExtendedTest() { public void nullByteArrayAnnotatedTest() { byte[] array = "".getBytes(); save(new ByteArrayAnnotatedModel()); - ByteArrayAnnotatedModel model = SugarRecord.findById(ByteArrayAnnotatedModel.class, 1); + ByteArrayAnnotatedModel model = findById(ByteArrayAnnotatedModel.class, 1); assertEquals(new String(array), new String(model.getByteArray())); assertArrayEquals(array, model.getByteArray()); } @@ -38,7 +42,7 @@ public void nullByteArrayAnnotatedTest() { public void byteArrayExtendedTest() { byte[] array = "hello".getBytes(); save(new ByteArrayExtendedModel(array)); - ByteArrayExtendedModel model = SugarRecord.findById(ByteArrayExtendedModel.class, 1); + ByteArrayExtendedModel model = findById(ByteArrayExtendedModel.class, 1); assertEquals(new String(array), new String(model.getByteArray())); assertArrayEquals(array, model.getByteArray()); } @@ -47,7 +51,7 @@ public void byteArrayExtendedTest() { public void byteArrayAnnotatedTest() { byte[] array = "hello".getBytes(); save(new ByteArrayAnnotatedModel(array)); - ByteArrayAnnotatedModel model = SugarRecord.findById(ByteArrayAnnotatedModel.class, 1); + ByteArrayAnnotatedModel model = findById(ByteArrayAnnotatedModel.class, 1); assertEquals(new String(array), new String(model.getByteArray())); assertArrayEquals(array, model.getByteArray()); } diff --git a/example/src/test/java/com/example/sugartest/CursorTests.java b/library/src/test/java/com/orm/record/CursorTests.java similarity index 82% rename from example/src/test/java/com/example/sugartest/CursorTests.java rename to library/src/test/java/com/orm/record/CursorTests.java index 78c3d71b..a6036a15 100644 --- a/example/src/test/java/com/example/sugartest/CursorTests.java +++ b/library/src/test/java/com/orm/record/CursorTests.java @@ -1,4 +1,4 @@ -package com.example.sugartest; +package com.orm.record; import android.annotation.TargetApi; import android.content.Context; @@ -9,12 +9,15 @@ import android.widget.CursorAdapter; import android.widget.TextView; -import com.example.models.SimpleModel; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.SimpleModel; import com.orm.query.Select; +import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; -import org.robolectric.Robolectric; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; @@ -23,8 +26,9 @@ import static junit.framework.Assert.assertSame; @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class CursorTests { +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class CursorTests { + @Test public void testColumnNames() { save(new SimpleModel()); @@ -34,7 +38,7 @@ public void testColumnNames() { } } @Test - public void testSugarCursor(){ + public void testSugarCursor() { save(new SimpleModel()); Cursor cursor = Select.from(SimpleModel.class).getCursor(); assertNotSame("No _id", -1, cursor.getColumnIndex("_id")); @@ -42,7 +46,7 @@ public void testSugarCursor(){ } @Test - public void testNoColumn(){ + public void testNoColumn() { save(new SimpleModel()); Cursor cursor = Select.from(SimpleModel.class).getCursor(); assertSame(-1, cursor.getColumnIndex("nonexistent")); @@ -68,5 +72,7 @@ public void bindView(View view, Context context, Cursor cursor) { ((TextView) view).setText(s); } }; + + Assert.assertNotNull(adapter); } } diff --git a/example/src/test/java/com/example/sugartest/DoubleFieldTests.java b/library/src/test/java/com/orm/record/DoubleFieldTests.java similarity index 55% rename from example/src/test/java/com/example/sugartest/DoubleFieldTests.java rename to library/src/test/java/com/orm/record/DoubleFieldTests.java index 89dbd00a..a05fa3e0 100644 --- a/example/src/test/java/com/example/sugartest/DoubleFieldTests.java +++ b/library/src/test/java/com/orm/record/DoubleFieldTests.java @@ -1,76 +1,83 @@ -package com.example.sugartest; +package com.orm.record; - -import com.example.models.DoubleFieldAnnotatedModel; -import com.example.models.DoubleFieldExtendedModel; +import com.orm.app.ClientApp; import com.orm.SugarRecord; +import com.orm.dsl.BuildConfig; +import com.orm.model.DoubleFieldAnnotatedModel; +import com.orm.model.DoubleFieldExtendedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.findById; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class DoubleFieldTests { +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class DoubleFieldTests { + @Test public void nullDoubleExtendedTest() { save(new DoubleFieldExtendedModel()); - DoubleFieldExtendedModel model = SugarRecord.findById(DoubleFieldExtendedModel.class, 1); + DoubleFieldExtendedModel model = findById(DoubleFieldExtendedModel.class, 1); assertNull(model.getDouble()); } @Test public void nullRawDoubleExtendedTest() { save(new DoubleFieldExtendedModel()); - DoubleFieldExtendedModel model = SugarRecord.findById(DoubleFieldExtendedModel.class, 1); + DoubleFieldExtendedModel model = findById(DoubleFieldExtendedModel.class, 1); assertEquals(0.0, model.getRawDouble(), 0.0000000001); } @Test public void nullDoubleAnnotatedTest() { save(new DoubleFieldAnnotatedModel()); - DoubleFieldAnnotatedModel model = SugarRecord.findById(DoubleFieldAnnotatedModel.class, 1); + DoubleFieldAnnotatedModel model = findById(DoubleFieldAnnotatedModel.class, 1); assertNull(model.getDouble()); } @Test public void nullRawDoubleAnnotatedTest() { save(new DoubleFieldAnnotatedModel()); - DoubleFieldAnnotatedModel model = SugarRecord.findById(DoubleFieldAnnotatedModel.class, 1); + DoubleFieldAnnotatedModel model = findById(DoubleFieldAnnotatedModel.class, 1); assertEquals(0.0, model.getRawDouble(), 0.0000000001); } @Test + @SuppressWarnings("all") public void objectDoubleExtendedTest() { - Double objectDouble = new Double(25.0); + Double objectDouble = Double.valueOf(25.0); save(new DoubleFieldExtendedModel(objectDouble)); - DoubleFieldExtendedModel model = SugarRecord.findById(DoubleFieldExtendedModel.class, 1); + DoubleFieldExtendedModel model = findById(DoubleFieldExtendedModel.class, 1); assertEquals(objectDouble, model.getDouble()); } @Test public void rawDoubleExtendedTest() { save(new DoubleFieldExtendedModel(25.0)); - DoubleFieldExtendedModel model = SugarRecord.findById(DoubleFieldExtendedModel.class, 1); + DoubleFieldExtendedModel model = findById(DoubleFieldExtendedModel.class, 1); assertEquals(25.0, model.getRawDouble(), 0.0000000001); } @Test + @SuppressWarnings("all") public void objectDoubleAnnotatedTest() { - Double objectDouble = new Double(25.0); + Double objectDouble = Double.valueOf(25.0); save(new DoubleFieldAnnotatedModel(objectDouble)); - DoubleFieldAnnotatedModel model = SugarRecord.findById(DoubleFieldAnnotatedModel.class, 1); + DoubleFieldAnnotatedModel model = findById(DoubleFieldAnnotatedModel.class, 1); assertEquals(objectDouble, model.getDouble()); } @Test public void rawDoubleAnnotatedTest() { save(new DoubleFieldAnnotatedModel(25.0)); - DoubleFieldAnnotatedModel model = SugarRecord.findById(DoubleFieldAnnotatedModel.class, 1); + DoubleFieldAnnotatedModel model = findById(DoubleFieldAnnotatedModel.class, 1); assertEquals(25.0, model.getRawDouble(), 0.0000000001); } } diff --git a/example/src/test/java/com/example/sugartest/EnumFieldTests.java b/library/src/test/java/com/orm/record/EnumFieldTests.java similarity index 53% rename from example/src/test/java/com/example/sugartest/EnumFieldTests.java rename to library/src/test/java/com/orm/record/EnumFieldTests.java index 4eeaed71..42647b00 100644 --- a/example/src/test/java/com/example/sugartest/EnumFieldTests.java +++ b/library/src/test/java/com/orm/record/EnumFieldTests.java @@ -1,71 +1,76 @@ -package com.example.sugartest; +package com.orm.record; -import com.example.models.EnumFieldAnnotatedModel; -import com.example.models.EnumFieldExtendedModel; -import com.orm.SugarRecord; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.EnumFieldAnnotatedModel; +import com.orm.model.EnumFieldExtendedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.findById; +import static com.orm.model.EnumFieldExtendedModel.DefaultEnum; +import static com.orm.model.EnumFieldExtendedModel.OverrideEnum; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk = 18) -public class EnumFieldTests { +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class EnumFieldTests { + @Test public void nullDefaultEnumExtendedTest() { save(new EnumFieldExtendedModel()); - EnumFieldExtendedModel model = SugarRecord.findById(EnumFieldExtendedModel.class, 1); + EnumFieldExtendedModel model = findById(EnumFieldExtendedModel.class, 1); assertNull(model.getDefaultEnum()); } @Test public void nullOverriddenEnumExtendedTest() { save(new EnumFieldExtendedModel()); - EnumFieldExtendedModel model = SugarRecord.findById(EnumFieldExtendedModel.class, 1); + EnumFieldExtendedModel model = findById(EnumFieldExtendedModel.class, 1); assertNull(model.getOverrideEnum()); } @Test public void nullDefaultEnumAnnotatedTest() { save(new EnumFieldAnnotatedModel()); - EnumFieldAnnotatedModel model = SugarRecord.findById(EnumFieldAnnotatedModel.class, 1); + EnumFieldAnnotatedModel model = findById(EnumFieldAnnotatedModel.class, 1); assertNull(model.getDefaultEnum()); } @Test public void nullOverriddenEnumAnnotatedTest() { save(new EnumFieldAnnotatedModel()); - EnumFieldAnnotatedModel model = SugarRecord.findById(EnumFieldAnnotatedModel.class, 1); + EnumFieldAnnotatedModel model = findById(EnumFieldAnnotatedModel.class, 1); assertNull(model.getOverrideEnum()); } @Test public void defaultEnumExtendedTest() { - save(new EnumFieldExtendedModel(EnumFieldExtendedModel.OverrideEnum.ONE, - EnumFieldExtendedModel.DefaultEnum.TWO)); - EnumFieldExtendedModel model = SugarRecord.findById(EnumFieldExtendedModel.class, 1); + save(new EnumFieldExtendedModel(OverrideEnum.ONE, DefaultEnum.TWO)); + EnumFieldExtendedModel model = findById(EnumFieldExtendedModel.class, 1); assertNotNull(model); - assertEquals(model.getDefaultEnum(), EnumFieldExtendedModel.DefaultEnum.TWO); + assertEquals(model.getDefaultEnum(), DefaultEnum.TWO); } @Test public void overriddenEnumExtendedTest() { - save(new EnumFieldExtendedModel(EnumFieldExtendedModel.OverrideEnum.ONE, - EnumFieldExtendedModel.DefaultEnum.TWO)); - EnumFieldExtendedModel model = SugarRecord.findById(EnumFieldExtendedModel.class, 1); + save(new EnumFieldExtendedModel(OverrideEnum.ONE, DefaultEnum.TWO)); + EnumFieldExtendedModel model = findById(EnumFieldExtendedModel.class, 1); assertNotNull(model); - assertEquals(model.getOverrideEnum(), EnumFieldExtendedModel.OverrideEnum.ONE); + assertEquals(model.getOverrideEnum(), OverrideEnum.ONE); } @Test public void defaultEnumAnnotatedTest() { save(new EnumFieldAnnotatedModel(EnumFieldAnnotatedModel.OverrideEnum.ONE, EnumFieldAnnotatedModel.DefaultEnum.TWO)); - EnumFieldAnnotatedModel model = SugarRecord.findById(EnumFieldAnnotatedModel.class, 1); + EnumFieldAnnotatedModel model = findById(EnumFieldAnnotatedModel.class, 1); assertNotNull(model); assertEquals(model.getDefaultEnum(), EnumFieldAnnotatedModel.DefaultEnum.TWO); } @@ -74,7 +79,7 @@ public void defaultEnumAnnotatedTest() { public void overriddenEnumAnnotatedTest() { save(new EnumFieldAnnotatedModel(EnumFieldAnnotatedModel.OverrideEnum.ONE, EnumFieldAnnotatedModel.DefaultEnum.TWO)); - EnumFieldAnnotatedModel model = SugarRecord.findById(EnumFieldAnnotatedModel.class, 1); + EnumFieldAnnotatedModel model = findById(EnumFieldAnnotatedModel.class, 1); assertNotNull(model); assertEquals(model.getOverrideEnum(), EnumFieldAnnotatedModel.OverrideEnum.ONE); } diff --git a/library/src/test/java/com/orm/record/FirstAndLastTests.java b/library/src/test/java/com/orm/record/FirstAndLastTests.java new file mode 100644 index 00000000..1b6db799 --- /dev/null +++ b/library/src/test/java/com/orm/record/FirstAndLastTests.java @@ -0,0 +1,199 @@ +package com.orm.record; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.FloatFieldAnnotatedModel; +import com.orm.model.FloatFieldExtendedModel; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.first; +import static com.orm.SugarRecord.delete; +import static com.orm.SugarRecord.findById; +import static com.orm.SugarRecord.last; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public class FirstAndLastTests { + + @Test + @SuppressWarnings("all") + public void firstExtendedTest() { + Float firstObjectFloat = 25F; + Float lastObjectFloat = 50F; + save(new FloatFieldExtendedModel(firstObjectFloat)); + save(new FloatFieldExtendedModel(lastObjectFloat)); + FloatFieldExtendedModel model = first(FloatFieldExtendedModel.class); + + if (null != model) { + assertEquals(firstObjectFloat, model.getFloat()); + } + } + + @Test + public void firstDeletedRecordExtendedTest() { + Float second = 25F; + + save(new FloatFieldExtendedModel(15F)); + save(new FloatFieldExtendedModel(second)); + save(new FloatFieldExtendedModel(35F)); + save(new FloatFieldExtendedModel(45F)); + + FloatFieldExtendedModel firstRecord = findById(FloatFieldExtendedModel.class, 1); + delete(firstRecord); + FloatFieldExtendedModel model = first(FloatFieldExtendedModel.class); + + if (null != model) { + assertEquals(second, model.getFloat()); + } + } + + @Test + public void lastExtendedTest() { + Float last = 50F; + + save(new FloatFieldExtendedModel(25F)); + save(new FloatFieldExtendedModel(last)); + + FloatFieldExtendedModel model = last(FloatFieldExtendedModel.class); + + if (null != model) { + assertEquals(last, model.getFloat()); + } + } + + @Test + public void lastDeletedRecordExtendedTest() { + Float third = 35F; + + save(new FloatFieldExtendedModel(15F)); + save(new FloatFieldExtendedModel(25F)); + save(new FloatFieldExtendedModel(third)); + save(new FloatFieldExtendedModel(45F)); + + FloatFieldExtendedModel lastRecord = findById(FloatFieldExtendedModel.class, 4); + delete(lastRecord); + FloatFieldExtendedModel model = last(FloatFieldExtendedModel.class); + + if (null != model) { + assertEquals(third, model.getFloat()); + } + } + + @Test + public void nullFirstExtendedTest() { + assertNull(first(FloatFieldExtendedModel.class)); + } + + @Test + public void nullLastExtendedTest() { + assertNull(last(FloatFieldExtendedModel.class)); + } + + @Test + public void oneItemExtendedTest() { + save(new FloatFieldExtendedModel(25F)); + + FloatFieldExtendedModel firstModel = first(FloatFieldExtendedModel.class); + FloatFieldExtendedModel lastModel = last(FloatFieldExtendedModel.class); + + if (null != firstModel && null != lastModel) { + assertEquals(firstModel.getFloat(), lastModel.getFloat()); + } + } + + @Test + public void firstAnnotatedTest() { + Float first = 25F; + + save(new FloatFieldAnnotatedModel(first)); + save(new FloatFieldAnnotatedModel(50F)); + + FloatFieldAnnotatedModel model = first(FloatFieldAnnotatedModel.class); + + if (null != model) { + assertEquals(first, model.getFloat()); + } + } + + @Test + public void firstDeletedRecordAnnotatedTest() { + Float second = 25F; + + save(new FloatFieldAnnotatedModel(15F)); + save(new FloatFieldAnnotatedModel(second)); + save(new FloatFieldAnnotatedModel(35F)); + save(new FloatFieldAnnotatedModel(45F)); + + FloatFieldAnnotatedModel firstRecord = findById(FloatFieldAnnotatedModel.class, 1); + + delete(firstRecord); + + FloatFieldAnnotatedModel model = first(FloatFieldAnnotatedModel.class); + + if (null != model) { + assertEquals(second, model.getFloat()); + } + } + + @Test + public void lastAnnotatedTest() { + Float last = 50F; + + save(new FloatFieldAnnotatedModel(25F)); + save(new FloatFieldAnnotatedModel(last)); + + FloatFieldAnnotatedModel model = last(FloatFieldAnnotatedModel.class); + + if (null != model) { + assertEquals(last, model.getFloat()); + } + } + + @Test + public void lastDeletedRecordAnnotatedTest() { + Float third = 35F; + + save(new FloatFieldAnnotatedModel(15F)); + save(new FloatFieldAnnotatedModel(25F)); + save(new FloatFieldAnnotatedModel(third)); + save(new FloatFieldAnnotatedModel(45F)); + + FloatFieldAnnotatedModel lastRecord = findById(FloatFieldAnnotatedModel.class, 4); + delete(lastRecord); + FloatFieldAnnotatedModel model = last(FloatFieldAnnotatedModel.class); + + if (null != model) { + assertEquals(third, model.getFloat()); + } + } + + @Test + public void nullFirstAnnotatedTest() { + assertNull(first(FloatFieldAnnotatedModel.class)); + } + + @Test + public void nullLastAnnotatedTest() { + assertNull(last(FloatFieldAnnotatedModel.class)); + } + + @Test + public void oneItemAnnotatedTest() { + save(new FloatFieldAnnotatedModel(25F)); + + FloatFieldAnnotatedModel first = first(FloatFieldAnnotatedModel.class); + FloatFieldAnnotatedModel last = last(FloatFieldAnnotatedModel.class); + + if (null != first && null != last) { + assertEquals(first.getFloat(), last.getFloat()); + } + } +} diff --git a/library/src/test/java/com/orm/record/FloatFieldTests.java b/library/src/test/java/com/orm/record/FloatFieldTests.java new file mode 100644 index 00000000..d76516b9 --- /dev/null +++ b/library/src/test/java/com/orm/record/FloatFieldTests.java @@ -0,0 +1,80 @@ +package com.orm.record; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.FloatFieldAnnotatedModel; +import com.orm.model.FloatFieldExtendedModel; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.findById; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +@SuppressWarnings("all") +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class FloatFieldTests { + Float aFloat = Float.valueOf(25F); + + @Test + public void nullFloatExtendedTest() { + save(new FloatFieldExtendedModel()); + FloatFieldExtendedModel model = findById(FloatFieldExtendedModel.class, 1); + assertNull(model.getFloat()); + } + + @Test + public void nullRawFloatExtendedTest() { + save(new FloatFieldExtendedModel()); + FloatFieldExtendedModel model = findById(FloatFieldExtendedModel.class, 1); + assertEquals(0F, model.getRawFloat(), 0.0000000001F); + } + + @Test + public void nullFloatAnnotatedTest() { + save(new FloatFieldAnnotatedModel()); + FloatFieldAnnotatedModel model = findById(FloatFieldAnnotatedModel.class, 1); + assertNull(model.getFloat()); + } + + @Test + public void nullRawFloatAnnotatedTest() { + save(new FloatFieldAnnotatedModel()); + FloatFieldAnnotatedModel model = findById(FloatFieldAnnotatedModel.class, 1); + assertEquals(0F, model.getRawFloat(), 0.0000000001F); + } + + @Test + public void objectFloatExtendedTest() { + save(new FloatFieldExtendedModel(aFloat)); + FloatFieldExtendedModel model = findById(FloatFieldExtendedModel.class, 1); + assertEquals(aFloat, model.getFloat()); + } + + @Test + public void rawFloatExtendedTest() { + save(new FloatFieldExtendedModel(aFloat.floatValue())); + FloatFieldExtendedModel model = findById(FloatFieldExtendedModel.class, 1); + assertEquals(aFloat.floatValue(), model.getRawFloat(), 0.0000000001F); + } + + @Test + public void objectFloatAnnotatedTest() { + save(new FloatFieldAnnotatedModel(aFloat)); + FloatFieldAnnotatedModel model = findById(FloatFieldAnnotatedModel.class, 1); + assertEquals(aFloat, model.getFloat()); + } + + @Test + public void rawFloatAnnotatedTest() { + save(new FloatFieldAnnotatedModel(aFloat.floatValue())); + FloatFieldAnnotatedModel model = findById(FloatFieldAnnotatedModel.class, 1); + assertEquals(aFloat.floatValue(), model.getRawFloat(), 0.0000000001F); + } +} diff --git a/example/src/test/java/com/example/sugartest/IncompleteAnnotatedModelTests.java b/library/src/test/java/com/orm/record/IncompleteAnnotatedModelTests.java similarity index 56% rename from example/src/test/java/com/example/sugartest/IncompleteAnnotatedModelTests.java rename to library/src/test/java/com/orm/record/IncompleteAnnotatedModelTests.java index 25f544ae..0053ed96 100644 --- a/example/src/test/java/com/example/sugartest/IncompleteAnnotatedModelTests.java +++ b/library/src/test/java/com/orm/record/IncompleteAnnotatedModelTests.java @@ -1,22 +1,26 @@ -package com.example.sugartest; - +package com.orm.record; import android.database.sqlite.SQLiteException; -import com.example.models.IncompleteAnnotatedModel; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.IncompleteAnnotatedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import static com.orm.SugarRecord.delete; import static com.orm.SugarRecord.save; + import static org.junit.Assert.assertFalse; @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class IncompleteAnnotatedModelTests { - @Test(expected=SQLiteException.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class IncompleteAnnotatedModelTests { + + @Test(expected = SQLiteException.class) public void saveNoIdFieldTest() { save(new IncompleteAnnotatedModel()); } diff --git a/library/src/test/java/com/orm/record/IntegerFieldTests.java b/library/src/test/java/com/orm/record/IntegerFieldTests.java new file mode 100644 index 00000000..faf5fa84 --- /dev/null +++ b/library/src/test/java/com/orm/record/IntegerFieldTests.java @@ -0,0 +1,107 @@ +package com.orm.record; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.IntegerFieldAnnotatedModel; +import com.orm.model.IntegerFieldExtendedModel; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import static com.orm.SugarRecord.findById; +import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.sum; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class IntegerFieldTests { + private Integer integer = 25; + + @Test + public void nullIntegerExtendedTest() { + save(new IntegerFieldExtendedModel()); + IntegerFieldExtendedModel model = findById(IntegerFieldExtendedModel.class, 1); + assertNull(model.getInteger()); + } + + @Test + public void nullIntExtendedTest() { + save(new IntegerFieldExtendedModel()); + IntegerFieldExtendedModel model = findById(IntegerFieldExtendedModel.class, 1); + assertEquals(0, model.getInt()); + } + + @Test + public void nullIntegerAnnotatedTest() { + save(new IntegerFieldAnnotatedModel()); + IntegerFieldAnnotatedModel model = findById(IntegerFieldAnnotatedModel.class, 1); + assertNull(model.getInteger()); + } + + @Test + public void nullIntAnnotatedTest() { + save(new IntegerFieldAnnotatedModel()); + IntegerFieldAnnotatedModel model = findById(IntegerFieldAnnotatedModel.class, 1); + assertEquals(0, model.getInt()); + } + + @Test + public void integerExtendedTest() { + save(new IntegerFieldExtendedModel(integer)); + IntegerFieldExtendedModel model = findById(IntegerFieldExtendedModel.class, 1); + assertEquals(integer, model.getInteger()); + } + + @Test + public void intExtendedTest() { + save(new IntegerFieldExtendedModel(integer.intValue())); + IntegerFieldExtendedModel model = findById(IntegerFieldExtendedModel.class, 1); + assertEquals(integer.intValue(), model.getInt()); + } + + @Test + public void integerAnnotatedTest() { + save(new IntegerFieldAnnotatedModel(integer)); + IntegerFieldAnnotatedModel model = findById(IntegerFieldAnnotatedModel.class, 1); + assertEquals(integer, model.getInteger()); + } + + @Test + public void intAnnotatedTest() { + save(new IntegerFieldAnnotatedModel(integer.intValue())); + IntegerFieldAnnotatedModel model = findById(IntegerFieldAnnotatedModel.class, 1); + assertEquals(integer.intValue(), model.getInt()); + } + + + @Test + public void sumTest() { + save(new IntegerFieldAnnotatedModel(integer.intValue())); + save(new IntegerFieldAnnotatedModel(integer.intValue())); + assertEquals(2 * integer, sum(IntegerFieldAnnotatedModel.class, "raw_integer")); + } + + @Test + public void whereSumTest() { + save(new IntegerFieldAnnotatedModel(integer.intValue())); + save(new IntegerFieldAnnotatedModel(integer.intValue())); + assertEquals((long) integer, sum(IntegerFieldAnnotatedModel.class, + "raw_integer", "id = ?", "1")); + } + + @Test + public void noSumTest() { + assertEquals(0, sum(IntegerFieldAnnotatedModel.class, "raw_integer")); + } + + @Test + public void brokenSumTest() { + save(new IntegerFieldAnnotatedModel(integer.intValue())); + save(new IntegerFieldAnnotatedModel(integer.intValue())); + assertEquals(-1, sum(IntegerFieldAnnotatedModel.class, "wrongfield")); + } +} diff --git a/library/src/test/java/com/orm/record/ListAllOrderByTests.java b/library/src/test/java/com/orm/record/ListAllOrderByTests.java new file mode 100644 index 00000000..548ead23 --- /dev/null +++ b/library/src/test/java/com/orm/record/ListAllOrderByTests.java @@ -0,0 +1,62 @@ +package com.orm.record; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.IntegerFieldExtendedModel; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.util.List; + +import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.listAll; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class ListAllOrderByTests { + + @Test + public void listAllOrderByEmptyTest() { + final List list = listAll(IntegerFieldExtendedModel.class, "id"); + assertEquals(0L, list.size()); + } + + @Test + public void listAllOrderByIdTest() { + for (int i = 1; i <= 100; i++) { + save(new IntegerFieldExtendedModel(i)); + } + + List models = listAll(IntegerFieldExtendedModel.class, "id"); + assertEquals(100L, models.size()); + + Long id = models.get(0).getId(); + + for (int i = 1; i < 100; i++) { + assertTrue(id < models.get(i).getId()); + } + } + + @Test + public void listAllOrderByFieldTest() { + for (int i = 1; i <= 100; i++) { + save(new IntegerFieldExtendedModel(i)); + } + + List models = listAll(IntegerFieldExtendedModel.class, "raw_integer"); + + assertEquals(100L, models.size()); + + int raw = models.get(0).getInt(); + + for (int i = 1; i < 100; i++) { + assertTrue(raw < models.get(i).getInt()); + } + } +} diff --git a/library/src/test/java/com/orm/record/LongFieldTests.java b/library/src/test/java/com/orm/record/LongFieldTests.java new file mode 100644 index 00000000..d1516a42 --- /dev/null +++ b/library/src/test/java/com/orm/record/LongFieldTests.java @@ -0,0 +1,80 @@ +package com.orm.record; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.LongFieldAnnotatedModel; +import com.orm.model.LongFieldExtendedModel; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.findById; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +@SuppressWarnings("all") +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class LongFieldTests { + private Long aLong = Long.valueOf(25L); + + @Test + public void nullLongExtendedTest() { + save(new LongFieldExtendedModel()); + LongFieldExtendedModel model = findById(LongFieldExtendedModel.class, 1); + assertNull(model.getLong()); + } + + @Test + public void nullRawLongExtendedTest() { + save(new LongFieldExtendedModel()); + LongFieldExtendedModel model = findById(LongFieldExtendedModel.class, 1); + assertEquals(0L, model.getRawLong()); + } + + @Test + public void nullLongAnnotatedTest() { + save(new LongFieldAnnotatedModel()); + LongFieldAnnotatedModel model = findById(LongFieldAnnotatedModel.class, 1); + assertNull(model.getLong()); + } + + @Test + public void nullRawLongAnnotatedTest() { + save(new LongFieldAnnotatedModel()); + LongFieldAnnotatedModel model = findById(LongFieldAnnotatedModel.class, 1); + assertEquals(0L, model.getRawLong()); + } + + @Test + public void objectLongExtendedTest() { + save(new LongFieldExtendedModel(aLong)); + LongFieldExtendedModel model = findById(LongFieldExtendedModel.class, 1); + assertEquals(aLong, model.getLong()); + } + + @Test + public void rawLongExtendedTest() { + save(new LongFieldExtendedModel(aLong.longValue())); + LongFieldExtendedModel model = findById(LongFieldExtendedModel.class, 1); + assertEquals(aLong.longValue(), model.getRawLong()); + } + + @Test + public void objectLongAnnotatedTest() { + save(new LongFieldAnnotatedModel(aLong)); + LongFieldAnnotatedModel model = findById(LongFieldAnnotatedModel.class, 1); + assertEquals(aLong, model.getLong()); + } + + @Test + public void rawLongAnnotatedTest() { + save(new LongFieldAnnotatedModel(aLong.longValue())); + LongFieldAnnotatedModel model = findById(LongFieldAnnotatedModel.class, 1); + assertEquals(aLong.longValue(), model.getRawLong()); + } +} diff --git a/library/src/test/java/com/orm/record/MultipleSaveTests.java b/library/src/test/java/com/orm/record/MultipleSaveTests.java new file mode 100644 index 00000000..73b353ad --- /dev/null +++ b/library/src/test/java/com/orm/record/MultipleSaveTests.java @@ -0,0 +1,111 @@ +package com.orm.record; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.StringFieldAnnotatedModel; +import com.orm.model.StringFieldAnnotatedNoIdModel; +import com.orm.model.StringFieldExtendedModel; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.findById; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class MultipleSaveTests { + private String testString = "Test String"; + private String anotherString = "Another test"; + + @Test + public void stringMultipleSaveOriginalExtendedTest() { + StringFieldExtendedModel model = new StringFieldExtendedModel(testString); + long id = save(model); + StringFieldExtendedModel query = findById(StringFieldExtendedModel.class, id); + + if (null != query) { + assertEquals(testString, query.getString()); + } + + model.setString(anotherString); + + assertEquals(id, save(model)); + assertNull(findById(StringFieldExtendedModel.class, 2)); + } + + @Test + public void stringMultipleSaveQueriedExtendedTest() { + StringFieldExtendedModel model = new StringFieldExtendedModel(testString); + long id = save(model); + StringFieldExtendedModel query = findById(StringFieldExtendedModel.class, id); + + if (null != query) { + assertEquals(testString, query.getString()); + query.setString(anotherString); + assertEquals(id, save(query)); + assertNull(findById(StringFieldExtendedModel.class, 2)); + } + } + + @Test + public void stringMultipleSaveOriginalAnnotatedTest() { + StringFieldAnnotatedModel model = new StringFieldAnnotatedModel(testString); + long id = save(model); + StringFieldAnnotatedModel query = findById(StringFieldAnnotatedModel.class, id); + + if (null != query) { + assertEquals(testString, query.getString()); + model.setString(anotherString); + assertEquals(id, save(model)); + assertNull(findById(StringFieldAnnotatedModel.class, 2)); + } + } + + @Test + public void stringMultipleSaveQueriedAnnotatedTest() { + StringFieldAnnotatedModel model = new StringFieldAnnotatedModel(testString); + long id = save(model); + StringFieldAnnotatedModel query = findById(StringFieldAnnotatedModel.class, id); + + if (null != query) { + assertEquals(testString, query.getString()); + query.setString(anotherString); + assertEquals(id, save(query)); + assertNull(findById(StringFieldAnnotatedModel.class, 2)); + } + } + + @Test + public void stringMultipleSaveOriginalAnnotatedNoIdTest() { + StringFieldAnnotatedNoIdModel model = new StringFieldAnnotatedNoIdModel(testString); + long id = save(model); + StringFieldAnnotatedNoIdModel query = findById(StringFieldAnnotatedNoIdModel.class, id); + + if (null != query) { + assertEquals(testString, query.getString()); + model.setString(anotherString); + assertEquals(id, save(model)); + assertNull(findById(StringFieldAnnotatedNoIdModel.class, 2)); + } + } + + @Test + public void stringMultipleSaveQueriedAnnotatedNoIdTest() { + StringFieldAnnotatedNoIdModel model = new StringFieldAnnotatedNoIdModel(testString); + long id = save(model); + StringFieldAnnotatedNoIdModel query = findById(StringFieldAnnotatedNoIdModel.class, id); + + if (null != query) { + assertEquals(testString, query.getString()); + query.setString(anotherString); + assertEquals(id, save(query)); + assertNull(findById(StringFieldAnnotatedNoIdModel.class, 2)); + } + } +} diff --git a/example/src/test/java/com/example/sugartest/NestedAnnotatedTests.java b/library/src/test/java/com/orm/record/NestedAnnotatedTests.java similarity index 61% rename from example/src/test/java/com/example/sugartest/NestedAnnotatedTests.java rename to library/src/test/java/com/orm/record/NestedAnnotatedTests.java index bf3f0e46..d7c8ef43 100644 --- a/example/src/test/java/com/example/sugartest/NestedAnnotatedTests.java +++ b/library/src/test/java/com/orm/record/NestedAnnotatedTests.java @@ -1,28 +1,33 @@ -package com.example.sugartest; +package com.orm.record; -import com.example.models.NestedAnnotatedModel; -import com.example.models.RelationshipAnnotatedModel; -import com.example.models.SimpleAnnotatedModel; -import com.orm.SugarRecord; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.NestedAnnotatedModel; +import com.orm.model.RelationshipAnnotatedModel; +import com.orm.model.SimpleAnnotatedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import java.util.List; import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; +import static com.orm.SugarRecord.count; +import static com.orm.SugarRecord.listAll; +import static org.junit.Assert.assertEquals; @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class NestedAnnotatedTests { +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class NestedAnnotatedTests { + @Test public void emptyDatabaseTest() throws Exception { - assertEquals(0L, SugarRecord.count(NestedAnnotatedModel.class)); - assertEquals(0L, SugarRecord.count(RelationshipAnnotatedModel.class)); - assertEquals(0L, SugarRecord.count(SimpleAnnotatedModel.class)); + assertEquals(0L, count(NestedAnnotatedModel.class)); + assertEquals(0L, count(RelationshipAnnotatedModel.class)); + assertEquals(0L, count(SimpleAnnotatedModel.class)); } @Test @@ -32,9 +37,9 @@ public void oneSaveTest() throws Exception { RelationshipAnnotatedModel nested = new RelationshipAnnotatedModel(simple); save(nested); save(new NestedAnnotatedModel(nested)); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipAnnotatedModel.class)); - assertEquals(1L, SugarRecord.count(NestedAnnotatedModel.class)); + assertEquals(1L, count(SimpleAnnotatedModel.class)); + assertEquals(1L, count(RelationshipAnnotatedModel.class)); + assertEquals(1L, count(NestedAnnotatedModel.class)); } @Test @@ -45,26 +50,27 @@ public void twoSameSaveTest() throws Exception { save(nested); save(new NestedAnnotatedModel(nested)); save(new NestedAnnotatedModel(nested)); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipAnnotatedModel.class)); - assertEquals(2L, SugarRecord.count(NestedAnnotatedModel.class)); + + assertEquals(1L, count(SimpleAnnotatedModel.class)); + assertEquals(1L, count(RelationshipAnnotatedModel.class)); + assertEquals(2L, count(NestedAnnotatedModel.class)); } @Test public void twoDifferentSaveTest() throws Exception { SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); save(simple); - SimpleAnnotatedModel another_simple = new SimpleAnnotatedModel(); - save(another_simple); + SimpleAnnotatedModel anotherSimple = new SimpleAnnotatedModel(); + save(anotherSimple); RelationshipAnnotatedModel nested = new RelationshipAnnotatedModel(simple); save(nested); - RelationshipAnnotatedModel another_nested = new RelationshipAnnotatedModel(another_simple); - save(another_nested); + RelationshipAnnotatedModel anotherNested = new RelationshipAnnotatedModel(anotherSimple); + save(anotherNested); save(new NestedAnnotatedModel(nested)); - save(new NestedAnnotatedModel(another_nested)); - assertEquals(2L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(2L, SugarRecord.count(RelationshipAnnotatedModel.class)); - assertEquals(2L, SugarRecord.count(NestedAnnotatedModel.class)); + save(new NestedAnnotatedModel(anotherNested)); + assertEquals(2L, count(SimpleAnnotatedModel.class)); + assertEquals(2L, count(RelationshipAnnotatedModel.class)); + assertEquals(2L, count(NestedAnnotatedModel.class)); } @Test @@ -76,9 +82,9 @@ public void manySameSaveTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new NestedAnnotatedModel(nested)); } - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipAnnotatedModel.class)); - assertEquals(100L, SugarRecord.count(NestedAnnotatedModel.class)); + assertEquals(1L, count(SimpleAnnotatedModel.class)); + assertEquals(1L, count(RelationshipAnnotatedModel.class)); + assertEquals(100L, count(NestedAnnotatedModel.class)); } @Test @@ -90,9 +96,9 @@ public void manyDifferentSaveTest() throws Exception { save(nested); save(new NestedAnnotatedModel(nested)); } - assertEquals(100L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(100L, SugarRecord.count(RelationshipAnnotatedModel.class)); - assertEquals(100L, SugarRecord.count(NestedAnnotatedModel.class)); + assertEquals(100L, count(SimpleAnnotatedModel.class)); + assertEquals(100L, count(RelationshipAnnotatedModel.class)); + assertEquals(100L, count(NestedAnnotatedModel.class)); } @Test @@ -101,11 +107,14 @@ public void listAllSameTest() throws Exception { save(simple); RelationshipAnnotatedModel nested = new RelationshipAnnotatedModel(simple); save(nested); + for (int i = 1; i <= 100; i++) { save(new NestedAnnotatedModel(nested)); } - List models = SugarRecord.listAll(NestedAnnotatedModel.class); + + List models = listAll(NestedAnnotatedModel.class); assertEquals(100, models.size()); + for (NestedAnnotatedModel model : models) { assertEquals(nested.getId(), model.getNested().getId()); assertEquals(simple.getId(), model.getNested().getSimple().getId()); @@ -121,8 +130,10 @@ public void listAllDifferentTest() throws Exception { save(nested); save(new NestedAnnotatedModel(nested)); } - List models = SugarRecord.listAll(NestedAnnotatedModel.class); + + List models = listAll(NestedAnnotatedModel.class); assertEquals(100, models.size()); + for (NestedAnnotatedModel model : models) { assertEquals(model.getId(), model.getNested().getId()); assertEquals(model.getId(), model.getNested().getSimple().getId()); diff --git a/example/src/test/java/com/example/sugartest/NestedExtendedTests.java b/library/src/test/java/com/orm/record/NestedExtendedTests.java similarity index 61% rename from example/src/test/java/com/example/sugartest/NestedExtendedTests.java rename to library/src/test/java/com/orm/record/NestedExtendedTests.java index f403784b..eaf8c120 100644 --- a/example/src/test/java/com/example/sugartest/NestedExtendedTests.java +++ b/library/src/test/java/com/orm/record/NestedExtendedTests.java @@ -1,28 +1,33 @@ -package com.example.sugartest; +package com.orm.record; -import com.example.models.NestedExtendedModel; -import com.example.models.RelationshipExtendedModel; -import com.example.models.SimpleExtendedModel; -import com.orm.SugarRecord; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.NestedExtendedModel; +import com.orm.model.RelationshipExtendedModel; +import com.orm.model.SimpleExtendedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import java.util.List; import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; +import static com.orm.SugarRecord.count; +import static com.orm.SugarRecord.listAll; +import static org.junit.Assert.assertEquals; @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class NestedExtendedTests { +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class NestedExtendedTests { + @Test public void emptyDatabaseTest() throws Exception { - assertEquals(0L, SugarRecord.count(NestedExtendedModel.class)); - assertEquals(0L, SugarRecord.count(RelationshipExtendedModel.class)); - assertEquals(0L, SugarRecord.count(SimpleExtendedModel.class)); + assertEquals(0L, count(NestedExtendedModel.class)); + assertEquals(0L, count(RelationshipExtendedModel.class)); + assertEquals(0L, count(SimpleExtendedModel.class)); } @Test @@ -32,9 +37,9 @@ public void oneSaveTest() throws Exception { RelationshipExtendedModel nested = new RelationshipExtendedModel(simple); save(nested); save(new NestedExtendedModel(nested)); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipExtendedModel.class)); - assertEquals(1L, SugarRecord.count(NestedExtendedModel.class)); + assertEquals(1L, count(SimpleExtendedModel.class)); + assertEquals(1L, count(RelationshipExtendedModel.class)); + assertEquals(1L, count(NestedExtendedModel.class)); } @Test @@ -45,26 +50,26 @@ public void twoSameSaveTest() throws Exception { save(nested); save(new NestedExtendedModel(nested)); save(new NestedExtendedModel(nested)); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipExtendedModel.class)); - assertEquals(2L, SugarRecord.count(NestedExtendedModel.class)); + assertEquals(1L, count(SimpleExtendedModel.class)); + assertEquals(1L, count(RelationshipExtendedModel.class)); + assertEquals(2L, count(NestedExtendedModel.class)); } @Test public void twoDifferentSaveTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); save(simple); - SimpleExtendedModel another_simple = new SimpleExtendedModel(); - save(another_simple); + SimpleExtendedModel anotherSimple = new SimpleExtendedModel(); + save(anotherSimple); RelationshipExtendedModel nested = new RelationshipExtendedModel(simple); save(nested); - RelationshipExtendedModel another_nested = new RelationshipExtendedModel(another_simple); - save(another_nested); + RelationshipExtendedModel anotherNested = new RelationshipExtendedModel(anotherSimple); + save(anotherNested); save(new NestedExtendedModel(nested)); - save(new NestedExtendedModel(another_nested)); - assertEquals(2L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(2L, SugarRecord.count(RelationshipExtendedModel.class)); - assertEquals(2L, SugarRecord.count(NestedExtendedModel.class)); + save(new NestedExtendedModel(anotherNested)); + assertEquals(2L, count(SimpleExtendedModel.class)); + assertEquals(2L, count(RelationshipExtendedModel.class)); + assertEquals(2L, count(NestedExtendedModel.class)); } @Test @@ -76,9 +81,9 @@ public void manySameSaveTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new NestedExtendedModel(nested)); } - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipExtendedModel.class)); - assertEquals(100L, SugarRecord.count(NestedExtendedModel.class)); + assertEquals(1L, count(SimpleExtendedModel.class)); + assertEquals(1L, count(RelationshipExtendedModel.class)); + assertEquals(100L, count(NestedExtendedModel.class)); } @Test @@ -90,9 +95,9 @@ public void manyDifferentSaveTest() throws Exception { save(nested); save(new NestedExtendedModel(nested)); } - assertEquals(100L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(100L, SugarRecord.count(RelationshipExtendedModel.class)); - assertEquals(100L, SugarRecord.count(NestedExtendedModel.class)); + assertEquals(100L, count(SimpleExtendedModel.class)); + assertEquals(100L, count(RelationshipExtendedModel.class)); + assertEquals(100L, count(NestedExtendedModel.class)); } @Test @@ -104,8 +109,10 @@ public void listAllSameTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new NestedExtendedModel(nested)); } - List models = SugarRecord.listAll(NestedExtendedModel.class); + + List models = listAll(NestedExtendedModel.class); assertEquals(100, models.size()); + for (NestedExtendedModel model : models) { assertEquals(nested.getId(), model.getNested().getId()); assertEquals(simple.getId(), model.getNested().getSimple().getId()); @@ -121,8 +128,10 @@ public void listAllDifferentTest() throws Exception { save(nested); save(new NestedExtendedModel(nested)); } - List models = SugarRecord.listAll(NestedExtendedModel.class); + + List models = listAll(NestedExtendedModel.class); assertEquals(100, models.size()); + for (NestedExtendedModel model : models) { assertEquals(model.getId(), model.getNested().getId()); assertEquals(model.getId(), model.getNested().getSimple().getId()); diff --git a/example/src/test/java/com/example/sugartest/NestedMixedAATests.java b/library/src/test/java/com/orm/record/NestedMixedAATests.java similarity index 61% rename from example/src/test/java/com/example/sugartest/NestedMixedAATests.java rename to library/src/test/java/com/orm/record/NestedMixedAATests.java index daf19272..9daf3fa9 100644 --- a/example/src/test/java/com/example/sugartest/NestedMixedAATests.java +++ b/library/src/test/java/com/orm/record/NestedMixedAATests.java @@ -1,28 +1,33 @@ -package com.example.sugartest; +package com.orm.record; -import com.example.models.NestedMixedAAModel; -import com.example.models.RelationshipMixedAModel; -import com.example.models.SimpleAnnotatedModel; -import com.orm.SugarRecord; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.NestedMixedAAModel; +import com.orm.model.RelationshipMixedAModel; +import com.orm.model.SimpleAnnotatedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import java.util.List; import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; +import static com.orm.SugarRecord.count; +import static com.orm.SugarRecord.listAll; +import static org.junit.Assert.assertEquals; @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class NestedMixedAATests { +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class NestedMixedAATests { + @Test public void emptyDatabaseTest() throws Exception { - assertEquals(0L, SugarRecord.count(NestedMixedAAModel.class)); - assertEquals(0L, SugarRecord.count(RelationshipMixedAModel.class)); - assertEquals(0L, SugarRecord.count(SimpleAnnotatedModel.class)); + assertEquals(0L, count(NestedMixedAAModel.class)); + assertEquals(0L, count(RelationshipMixedAModel.class)); + assertEquals(0L, count(SimpleAnnotatedModel.class)); } @Test @@ -32,9 +37,9 @@ public void oneSaveTest() throws Exception { RelationshipMixedAModel nested = new RelationshipMixedAModel(simple); save(nested); save(new NestedMixedAAModel(nested)); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipMixedAModel.class)); - assertEquals(1L, SugarRecord.count(NestedMixedAAModel.class)); + assertEquals(1L, count(SimpleAnnotatedModel.class)); + assertEquals(1L, count(RelationshipMixedAModel.class)); + assertEquals(1L, count(NestedMixedAAModel.class)); } @Test @@ -45,26 +50,26 @@ public void twoSameSaveTest() throws Exception { save(nested); save(new NestedMixedAAModel(nested)); save(new NestedMixedAAModel(nested)); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipMixedAModel.class)); - assertEquals(2L, SugarRecord.count(NestedMixedAAModel.class)); + assertEquals(1L, count(SimpleAnnotatedModel.class)); + assertEquals(1L, count(RelationshipMixedAModel.class)); + assertEquals(2L, count(NestedMixedAAModel.class)); } @Test public void twoDifferentSaveTest() throws Exception { SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); save(simple); - SimpleAnnotatedModel another_simple = new SimpleAnnotatedModel(); - save(another_simple); + SimpleAnnotatedModel anotherSimple = new SimpleAnnotatedModel(); + save(anotherSimple); RelationshipMixedAModel nested = new RelationshipMixedAModel(simple); save(nested); - RelationshipMixedAModel another_nested = new RelationshipMixedAModel(another_simple); - save(another_nested); + RelationshipMixedAModel anotherNested = new RelationshipMixedAModel(anotherSimple); + save(anotherNested); save(new NestedMixedAAModel(nested)); - save(new NestedMixedAAModel(another_nested)); - assertEquals(2L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(2L, SugarRecord.count(RelationshipMixedAModel.class)); - assertEquals(2L, SugarRecord.count(NestedMixedAAModel.class)); + save(new NestedMixedAAModel(anotherNested)); + assertEquals(2L, count(SimpleAnnotatedModel.class)); + assertEquals(2L, count(RelationshipMixedAModel.class)); + assertEquals(2L, count(NestedMixedAAModel.class)); } @Test @@ -76,9 +81,9 @@ public void manySameSaveTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new NestedMixedAAModel(nested)); } - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipMixedAModel.class)); - assertEquals(100L, SugarRecord.count(NestedMixedAAModel.class)); + assertEquals(1L, count(SimpleAnnotatedModel.class)); + assertEquals(1L, count(RelationshipMixedAModel.class)); + assertEquals(100L, count(NestedMixedAAModel.class)); } @Test @@ -90,9 +95,9 @@ public void manyDifferentSaveTest() throws Exception { save(nested); save(new NestedMixedAAModel(nested)); } - assertEquals(100L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(100L, SugarRecord.count(RelationshipMixedAModel.class)); - assertEquals(100L, SugarRecord.count(NestedMixedAAModel.class)); + assertEquals(100L, count(SimpleAnnotatedModel.class)); + assertEquals(100L, count(RelationshipMixedAModel.class)); + assertEquals(100L, count(NestedMixedAAModel.class)); } @Test @@ -101,11 +106,14 @@ public void listAllSameTest() throws Exception { save(simple); RelationshipMixedAModel nested = new RelationshipMixedAModel(simple); save(nested); + for (int i = 1; i <= 100; i++) { save(new NestedMixedAAModel(nested)); } - List models = SugarRecord.listAll(NestedMixedAAModel.class); + + List models = listAll(NestedMixedAAModel.class); assertEquals(100, models.size()); + for (NestedMixedAAModel model : models) { assertEquals(nested.getId(), model.getNested().getId()); assertEquals(simple.getId(), model.getNested().getSimple().getId()); @@ -121,8 +129,10 @@ public void listAllDifferentTest() throws Exception { save(nested); save(new NestedMixedAAModel(nested)); } - List models = SugarRecord.listAll(NestedMixedAAModel.class); + + List models = listAll(NestedMixedAAModel.class); assertEquals(100, models.size()); + for (NestedMixedAAModel model : models) { assertEquals(model.getId(), model.getNested().getId()); assertEquals(model.getId(), model.getNested().getSimple().getId()); diff --git a/example/src/test/java/com/example/sugartest/NestedMixedABTests.java b/library/src/test/java/com/orm/record/NestedMixedABTests.java similarity index 61% rename from example/src/test/java/com/example/sugartest/NestedMixedABTests.java rename to library/src/test/java/com/orm/record/NestedMixedABTests.java index 5b9a70dc..fa16b506 100644 --- a/example/src/test/java/com/example/sugartest/NestedMixedABTests.java +++ b/library/src/test/java/com/orm/record/NestedMixedABTests.java @@ -1,28 +1,33 @@ -package com.example.sugartest; +package com.orm.record; -import com.example.models.NestedMixedABModel; -import com.example.models.RelationshipMixedBModel; -import com.example.models.SimpleExtendedModel; -import com.orm.SugarRecord; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.NestedMixedABModel; +import com.orm.model.RelationshipMixedBModel; +import com.orm.model.SimpleExtendedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import java.util.List; import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; +import static com.orm.SugarRecord.count; +import static com.orm.SugarRecord.listAll; +import static org.junit.Assert.assertEquals; @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) public class NestedMixedABTests { + @Test public void emptyDatabaseTest() throws Exception { - assertEquals(0L, SugarRecord.count(NestedMixedABModel.class)); - assertEquals(0L, SugarRecord.count(RelationshipMixedBModel.class)); - assertEquals(0L, SugarRecord.count(SimpleExtendedModel.class)); + assertEquals(0L, count(NestedMixedABModel.class)); + assertEquals(0L, count(RelationshipMixedBModel.class)); + assertEquals(0L, count(SimpleExtendedModel.class)); } @Test @@ -30,11 +35,13 @@ public void oneSaveTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); save(simple); RelationshipMixedBModel nested = new RelationshipMixedBModel(simple); + save(nested); save(new NestedMixedABModel(nested)); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipMixedBModel.class)); - assertEquals(1L, SugarRecord.count(NestedMixedABModel.class)); + + assertEquals(1L, count(SimpleExtendedModel.class)); + assertEquals(1L, count(RelationshipMixedBModel.class)); + assertEquals(1L, count(NestedMixedABModel.class)); } @Test @@ -42,29 +49,33 @@ public void twoSameSaveTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); save(simple); RelationshipMixedBModel nested = new RelationshipMixedBModel(simple); + save(nested); save(new NestedMixedABModel(nested)); save(new NestedMixedABModel(nested)); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipMixedBModel.class)); - assertEquals(2L, SugarRecord.count(NestedMixedABModel.class)); + + assertEquals(1L, count(SimpleExtendedModel.class)); + assertEquals(1L, count(RelationshipMixedBModel.class)); + assertEquals(2L, count(NestedMixedABModel.class)); } @Test public void twoDifferentSaveTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); save(simple); - SimpleExtendedModel another_simple = new SimpleExtendedModel(); - save(another_simple); + SimpleExtendedModel anotherSimple = new SimpleExtendedModel(); + save(anotherSimple); RelationshipMixedBModel nested = new RelationshipMixedBModel(simple); save(nested); - RelationshipMixedBModel another_nested = new RelationshipMixedBModel(another_simple); - save(another_nested); + RelationshipMixedBModel anotherNested = new RelationshipMixedBModel(anotherSimple); + + save(anotherNested); save(new NestedMixedABModel(nested)); - save(new NestedMixedABModel(another_nested)); - assertEquals(2L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(2L, SugarRecord.count(RelationshipMixedBModel.class)); - assertEquals(2L, SugarRecord.count(NestedMixedABModel.class)); + save(new NestedMixedABModel(anotherNested)); + + assertEquals(2L, count(SimpleExtendedModel.class)); + assertEquals(2L, count(RelationshipMixedBModel.class)); + assertEquals(2L, count(NestedMixedABModel.class)); } @Test @@ -73,12 +84,14 @@ public void manySameSaveTest() throws Exception { save(simple); RelationshipMixedBModel nested = new RelationshipMixedBModel(simple); save(nested); + for (int i = 1; i <= 100; i++) { save(new NestedMixedABModel(nested)); } - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipMixedBModel.class)); - assertEquals(100L, SugarRecord.count(NestedMixedABModel.class)); + + assertEquals(1L, count(SimpleExtendedModel.class)); + assertEquals(1L, count(RelationshipMixedBModel.class)); + assertEquals(100L, count(NestedMixedABModel.class)); } @Test @@ -90,9 +103,10 @@ public void manyDifferentSaveTest() throws Exception { save(nested); save(new NestedMixedABModel(nested)); } - assertEquals(100L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(100L, SugarRecord.count(RelationshipMixedBModel.class)); - assertEquals(100L, SugarRecord.count(NestedMixedABModel.class)); + + assertEquals(100L, count(SimpleExtendedModel.class)); + assertEquals(100L, count(RelationshipMixedBModel.class)); + assertEquals(100L, count(NestedMixedABModel.class)); } @Test @@ -101,11 +115,14 @@ public void listAllSameTest() throws Exception { save(simple); RelationshipMixedBModel nested = new RelationshipMixedBModel(simple); save(nested); + for (int i = 1; i <= 100; i++) { save(new NestedMixedABModel(nested)); } - List models = SugarRecord.listAll(NestedMixedABModel.class); + + List models = listAll(NestedMixedABModel.class); assertEquals(100, models.size()); + for (NestedMixedABModel model : models) { assertEquals(nested.getId(), model.getNested().getId()); assertEquals(simple.getId(), model.getNested().getSimple().getId()); @@ -121,8 +138,10 @@ public void listAllDifferentTest() throws Exception { save(nested); save(new NestedMixedABModel(nested)); } - List models = SugarRecord.listAll(NestedMixedABModel.class); + + List models = listAll(NestedMixedABModel.class); assertEquals(100, models.size()); + for (NestedMixedABModel model : models) { assertEquals(model.getId(), model.getNested().getId()); assertEquals(model.getId(), model.getNested().getSimple().getId()); diff --git a/example/src/test/java/com/example/sugartest/NestedMixedBATests.java b/library/src/test/java/com/orm/record/NestedMixedBATests.java similarity index 61% rename from example/src/test/java/com/example/sugartest/NestedMixedBATests.java rename to library/src/test/java/com/orm/record/NestedMixedBATests.java index 7d6e4886..c6f07da5 100644 --- a/example/src/test/java/com/example/sugartest/NestedMixedBATests.java +++ b/library/src/test/java/com/orm/record/NestedMixedBATests.java @@ -1,28 +1,34 @@ -package com.example.sugartest; +package com.orm.record; -import com.example.models.NestedMixedBAModel; -import com.example.models.RelationshipMixedAModel; -import com.example.models.SimpleAnnotatedModel; +import com.orm.app.ClientApp; import com.orm.SugarRecord; +import com.orm.dsl.BuildConfig; +import com.orm.model.NestedMixedBAModel; +import com.orm.model.RelationshipMixedAModel; +import com.orm.model.SimpleAnnotatedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import java.util.List; import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; +import static com.orm.SugarRecord.count; +import static com.orm.SugarRecord.listAll; +import static org.junit.Assert.assertEquals; @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class NestedMixedBATests { +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class NestedMixedBATests { + @Test public void emptyDatabaseTest() throws Exception { - assertEquals(0L, SugarRecord.count(NestedMixedBAModel.class)); - assertEquals(0L, SugarRecord.count(RelationshipMixedAModel.class)); - assertEquals(0L, SugarRecord.count(SimpleAnnotatedModel.class)); + assertEquals(0L, count(NestedMixedBAModel.class)); + assertEquals(0L, count(RelationshipMixedAModel.class)); + assertEquals(0L, count(SimpleAnnotatedModel.class)); } @Test @@ -30,11 +36,13 @@ public void oneSaveTest() throws Exception { SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); save(simple); RelationshipMixedAModel nested = new RelationshipMixedAModel(simple); + save(nested); save(new NestedMixedBAModel(nested)); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipMixedAModel.class)); - assertEquals(1L, SugarRecord.count(NestedMixedBAModel.class)); + + assertEquals(1L, count(SimpleAnnotatedModel.class)); + assertEquals(1L, count(RelationshipMixedAModel.class)); + assertEquals(1L, count(NestedMixedBAModel.class)); } @Test @@ -42,29 +50,33 @@ public void twoSameSaveTest() throws Exception { SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); save(simple); RelationshipMixedAModel nested = new RelationshipMixedAModel(simple); + save(nested); save(new NestedMixedBAModel(nested)); save(new NestedMixedBAModel(nested)); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipMixedAModel.class)); - assertEquals(2L, SugarRecord.count(NestedMixedBAModel.class)); + + assertEquals(1L, count(SimpleAnnotatedModel.class)); + assertEquals(1L, count(RelationshipMixedAModel.class)); + assertEquals(2L, count(NestedMixedBAModel.class)); } @Test public void twoDifferentSaveTest() throws Exception { SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); save(simple); - SimpleAnnotatedModel another_simple = new SimpleAnnotatedModel(); - save(another_simple); + SimpleAnnotatedModel anotherSimple = new SimpleAnnotatedModel(); + save(anotherSimple); RelationshipMixedAModel nested = new RelationshipMixedAModel(simple); save(nested); - RelationshipMixedAModel another_nested = new RelationshipMixedAModel(another_simple); - save(another_nested); + RelationshipMixedAModel anotherNested = new RelationshipMixedAModel(anotherSimple); + + save(anotherNested); save(new NestedMixedBAModel(nested)); - save(new NestedMixedBAModel(another_nested)); - assertEquals(2L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(2L, SugarRecord.count(RelationshipMixedAModel.class)); - assertEquals(2L, SugarRecord.count(NestedMixedBAModel.class)); + save(new NestedMixedBAModel(anotherNested)); + + assertEquals(2L, count(SimpleAnnotatedModel.class)); + assertEquals(2L, count(RelationshipMixedAModel.class)); + assertEquals(2L, count(NestedMixedBAModel.class)); } @Test @@ -73,12 +85,14 @@ public void manySameSaveTest() throws Exception { save(simple); RelationshipMixedAModel nested = new RelationshipMixedAModel(simple); save(nested); + for (int i = 1; i <= 100; i++) { save(new NestedMixedBAModel(nested)); } - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipMixedAModel.class)); - assertEquals(100L, SugarRecord.count(NestedMixedBAModel.class)); + + assertEquals(1L, count(SimpleAnnotatedModel.class)); + assertEquals(1L, count(RelationshipMixedAModel.class)); + assertEquals(100L, count(NestedMixedBAModel.class)); } @Test @@ -90,9 +104,10 @@ public void manyDifferentSaveTest() throws Exception { save(nested); save(new NestedMixedBAModel(nested)); } - assertEquals(100L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(100L, SugarRecord.count(RelationshipMixedAModel.class)); - assertEquals(100L, SugarRecord.count(NestedMixedBAModel.class)); + + assertEquals(100L, count(SimpleAnnotatedModel.class)); + assertEquals(100L, count(RelationshipMixedAModel.class)); + assertEquals(100L, count(NestedMixedBAModel.class)); } @Test @@ -101,11 +116,14 @@ public void listAllSameTest() throws Exception { save(simple); RelationshipMixedAModel nested = new RelationshipMixedAModel(simple); save(nested); + for (int i = 1; i <= 100; i++) { save(new NestedMixedBAModel(nested)); } - List models = SugarRecord.listAll(NestedMixedBAModel.class); + + List models = listAll(NestedMixedBAModel.class); assertEquals(100, models.size()); + for (NestedMixedBAModel model : models) { assertEquals(nested.getId(), model.getNested().getId()); assertEquals(simple.getId(), model.getNested().getSimple().getId()); @@ -121,8 +139,10 @@ public void listAllDifferentTest() throws Exception { save(nested); save(new NestedMixedBAModel(nested)); } - List models = SugarRecord.listAll(NestedMixedBAModel.class); + + List models = listAll(NestedMixedBAModel.class); assertEquals(100, models.size()); + for (NestedMixedBAModel model : models) { assertEquals(model.getId(), model.getNested().getId()); assertEquals(model.getId(), model.getNested().getSimple().getId()); diff --git a/example/src/test/java/com/example/sugartest/NestedMixedBBTests.java b/library/src/test/java/com/orm/record/NestedMixedBBTests.java similarity index 61% rename from example/src/test/java/com/example/sugartest/NestedMixedBBTests.java rename to library/src/test/java/com/orm/record/NestedMixedBBTests.java index c9e32182..1eeb2a7d 100644 --- a/example/src/test/java/com/example/sugartest/NestedMixedBBTests.java +++ b/library/src/test/java/com/orm/record/NestedMixedBBTests.java @@ -1,28 +1,33 @@ -package com.example.sugartest; +package com.orm.record; -import com.example.models.NestedMixedBBModel; -import com.example.models.RelationshipMixedBModel; -import com.example.models.SimpleExtendedModel; -import com.orm.SugarRecord; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.NestedMixedBBModel; +import com.orm.model.RelationshipMixedBModel; +import com.orm.model.SimpleExtendedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import java.util.List; import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; +import static com.orm.SugarRecord.count; +import static com.orm.SugarRecord.listAll; +import static org.junit.Assert.assertEquals; @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) public class NestedMixedBBTests { + @Test public void emptyDatabaseTest() throws Exception { - assertEquals(0L, SugarRecord.count(NestedMixedBBModel.class)); - assertEquals(0L, SugarRecord.count(RelationshipMixedBModel.class)); - assertEquals(0L, SugarRecord.count(SimpleExtendedModel.class)); + assertEquals(0L, count(NestedMixedBBModel.class)); + assertEquals(0L, count(RelationshipMixedBModel.class)); + assertEquals(0L, count(SimpleExtendedModel.class)); } @Test @@ -30,11 +35,13 @@ public void oneSaveTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); save(simple); RelationshipMixedBModel nested = new RelationshipMixedBModel(simple); + save(nested); save(new NestedMixedBBModel(nested)); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipMixedBModel.class)); - assertEquals(1L, SugarRecord.count(NestedMixedBBModel.class)); + + assertEquals(1L, count(SimpleExtendedModel.class)); + assertEquals(1L, count(RelationshipMixedBModel.class)); + assertEquals(1L, count(NestedMixedBBModel.class)); } @Test @@ -42,29 +49,33 @@ public void twoSameSaveTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); save(simple); RelationshipMixedBModel nested = new RelationshipMixedBModel(simple); + save(nested); save(new NestedMixedBBModel(nested)); save(new NestedMixedBBModel(nested)); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipMixedBModel.class)); - assertEquals(2L, SugarRecord.count(NestedMixedBBModel.class)); + + assertEquals(1L, count(SimpleExtendedModel.class)); + assertEquals(1L, count(RelationshipMixedBModel.class)); + assertEquals(2L, count(NestedMixedBBModel.class)); } @Test public void twoDifferentSaveTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); save(simple); - SimpleExtendedModel another_simple = new SimpleExtendedModel(); - save(another_simple); + SimpleExtendedModel anotherSimple = new SimpleExtendedModel(); + save(anotherSimple); RelationshipMixedBModel nested = new RelationshipMixedBModel(simple); save(nested); - RelationshipMixedBModel another_nested = new RelationshipMixedBModel(another_simple); - save(another_nested); + RelationshipMixedBModel anotherNested = new RelationshipMixedBModel(anotherSimple); + + save(anotherNested); save(new NestedMixedBBModel(nested)); - save(new NestedMixedBBModel(another_nested)); - assertEquals(2L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(2L, SugarRecord.count(RelationshipMixedBModel.class)); - assertEquals(2L, SugarRecord.count(NestedMixedBBModel.class)); + save(new NestedMixedBBModel(anotherNested)); + + assertEquals(2L, count(SimpleExtendedModel.class)); + assertEquals(2L, count(RelationshipMixedBModel.class)); + assertEquals(2L, count(NestedMixedBBModel.class)); } @Test @@ -73,12 +84,14 @@ public void manySameSaveTest() throws Exception { save(simple); RelationshipMixedBModel nested = new RelationshipMixedBModel(simple); save(nested); + for (int i = 1; i <= 100; i++) { save(new NestedMixedBBModel(nested)); } - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipMixedBModel.class)); - assertEquals(100L, SugarRecord.count(NestedMixedBBModel.class)); + + assertEquals(1L, count(SimpleExtendedModel.class)); + assertEquals(1L, count(RelationshipMixedBModel.class)); + assertEquals(100L, count(NestedMixedBBModel.class)); } @Test @@ -90,9 +103,10 @@ public void manyDifferentSaveTest() throws Exception { save(nested); save(new NestedMixedBBModel(nested)); } - assertEquals(100L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(100L, SugarRecord.count(RelationshipMixedBModel.class)); - assertEquals(100L, SugarRecord.count(NestedMixedBBModel.class)); + + assertEquals(100L, count(SimpleExtendedModel.class)); + assertEquals(100L, count(RelationshipMixedBModel.class)); + assertEquals(100L, count(NestedMixedBBModel.class)); } @Test @@ -101,11 +115,14 @@ public void listAllSameTest() throws Exception { save(simple); RelationshipMixedBModel nested = new RelationshipMixedBModel(simple); save(nested); + for (int i = 1; i <= 100; i++) { save(new NestedMixedBBModel(nested)); } - List models = SugarRecord.listAll(NestedMixedBBModel.class); + + List models = listAll(NestedMixedBBModel.class); assertEquals(100, models.size()); + for (NestedMixedBBModel model : models) { assertEquals(nested.getId(), model.getNested().getId()); assertEquals(simple.getId(), model.getNested().getSimple().getId()); @@ -121,8 +138,10 @@ public void listAllDifferentTest() throws Exception { save(nested); save(new NestedMixedBBModel(nested)); } - List models = SugarRecord.listAll(NestedMixedBBModel.class); + + List models = listAll(NestedMixedBBModel.class); assertEquals(100, models.size()); + for (NestedMixedBBModel model : models) { assertEquals(model.getId(), model.getNested().getId()); assertEquals(model.getId(), model.getNested().getSimple().getId()); diff --git a/library/src/test/java/com/orm/record/NoSugarModelTests.java b/library/src/test/java/com/orm/record/NoSugarModelTests.java new file mode 100644 index 00000000..08f43154 --- /dev/null +++ b/library/src/test/java/com/orm/record/NoSugarModelTests.java @@ -0,0 +1,34 @@ +package com.orm.record; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.NoSugarModel; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import static com.orm.SugarRecord.delete; +import static com.orm.SugarRecord.count; +import static com.orm.SugarRecord.saveInTx; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class NoSugarModelTests { + + @Test + public void deleteTest() throws Exception { + NoSugarModel model = new NoSugarModel(); + assertFalse(delete(model)); + } + + @Test + public void saveInTransactionTest() throws Exception { + saveInTx(new NoSugarModel(), new NoSugarModel()); + assertEquals(-1L, count(NoSugarModel.class)); + } +} diff --git a/library/src/test/java/com/orm/record/OneToManyTest.java b/library/src/test/java/com/orm/record/OneToManyTest.java new file mode 100644 index 00000000..73a60b57 --- /dev/null +++ b/library/src/test/java/com/orm/record/OneToManyTest.java @@ -0,0 +1,139 @@ +package com.orm.record; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.onetomany.OneToManyRelationModel; +import com.orm.model.onetomany.OneToManyModel; +import com.orm.model.onetomany.WithoutOneToManyAnnotationModel; +import com.orm.model.onetomany.WithoutOneToManyAnnotationRelationModel; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.util.Arrays; +import java.util.List; + +import static com.orm.SugarRecord.findById; +import static com.orm.SugarRecord.save; + +/** + * Created by Łukasz Wesołowski on 28.07.2016. + */ + +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public class OneToManyTest { + @Test + public void shouldSaveWithOneToManyRelation() { + List relationIds = Arrays.asList(1l, 2l, 3l, 4l); + + OneToManyModel model = new OneToManyModel(1l); + save(model); + + for (long i : relationIds) { + save(new OneToManyRelationModel(i, model)); + } + + OneToManyModel result = findById(OneToManyModel.class, 1l); + + Assert.assertEquals(4, result.getModels().size()); + + Assert.assertTrue(relationIds.contains(result.getModels().get(0).getId())); + Assert.assertTrue(relationIds.contains(result.getModels().get(1).getId())); + Assert.assertTrue(relationIds.contains(result.getModels().get(2).getId())); + Assert.assertTrue(relationIds.contains(result.getModels().get(3).getId())); + + Assert.assertEquals(result, result.getModels().get(0).getModel()); + Assert.assertEquals(result, result.getModels().get(1).getModel()); + Assert.assertEquals(result, result.getModels().get(2).getModel()); + Assert.assertEquals(result, result.getModels().get(3).getModel()); + } + + @Test + public void shouldRemoveOneOfManyToOneRelation() { + OneToManyModel model = new OneToManyModel(1l); + save(model); + + for (long i : Arrays.asList(1l, 2l, 3l, 4l)) { + save(new OneToManyRelationModel(i, model)); + } + + OneToManyModel result = findById(OneToManyModel.class, 1l); + + Assert.assertEquals(4, result.getModels().size()); + + OneToManyRelationModel.deleteAll(OneToManyRelationModel.class, "id = ?", String.valueOf(3l)); + + result = findById(OneToManyModel.class, 1l); + + Assert.assertEquals(3, result.getModels().size()); + + Assert.assertTrue(result.getModels().get(0).getId() != 3l); + Assert.assertTrue(result.getModels().get(1).getId() != 3l); + Assert.assertTrue(result.getModels().get(2).getId() != 3l); + } + + @Test + public void shouldNotRemoveRelation() { + OneToManyModel model = new OneToManyModel(1l); + save(model); + + for (long i : Arrays.asList(1l, 2l, 3l, 4l)) { + save(new OneToManyRelationModel(i, model)); + } + + OneToManyModel result = findById(OneToManyModel.class, 1l); + + result.getModels().clear(); + + save(model); + + result = findById(OneToManyModel.class, 1l); + + Assert.assertEquals(4, result.getModels().size()); + } + + @Test + public void shouldNotAddRelation() { + List relationIds = Arrays.asList(1l, 2l, 3l, 4l); + OneToManyModel model = new OneToManyModel(1l); + save(model); + + for (long i : relationIds) { + save(new OneToManyRelationModel(i, model)); + } + + save(new OneToManyRelationModel(5l, null)); + + OneToManyModel result = findById(OneToManyModel.class, 1l); + + Assert.assertEquals(4, result.getModels().size()); + + Assert.assertTrue(relationIds.contains(result.getModels().get(0).getId())); + Assert.assertTrue(relationIds.contains(result.getModels().get(1).getId())); + Assert.assertTrue(relationIds.contains(result.getModels().get(2).getId())); + Assert.assertTrue(relationIds.contains(result.getModels().get(3).getId())); + + Assert.assertEquals(result, result.getModels().get(0).getModel()); + Assert.assertEquals(result, result.getModels().get(1).getModel()); + Assert.assertEquals(result, result.getModels().get(2).getModel()); + Assert.assertEquals(result, result.getModels().get(3).getModel()); + } + + @Test + public void shouldNotInflateList() { + List relationIds = Arrays.asList(1l, 2l, 3l, 4l); + WithoutOneToManyAnnotationModel model = new WithoutOneToManyAnnotationModel(1l); + save(model); + + for (long i : relationIds) { + save(new WithoutOneToManyAnnotationRelationModel(i, model)); + } + + WithoutOneToManyAnnotationModel result = findById(WithoutOneToManyAnnotationModel.class, 1l); + + Assert.assertEquals(null, result.getModels()); + } +} diff --git a/example/src/test/java/com/example/sugartest/RelationshipAnnotatedTests.java b/library/src/test/java/com/orm/record/RelationshipAnnotatedTests.java similarity index 60% rename from example/src/test/java/com/example/sugartest/RelationshipAnnotatedTests.java rename to library/src/test/java/com/orm/record/RelationshipAnnotatedTests.java index 503926e1..506e0264 100644 --- a/example/src/test/java/com/example/sugartest/RelationshipAnnotatedTests.java +++ b/library/src/test/java/com/orm/record/RelationshipAnnotatedTests.java @@ -1,68 +1,81 @@ -package com.example.sugartest; +package com.orm.record; -import com.example.models.RelationshipAnnotatedModel; -import com.example.models.SimpleAnnotatedModel; -import com.orm.SugarRecord; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.RelationshipAnnotatedModel; +import com.orm.model.SimpleAnnotatedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import java.util.List; import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; +import static com.orm.SugarRecord.count; +import static com.orm.SugarRecord.listAll; +import static org.junit.Assert.assertEquals; @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class RelationshipAnnotatedTests { +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class RelationshipAnnotatedTests { + @Test public void emptyDatabaseTest() throws Exception { - assertEquals(0L, SugarRecord.count(RelationshipAnnotatedModel.class)); - assertEquals(0L, SugarRecord.count(SimpleAnnotatedModel.class)); + assertEquals(0L, count(RelationshipAnnotatedModel.class)); + assertEquals(0L, count(SimpleAnnotatedModel.class)); } @Test public void oneSaveTest() throws Exception { SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); + save(simple); save(new RelationshipAnnotatedModel(simple)); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipAnnotatedModel.class)); + + assertEquals(1L, count(SimpleAnnotatedModel.class)); + assertEquals(1L, count(RelationshipAnnotatedModel.class)); } @Test public void twoSameSaveTest() throws Exception { SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); + save(simple); save(new RelationshipAnnotatedModel(simple)); save(new RelationshipAnnotatedModel(simple)); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(2L, SugarRecord.count(RelationshipAnnotatedModel.class)); + + assertEquals(1L, count(SimpleAnnotatedModel.class)); + assertEquals(2L, count(RelationshipAnnotatedModel.class)); } @Test public void twoDifferentSaveTest() throws Exception { SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); save(simple); - SimpleAnnotatedModel another_simple = new SimpleAnnotatedModel(); - save(another_simple); + SimpleAnnotatedModel anotherSimple = new SimpleAnnotatedModel(); + + save(anotherSimple); save(new RelationshipAnnotatedModel(simple)); - save(new RelationshipAnnotatedModel(another_simple)); - assertEquals(2L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(2L, SugarRecord.count(RelationshipAnnotatedModel.class)); + save(new RelationshipAnnotatedModel(anotherSimple)); + + assertEquals(2L, count(SimpleAnnotatedModel.class)); + assertEquals(2L, count(RelationshipAnnotatedModel.class)); } @Test public void manySameSaveTest() throws Exception { SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); save(simple); + for (int i = 1; i <= 100; i++) { save(new RelationshipAnnotatedModel(simple)); } - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(100L, SugarRecord.count(RelationshipAnnotatedModel.class)); + + assertEquals(1L, count(SimpleAnnotatedModel.class)); + assertEquals(100L, count(RelationshipAnnotatedModel.class)); } @Test @@ -72,20 +85,23 @@ public void manyDifferentSaveTest() throws Exception { save(simple); save(new RelationshipAnnotatedModel(simple)); } - assertEquals(100L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(100L, SugarRecord.count(RelationshipAnnotatedModel.class)); + + assertEquals(100L, count(SimpleAnnotatedModel.class)); + assertEquals(100L, count(RelationshipAnnotatedModel.class)); } @Test public void listAllSameTest() throws Exception { SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); save(simple); + for (int i = 1; i <= 100; i++) { save(new RelationshipAnnotatedModel(simple)); } - List models = - SugarRecord.listAll(RelationshipAnnotatedModel.class); + + List models = listAll(RelationshipAnnotatedModel.class); assertEquals(100, models.size()); + for (RelationshipAnnotatedModel model : models) { assertEquals(simple.getId(), model.getSimple().getId()); } @@ -98,9 +114,10 @@ public void listAllDifferentTest() throws Exception { save(simple); save(new RelationshipAnnotatedModel(simple)); } - List models = - SugarRecord.listAll(RelationshipAnnotatedModel.class); + + List models = listAll(RelationshipAnnotatedModel.class); assertEquals(100, models.size()); + for (RelationshipAnnotatedModel model : models) { assertEquals(model.getId(), model.getSimple().getId()); } diff --git a/example/src/test/java/com/example/sugartest/RelationshipExtendedTests.java b/library/src/test/java/com/orm/record/RelationshipExtendedTests.java similarity index 61% rename from example/src/test/java/com/example/sugartest/RelationshipExtendedTests.java rename to library/src/test/java/com/orm/record/RelationshipExtendedTests.java index 3c3e04c7..f9faeedd 100644 --- a/example/src/test/java/com/example/sugartest/RelationshipExtendedTests.java +++ b/library/src/test/java/com/orm/record/RelationshipExtendedTests.java @@ -1,68 +1,81 @@ -package com.example.sugartest; +package com.orm.record; -import com.example.models.RelationshipExtendedModel; -import com.example.models.SimpleExtendedModel; -import com.orm.SugarRecord; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.RelationshipExtendedModel; +import com.orm.model.SimpleExtendedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import java.util.List; import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; +import static com.orm.SugarRecord.count; +import static com.orm.SugarRecord.listAll; +import static org.junit.Assert.assertEquals; @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) public class RelationshipExtendedTests { + @Test public void emptyDatabaseTest() throws Exception { - assertEquals(0L, SugarRecord.count(RelationshipExtendedModel.class)); - assertEquals(0L, SugarRecord.count(SimpleExtendedModel.class)); + assertEquals(0L, count(RelationshipExtendedModel.class)); + assertEquals(0L, count(SimpleExtendedModel.class)); } @Test public void oneSaveTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); + save(simple); save(new RelationshipExtendedModel(simple)); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipExtendedModel.class)); + + assertEquals(1L, count(SimpleExtendedModel.class)); + assertEquals(1L, count(RelationshipExtendedModel.class)); } @Test public void twoSameSaveTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); + save(simple); save(new RelationshipExtendedModel(simple)); save(new RelationshipExtendedModel(simple)); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(2L, SugarRecord.count(RelationshipExtendedModel.class)); + + assertEquals(1L, count(SimpleExtendedModel.class)); + assertEquals(2L, count(RelationshipExtendedModel.class)); } @Test public void twoDifferentSaveTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); save(simple); - SimpleExtendedModel another_simple = new SimpleExtendedModel(); - save(another_simple); + SimpleExtendedModel anotherSimple = new SimpleExtendedModel(); + + save(anotherSimple); save(new RelationshipExtendedModel(simple)); - save(new RelationshipExtendedModel(another_simple)); - assertEquals(2L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(2L, SugarRecord.count(RelationshipExtendedModel.class)); + save(new RelationshipExtendedModel(anotherSimple)); + + assertEquals(2L, count(SimpleExtendedModel.class)); + assertEquals(2L, count(RelationshipExtendedModel.class)); } @Test public void manySameSaveTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); save(simple); + for (int i = 1; i <= 100; i++) { save(new RelationshipExtendedModel(simple)); } - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(100L, SugarRecord.count(RelationshipExtendedModel.class)); + + assertEquals(1L, count(SimpleExtendedModel.class)); + assertEquals(100L, count(RelationshipExtendedModel.class)); } @Test @@ -72,20 +85,23 @@ public void manyDifferentSaveTest() throws Exception { save(simple); save(new RelationshipExtendedModel(simple)); } - assertEquals(100L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(100L, SugarRecord.count(RelationshipExtendedModel.class)); + + assertEquals(100L, count(SimpleExtendedModel.class)); + assertEquals(100L, count(RelationshipExtendedModel.class)); } @Test public void listAllSameTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); save(simple); + for (int i = 1; i <= 100; i++) { save(new RelationshipExtendedModel(simple)); } - List models = - SugarRecord.listAll(RelationshipExtendedModel.class); + + List models = listAll(RelationshipExtendedModel.class); assertEquals(100, models.size()); + for (RelationshipExtendedModel model : models) { assertEquals(simple.getId(), model.getSimple().getId()); } @@ -98,9 +114,10 @@ public void listAllDifferentTest() throws Exception { save(simple); save(new RelationshipExtendedModel(simple)); } - List models = - SugarRecord.listAll(RelationshipExtendedModel.class); + + List models = listAll(RelationshipExtendedModel.class); assertEquals(100, models.size()); + for (RelationshipExtendedModel model : models) { assertEquals(model.getId(), model.getSimple().getId()); } diff --git a/library/src/test/java/com/orm/record/RelationshipMixedATests.java b/library/src/test/java/com/orm/record/RelationshipMixedATests.java new file mode 100644 index 00000000..35aaa16d --- /dev/null +++ b/library/src/test/java/com/orm/record/RelationshipMixedATests.java @@ -0,0 +1,141 @@ +package com.orm.record; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.RelationshipMixedAModel; +import com.orm.model.SimpleAnnotatedModel; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.util.List; + +import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.count; +import static com.orm.SugarRecord.listAll; + +import static org.junit.Assert.assertEquals; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class RelationshipMixedATests { + + @Test + public void emptyDatabaseTest() throws Exception { + assertEquals(0L, count(RelationshipMixedAModel.class)); + assertEquals(0L, count(SimpleAnnotatedModel.class)); + } + + @Test + public void oneSaveTest() throws Exception { + SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); + RelationshipMixedAModel mixedAModel = new RelationshipMixedAModel(simple); + + save(simple); + save(mixedAModel); + + assertEquals(1L, count(simple.getClass())); + assertEquals(1L, count(mixedAModel.getClass())); + } + + @Test + public void twoSameSaveTest() throws Exception { + SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); + RelationshipMixedAModel mixedAModel1 = new RelationshipMixedAModel(simple); + RelationshipMixedAModel mixedAModel2 = new RelationshipMixedAModel(simple); + + + save(simple); + save(mixedAModel1); + save(mixedAModel2); + + assertEquals(1L, count(simple.getClass())); + assertEquals(2L, count(mixedAModel1.getClass())); + } + + @Test + public void twoDifferentSaveTest() throws Exception { + SimpleAnnotatedModel anotherSimple = new SimpleAnnotatedModel(); + SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); + RelationshipMixedAModel mixedAModel = new RelationshipMixedAModel(simple); + RelationshipMixedAModel anotherMixedAModel = new RelationshipMixedAModel(anotherSimple); + + save(simple); + save(anotherSimple); + save(mixedAModel); + save(anotherMixedAModel); + + assertEquals(2L, count(simple.getClass())); + assertEquals(2L, count(mixedAModel.getClass())); + } + + @Test + public void manySameSaveTest() throws Exception { + final SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); + RelationshipMixedAModel mixedAModel = null; + save(simple); + + for (int i = 1; i <= 100; i++) { + mixedAModel = new RelationshipMixedAModel(simple); + save(mixedAModel); + } + + assertEquals(1L, count(simple.getClass())); + assertEquals(100L, count(mixedAModel.getClass())); + } + + @Test + public void manyDifferentSaveTest() throws Exception { + SimpleAnnotatedModel simple = null; + RelationshipMixedAModel mixedAModel = null; + + for (int i = 1; i <= 100; i++) { + simple = new SimpleAnnotatedModel(); + mixedAModel = new RelationshipMixedAModel(simple); + + save(simple); + save(mixedAModel); + } + + assertEquals(100L, count(simple.getClass())); + assertEquals(100L, count(mixedAModel.getClass())); + } + + @Test + public void listAllSameTest() throws Exception { + SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); + + for (int i = 1; i <= 100; i++) { + RelationshipMixedAModel mixedAModel = new RelationshipMixedAModel(simple); + + save(simple); + save(mixedAModel); + } + + List models = listAll(RelationshipMixedAModel.class); + assertEquals(100, models.size()); + + for (RelationshipMixedAModel model : models) { + assertEquals(simple.getId(), model.getSimple().getId()); + } + } + + @Test + public void listAllDifferentTest() throws Exception { + for (int i = 1; i <= 100; i++) { + SimpleAnnotatedModel simple = new SimpleAnnotatedModel(); + + save(simple); + save(new RelationshipMixedAModel(simple)); + } + + List models = listAll(RelationshipMixedAModel.class); + assertEquals(100, models.size()); + + for (RelationshipMixedAModel model : models) { + assertEquals(model.getId(), model.getSimple().getId()); + } + } +} diff --git a/example/src/test/java/com/example/sugartest/RelationshipMixedBTests.java b/library/src/test/java/com/orm/record/RelationshipMixedBTests.java similarity index 61% rename from example/src/test/java/com/example/sugartest/RelationshipMixedBTests.java rename to library/src/test/java/com/orm/record/RelationshipMixedBTests.java index 1d31ecd2..7792fce8 100644 --- a/example/src/test/java/com/example/sugartest/RelationshipMixedBTests.java +++ b/library/src/test/java/com/orm/record/RelationshipMixedBTests.java @@ -1,68 +1,81 @@ -package com.example.sugartest; +package com.orm.record; -import com.example.models.RelationshipMixedBModel; -import com.example.models.SimpleExtendedModel; -import com.orm.SugarRecord; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.RelationshipMixedBModel; +import com.orm.model.SimpleExtendedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import java.util.List; import static com.orm.SugarRecord.save; -import static org.junit.Assert.assertEquals; +import static com.orm.SugarRecord.count; +import static com.orm.SugarRecord.listAll; +import static org.junit.Assert.assertEquals; @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) public class RelationshipMixedBTests { + @Test public void emptyDatabaseTest() throws Exception { - assertEquals(0L, SugarRecord.count(RelationshipMixedBModel.class)); - assertEquals(0L, SugarRecord.count(SimpleExtendedModel.class)); + assertEquals(0L, count(RelationshipMixedBModel.class)); + assertEquals(0L, count(SimpleExtendedModel.class)); } @Test public void oneSaveTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); + save(simple); save(new RelationshipMixedBModel(simple)); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(1L, SugarRecord.count(RelationshipMixedBModel.class)); + + assertEquals(1L, count(SimpleExtendedModel.class)); + assertEquals(1L, count(RelationshipMixedBModel.class)); } @Test public void twoSameSaveTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); + save(simple); save(new RelationshipMixedBModel(simple)); save(new RelationshipMixedBModel(simple)); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(2L, SugarRecord.count(RelationshipMixedBModel.class)); + + assertEquals(1L, count(SimpleExtendedModel.class)); + assertEquals(2L, count(RelationshipMixedBModel.class)); } @Test public void twoDifferentSaveTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); save(simple); - SimpleExtendedModel another_simple = new SimpleExtendedModel(); - save(another_simple); + SimpleExtendedModel anotherSimple = new SimpleExtendedModel(); + + save(anotherSimple); save(new RelationshipMixedBModel(simple)); - save(new RelationshipMixedBModel(another_simple)); - assertEquals(2L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(2L, SugarRecord.count(RelationshipMixedBModel.class)); + save(new RelationshipMixedBModel(anotherSimple)); + + assertEquals(2L, count(SimpleExtendedModel.class)); + assertEquals(2L, count(RelationshipMixedBModel.class)); } @Test public void manySameSaveTest() throws Exception { SimpleExtendedModel simple = new SimpleExtendedModel(); save(simple); + for (int i = 1; i <= 100; i++) { save(new RelationshipMixedBModel(simple)); } - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(100L, SugarRecord.count(RelationshipMixedBModel.class)); + + assertEquals(1L, count(SimpleExtendedModel.class)); + assertEquals(100L, count(RelationshipMixedBModel.class)); } @Test @@ -72,8 +85,9 @@ public void manyDifferentSaveTest() throws Exception { save(simple); save(new RelationshipMixedBModel(simple)); } - assertEquals(100L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(100L, SugarRecord.count(RelationshipMixedBModel.class)); + + assertEquals(100L, count(SimpleExtendedModel.class)); + assertEquals(100L, count(RelationshipMixedBModel.class)); } @Test @@ -83,8 +97,7 @@ public void listAllSameTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new RelationshipMixedBModel(simple)); } - List models = - SugarRecord.listAll(RelationshipMixedBModel.class); + List models = listAll(RelationshipMixedBModel.class); assertEquals(100, models.size()); for (RelationshipMixedBModel model : models) { assertEquals(simple.getId(), model.getSimple().getId()); @@ -98,8 +111,7 @@ public void listAllDifferentTest() throws Exception { save(simple); save(new RelationshipMixedBModel(simple)); } - List models = - SugarRecord.listAll(RelationshipMixedBModel.class); + List models = listAll(RelationshipMixedBModel.class); assertEquals(100, models.size()); for (RelationshipMixedBModel model : models) { assertEquals(model.getId(), model.getSimple().getId()); diff --git a/library/src/test/java/com/orm/record/ShortFieldTests.java b/library/src/test/java/com/orm/record/ShortFieldTests.java new file mode 100644 index 00000000..1a65f676 --- /dev/null +++ b/library/src/test/java/com/orm/record/ShortFieldTests.java @@ -0,0 +1,80 @@ +package com.orm.record; + +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.ShortFieldAnnotatedModel; +import com.orm.model.ShortFieldExtendedModel; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.findById; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +@SuppressWarnings("all") +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class ShortFieldTests { + private Short aShort = Short.valueOf((short) 25); + + @Test + public void nullShortExtendedTest() { + save(new ShortFieldExtendedModel()); + ShortFieldExtendedModel model = findById(ShortFieldExtendedModel.class, 1); + assertNull(model.getShort()); + } + + @Test + public void nullRawShortExtendedTest() { + save(new ShortFieldExtendedModel()); + ShortFieldExtendedModel model = findById(ShortFieldExtendedModel.class, 1); + assertEquals((short) 0, model.getRawShort()); + } + + @Test + public void nullShortAnnotatedTest() { + save(new ShortFieldAnnotatedModel()); + ShortFieldAnnotatedModel model = findById(ShortFieldAnnotatedModel.class, 1); + assertNull(model.getShort()); + } + + @Test + public void nullRawShortAnnotatedTest() { + save(new ShortFieldAnnotatedModel()); + ShortFieldAnnotatedModel model = findById(ShortFieldAnnotatedModel.class, 1); + assertEquals((short) 0, model.getRawShort()); + } + + @Test + public void objectShortExtendedTest() { + save(new ShortFieldExtendedModel(aShort)); + ShortFieldExtendedModel model = findById(ShortFieldExtendedModel.class, 1); + assertEquals(aShort, model.getShort()); + } + + @Test + public void rawShortExtendedTest() { + save(new ShortFieldExtendedModel(aShort.shortValue())); + ShortFieldExtendedModel model = findById(ShortFieldExtendedModel.class, 1); + assertEquals(aShort.shortValue(), model.getRawShort()); + } + + @Test + public void objectShortAnnotatedTest() { + save(new ShortFieldAnnotatedModel(aShort)); + ShortFieldAnnotatedModel model = findById(ShortFieldAnnotatedModel.class, 1); + assertEquals(aShort, model.getShort()); + } + + @Test + public void rawShortAnnotatedTest() { + save(new ShortFieldAnnotatedModel(aShort.shortValue())); + ShortFieldAnnotatedModel model = findById(ShortFieldAnnotatedModel.class, 1); + assertEquals(aShort.shortValue(), model.getRawShort()); + } +} diff --git a/example/src/test/java/com/example/sugartest/SimpleAnnotatedModelTests.java b/library/src/test/java/com/orm/record/SimpleAnnotatedModelTests.java similarity index 54% rename from example/src/test/java/com/example/sugartest/SimpleAnnotatedModelTests.java rename to library/src/test/java/com/orm/record/SimpleAnnotatedModelTests.java index 7bfe0108..a201a9eb 100644 --- a/example/src/test/java/com/example/sugartest/SimpleAnnotatedModelTests.java +++ b/library/src/test/java/com/orm/record/SimpleAnnotatedModelTests.java @@ -1,11 +1,13 @@ -package com.example.sugartest; +package com.orm.record; -import com.example.models.SimpleAnnotatedModel; -import com.orm.SugarRecord; -import com.orm.util.NamingHelper; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.helper.NamingHelper; +import com.orm.model.SimpleAnnotatedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import java.lang.reflect.Field; @@ -15,32 +17,46 @@ import java.util.NoSuchElementException; import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.count; +import static com.orm.SugarRecord.deleteAll; +import static com.orm.SugarRecord.delete; +import static com.orm.SugarRecord.deleteInTx; +import static com.orm.SugarRecord.listAll; +import static com.orm.SugarRecord.findById; +import static com.orm.SugarRecord.saveInTx; +import static com.orm.SugarRecord.find; +import static com.orm.SugarRecord.findAsIterator; +import static com.orm.SugarRecord.findWithQuery; +import static com.orm.SugarRecord.findAll; +import static com.orm.SugarRecord.findWithQueryAsIterator; +import static com.orm.SugarRecord.executeQuery; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; - @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class SimpleAnnotatedModelTests { +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class SimpleAnnotatedModelTests { + @Test public void emptyDatabaseTest() throws Exception { - assertEquals(0L, SugarRecord.count(SimpleAnnotatedModel.class)); + assertEquals(0L, count(SimpleAnnotatedModel.class)); } @Test public void oneSaveTest() throws Exception { save(new SimpleAnnotatedModel()); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); + assertEquals(1L, count(SimpleAnnotatedModel.class)); } @Test public void twoSaveTest() throws Exception { save(new SimpleAnnotatedModel()); save(new SimpleAnnotatedModel()); - assertEquals(2L, SugarRecord.count(SimpleAnnotatedModel.class)); + assertEquals(2L, count(SimpleAnnotatedModel.class)); } @Test @@ -48,7 +64,7 @@ public void manySaveTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new SimpleAnnotatedModel()); } - assertEquals(100L, SugarRecord.count(SimpleAnnotatedModel.class)); + assertEquals(100L, count(SimpleAnnotatedModel.class)); } @Test @@ -60,74 +76,75 @@ public void defaultIdTest() throws Exception { public void whereCountTest() throws Exception { save(new SimpleAnnotatedModel()); save(new SimpleAnnotatedModel()); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class, "id = ?", new String[]{"1"})); + assertEquals(1L, count(SimpleAnnotatedModel.class, "id = ?", new String[]{"1"})); } @Test public void whereNoCountTest() throws Exception { - assertEquals(0L, SugarRecord.count(SimpleAnnotatedModel.class, "id = ?", new String[]{"1"})); + assertEquals(0L, count(SimpleAnnotatedModel.class, "id = ?", new String[]{"1"})); save(new SimpleAnnotatedModel()); save(new SimpleAnnotatedModel()); - assertEquals(0L, SugarRecord.count(SimpleAnnotatedModel.class, "id = ?", new String[]{"3"})); - assertEquals(0L, SugarRecord.count(SimpleAnnotatedModel.class, "id = ?", new String[]{"a"})); + assertEquals(0L, count(SimpleAnnotatedModel.class, "id = ?", new String[]{"3"})); + assertEquals(0L, count(SimpleAnnotatedModel.class, "id = ?", new String[]{"a"})); } @Test public void whereBrokenCountTest() throws Exception { save(new SimpleAnnotatedModel()); save(new SimpleAnnotatedModel()); - assertEquals(-1L, SugarRecord.count(SimpleAnnotatedModel.class, "di = ?", new String[]{"1"})); + assertEquals(-1L, count(SimpleAnnotatedModel.class, "di = ?", new String[]{"1"})); } @Test public void deleteTest() throws Exception { SimpleAnnotatedModel model = new SimpleAnnotatedModel(); save(model); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertTrue(SugarRecord.delete(model)); - assertEquals(0L, SugarRecord.count(SimpleAnnotatedModel.class)); + assertEquals(1L, count(SimpleAnnotatedModel.class)); + assertTrue(delete(model)); + assertEquals(0L, count(SimpleAnnotatedModel.class)); } @Test public void deleteUnsavedTest() throws Exception { SimpleAnnotatedModel model = new SimpleAnnotatedModel(); - assertEquals(0L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertFalse(SugarRecord.delete(model)); - assertEquals(0L, SugarRecord.count(SimpleAnnotatedModel.class)); + assertEquals(0L, count(SimpleAnnotatedModel.class)); + assertFalse(delete(model)); + assertEquals(0L, count(SimpleAnnotatedModel.class)); } @Test public void deleteWrongTest() throws Exception { SimpleAnnotatedModel model = new SimpleAnnotatedModel(); save(model); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); + assertEquals(1L, count(SimpleAnnotatedModel.class)); + Field idField = model.getClass().getDeclaredField("id"); idField.setAccessible(true); idField.set(model, Long.MAX_VALUE); - assertFalse(SugarRecord.delete(model)); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); + + assertFalse(delete(model)); + assertEquals(1L, count(SimpleAnnotatedModel.class)); } @Test public void deleteAllTest() throws Exception { - int elementNumber = 100; - for (int i = 1; i <= elementNumber; i++) { + for (int i = 1; i <= 100; i++) { save(new SimpleAnnotatedModel()); } - assertEquals(elementNumber, SugarRecord.deleteAll(SimpleAnnotatedModel.class)); - assertEquals(0L, SugarRecord.count(SimpleAnnotatedModel.class)); + + assertEquals(100, deleteAll(SimpleAnnotatedModel.class)); + assertEquals(0L, count(SimpleAnnotatedModel.class)); } @Test + @SuppressWarnings("all") public void deleteAllWhereTest() throws Exception { - int elementNumber = 100; - for (int i = 1; i <= elementNumber; i++) { + for (int i = 1; i <= 100; i++) { save(new SimpleAnnotatedModel()); } - assertEquals(elementNumber - 1, SugarRecord.deleteAll(SimpleAnnotatedModel.class, - "id > ?", - new String[]{"1"})); - assertEquals(1L, SugarRecord.count(SimpleAnnotatedModel.class)); + + assertEquals(99, deleteAll(SimpleAnnotatedModel.class, "id > ?", new String[]{"1"})); + assertEquals(1L, count(SimpleAnnotatedModel.class)); } @Test @@ -138,32 +155,33 @@ public void deleteInTransactionFewTest() throws Exception { save(first); save(second); // Not saving last model - assertEquals(2L, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(2, SugarRecord.deleteInTx(first, second, third)); - assertEquals(0L, SugarRecord.count(SimpleAnnotatedModel.class)); + assertEquals(2L, count(SimpleAnnotatedModel.class)); + assertEquals(2, deleteInTx(first, second, third)); + assertEquals(0L, count(SimpleAnnotatedModel.class)); } @Test public void deleteInTransactionManyTest() throws Exception { - long elementNumber = 100; List models = new ArrayList<>(); - for (int i = 1; i <= elementNumber; i++) { + + for (int i = 1; i <= 100; i++) { SimpleAnnotatedModel model = new SimpleAnnotatedModel(); models.add(model); // Not saving last model - if (i < elementNumber) { + if (i < 100) { save(model); } } - assertEquals(elementNumber - 1, SugarRecord.count(SimpleAnnotatedModel.class)); - assertEquals(elementNumber - 1, SugarRecord.deleteInTx(models)); - assertEquals(0L, SugarRecord.count(SimpleAnnotatedModel.class)); + + assertEquals(99, count(SimpleAnnotatedModel.class)); + assertEquals(99, deleteInTx(models)); + assertEquals(0L, count(SimpleAnnotatedModel.class)); } @Test public void saveInTransactionTest() throws Exception { - SugarRecord.saveInTx(new SimpleAnnotatedModel(), new SimpleAnnotatedModel()); - assertEquals(2L, SugarRecord.count(SimpleAnnotatedModel.class)); + saveInTx(new SimpleAnnotatedModel(), new SimpleAnnotatedModel()); + assertEquals(2L, count(SimpleAnnotatedModel.class)); } @Test @@ -171,10 +189,12 @@ public void listAllTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new SimpleAnnotatedModel()); } - List models = SugarRecord.listAll(SimpleAnnotatedModel.class); + + List models = listAll(SimpleAnnotatedModel.class); assertEquals(100, models.size()); + for (long i = 1; i <= 100; i++) { - assertEquals(new Long(i), models.get((int) i - 1).getId()); + assertEquals(Long.valueOf(i), models.get((int) i - 1).getId()); } } @@ -182,10 +202,11 @@ public void listAllTest() throws Exception { public void findTest() throws Exception { save(new SimpleAnnotatedModel()); save(new SimpleAnnotatedModel()); - List models = - SugarRecord.find(SimpleAnnotatedModel.class, "id = ?", "2"); + + List models = find(SimpleAnnotatedModel.class, "id = ?", "2"); + assertEquals(1, models.size()); - assertEquals(new Long(2L), models.get(0).getId()); + assertEquals(2L, models.get(0).getId().longValue()); } @Test @@ -193,40 +214,41 @@ public void findWithQueryTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new SimpleAnnotatedModel()); } - List models = - SugarRecord.findWithQuery(SimpleAnnotatedModel.class, "Select * from " + - NamingHelper.toSQLName(SimpleAnnotatedModel.class) + + + List models = findWithQuery(SimpleAnnotatedModel.class, "Select * from " + + NamingHelper.toTableName(SimpleAnnotatedModel.class) + " where id >= ? ", "50"); + for (SimpleAnnotatedModel model : models) { - assertEquals(new Long(75), model.getId(), 25L); + assertEquals(75L, model.getId(), 25L); } } @Test + @SuppressWarnings("all") public void findByIdTest() throws Exception { save(new SimpleAnnotatedModel()); - assertEquals(new Long(1L), SugarRecord.findById(SimpleAnnotatedModel.class, 1L).getId()); + assertEquals(1L, findById(SimpleAnnotatedModel.class, 1L).getId().longValue()); } @Test public void findByIdIntegerTest() throws Exception { save(new SimpleAnnotatedModel()); - assertEquals(new Long(1L), SugarRecord.findById(SimpleAnnotatedModel.class, 1).getId()); + assertEquals(1L, findById(SimpleAnnotatedModel.class, 1).getId().longValue()); } @Test public void findByIdStringsNullTest() throws Exception { save(new SimpleAnnotatedModel()); - assertEquals(0, SugarRecord.findById(SimpleAnnotatedModel.class, new String[]{""}).size()); + assertEquals(0, findById(SimpleAnnotatedModel.class, new String[]{""}).size()); } @Test public void findByIdStringsOneTest() throws Exception { save(new SimpleAnnotatedModel()); - List models = - SugarRecord.findById(SimpleAnnotatedModel.class, new String[]{"1"}); + List models = findById(SimpleAnnotatedModel.class, new String[]{"1"}); assertEquals(1, models.size()); - assertEquals(new Long(1L), models.get(0).getId()); + assertEquals(1L, models.get(0).getId().longValue()); } @Test @@ -234,11 +256,10 @@ public void findByIdStringsTwoTest() throws Exception { save(new SimpleAnnotatedModel()); save(new SimpleAnnotatedModel()); save(new SimpleAnnotatedModel()); - List models = - SugarRecord.findById(SimpleAnnotatedModel.class, new String[]{"1", "3"}); + List models = findById(SimpleAnnotatedModel.class, new String[]{"1", "3"}); assertEquals(2, models.size()); - assertEquals(new Long(1L), models.get(0).getId()); - assertEquals(new Long(3L), models.get(1).getId()); + assertEquals(Long.valueOf(1L), models.get(0).getId()); + assertEquals(Long.valueOf(3L), models.get(1).getId()); } @Test @@ -246,13 +267,12 @@ public void findByIdStringsManyTest() throws Exception { for (int i = 1; i <= 10; i++) { save(new SimpleAnnotatedModel()); } - List models = - SugarRecord.findById(SimpleAnnotatedModel.class, new String[]{"1", "3", "6", "10"}); + List models = findById(SimpleAnnotatedModel.class, new String[]{"1", "3", "6", "10"}); assertEquals(4, models.size()); - assertEquals(new Long(1L), models.get(0).getId()); - assertEquals(new Long(3L), models.get(1).getId()); - assertEquals(new Long(6L), models.get(2).getId()); - assertEquals(new Long(10L), models.get(3).getId()); + assertEquals(Long.valueOf(1L), models.get(0).getId()); + assertEquals(Long.valueOf(3L), models.get(1).getId()); + assertEquals(Long.valueOf(6L), models.get(2).getId()); + assertEquals(Long.valueOf(10L), models.get(3).getId()); } @Test @@ -260,20 +280,19 @@ public void findByIdStringsOrderTest() throws Exception { for (int i = 1; i <= 10; i++) { save(new SimpleAnnotatedModel()); } - List models = - SugarRecord.findById(SimpleAnnotatedModel.class, new String[]{"10", "6", "3", "1"}); + List models = findById(SimpleAnnotatedModel.class, new String[]{"10", "6", "3", "1"}); assertEquals(4, models.size()); // The order of the query doesn't matter - assertEquals(new Long(1L), models.get(0).getId()); - assertEquals(new Long(3L), models.get(1).getId()); - assertEquals(new Long(6L), models.get(2).getId()); - assertEquals(new Long(10L), models.get(3).getId()); + assertEquals(Long.valueOf(1L), models.get(0).getId()); + assertEquals(Long.valueOf(3L), models.get(1).getId()); + assertEquals(Long.valueOf(6L), models.get(2).getId()); + assertEquals(Long.valueOf(10L), models.get(3).getId()); } @Test public void findByIdNullTest() throws Exception { save(new SimpleAnnotatedModel()); - assertNull(SugarRecord.findById(SimpleAnnotatedModel.class, 2L)); + assertNull(findById(SimpleAnnotatedModel.class, 2L)); } @Test @@ -281,12 +300,12 @@ public void findAllTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new SimpleAnnotatedModel()); } - Iterator cursor = SugarRecord.findAll(SimpleAnnotatedModel.class); + Iterator cursor = findAll(SimpleAnnotatedModel.class); for (int i = 1; i <= 100; i++) { assertTrue(cursor.hasNext()); SimpleAnnotatedModel model = cursor.next(); assertNotNull(model); - assertEquals(new Long(i), model.getId()); + assertEquals(Long.valueOf(i), model.getId()); } } @@ -295,13 +314,13 @@ public void findAsIteratorTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new SimpleAnnotatedModel()); } - Iterator cursor = SugarRecord.findAsIterator(SimpleAnnotatedModel.class, + Iterator cursor = findAsIterator(SimpleAnnotatedModel.class, "id >= ?", "50"); for (int i = 50; i <= 100; i++) { assertTrue(cursor.hasNext()); SimpleAnnotatedModel model = cursor.next(); assertNotNull(model); - assertEquals(new Long(i), model.getId()); + assertEquals(Long.valueOf(i), model.getId()); } } @@ -310,28 +329,27 @@ public void findWithQueryAsIteratorTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new SimpleAnnotatedModel()); } - Iterator cursor = - SugarRecord.findWithQueryAsIterator(SimpleAnnotatedModel.class, + Iterator cursor = findWithQueryAsIterator(SimpleAnnotatedModel.class, "Select * from " + - NamingHelper.toSQLName(SimpleAnnotatedModel.class) + + NamingHelper.toTableName(SimpleAnnotatedModel.class) + " where id >= ? ", "50"); for (int i = 50; i <= 100; i++) { assertTrue(cursor.hasNext()); SimpleAnnotatedModel model = cursor.next(); assertNotNull(model); - assertEquals(new Long(i), model.getId()); + assertEquals(Long.valueOf(i), model.getId()); } } @Test(expected=NoSuchElementException.class) public void findAsIteratorOutOfBoundsTest() throws Exception { save(new SimpleAnnotatedModel()); - Iterator cursor = SugarRecord.findAsIterator(SimpleAnnotatedModel.class, + Iterator cursor = findAsIterator(SimpleAnnotatedModel.class, "id = ?", "1"); assertTrue(cursor.hasNext()); SimpleAnnotatedModel model = cursor.next(); assertNotNull(model); - assertEquals(new Long(1), model.getId()); + assertEquals(Long.valueOf(1), model.getId()); // This should throw a NoSuchElementException cursor.next(); } @@ -339,18 +357,17 @@ public void findAsIteratorOutOfBoundsTest() throws Exception { @Test(expected=UnsupportedOperationException.class) public void disallowRemoveCursorTest() throws Exception { save(new SimpleAnnotatedModel()); - Iterator cursor = SugarRecord.findAsIterator(SimpleAnnotatedModel.class, - "id = ?", "1"); + Iterator cursor = findAsIterator(SimpleAnnotatedModel.class, "id = ?", "1"); assertTrue(cursor.hasNext()); SimpleAnnotatedModel model = cursor.next(); assertNotNull(model); - assertEquals(new Long(1), model.getId()); + assertEquals(Long.valueOf(1), model.getId()); // This should throw a UnsupportedOperationException cursor.remove(); } @Test public void vacuumTest() throws Exception { - SugarRecord.executeQuery("Vacuum"); + executeQuery("Vacuum"); } } \ No newline at end of file diff --git a/example/src/test/java/com/example/sugartest/SimpleExtendedModelTests.java b/library/src/test/java/com/orm/record/SimpleExtendedModelTests.java similarity index 56% rename from example/src/test/java/com/example/sugartest/SimpleExtendedModelTests.java rename to library/src/test/java/com/orm/record/SimpleExtendedModelTests.java index aa860270..e809405d 100644 --- a/example/src/test/java/com/example/sugartest/SimpleExtendedModelTests.java +++ b/library/src/test/java/com/orm/record/SimpleExtendedModelTests.java @@ -1,11 +1,13 @@ -package com.example.sugartest; +package com.orm.record; -import com.example.models.SimpleExtendedModel; -import com.orm.SugarRecord; -import com.orm.util.NamingHelper; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.helper.NamingHelper; +import com.orm.model.SimpleExtendedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import java.lang.reflect.Field; @@ -15,32 +17,47 @@ import java.util.NoSuchElementException; import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.count; +import static com.orm.SugarRecord.delete; +import static com.orm.SugarRecord.deleteAll; +import static com.orm.SugarRecord.executeQuery; +import static com.orm.SugarRecord.find; +import static com.orm.SugarRecord.findAll; +import static com.orm.SugarRecord.findById; +import static com.orm.SugarRecord.findWithQuery; +import static com.orm.SugarRecord.findAsIterator; +import static com.orm.SugarRecord.findWithQueryAsIterator; +import static com.orm.SugarRecord.deleteInTx; +import static com.orm.SugarRecord.saveInTx; +import static com.orm.SugarRecord.listAll; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; - @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class SimpleExtendedModelTests { +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class SimpleExtendedModelTests { + private String id = "id = ?"; + @Test public void emptyDatabaseTest() throws Exception { - assertEquals(0L, SugarRecord.count(SimpleExtendedModel.class)); + assertEquals(0L, count(SimpleExtendedModel.class)); } @Test public void oneSaveTest() throws Exception { save(new SimpleExtendedModel()); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); + assertEquals(1L, count(SimpleExtendedModel.class)); } @Test public void twoSaveTest() throws Exception { save(new SimpleExtendedModel()); save(new SimpleExtendedModel()); - assertEquals(2L, SugarRecord.count(SimpleExtendedModel.class)); + assertEquals(2L, count(SimpleExtendedModel.class)); } @Test @@ -48,7 +65,8 @@ public void manySaveTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new SimpleExtendedModel()); } - assertEquals(100L, SugarRecord.count(SimpleExtendedModel.class)); + + assertEquals(100L, count(SimpleExtendedModel.class)); } @Test @@ -60,59 +78,59 @@ public void defaultIdTest() throws Exception { public void whereCountTest() throws Exception { save(new SimpleExtendedModel()); save(new SimpleExtendedModel()); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class, "id = ?", new String[]{"1"})); + assertEquals(1L, count(SimpleExtendedModel.class, id, new String[]{"1"})); } @Test public void whereNoCountTest() throws Exception { - assertEquals(0L, SugarRecord.count(SimpleExtendedModel.class, "id = ?", new String[]{"1"})); + assertEquals(0L, count(SimpleExtendedModel.class, id, new String[]{"1"})); save(new SimpleExtendedModel()); save(new SimpleExtendedModel()); - assertEquals(0L, SugarRecord.count(SimpleExtendedModel.class, "id = ?", new String[]{"3"})); - assertEquals(0L, SugarRecord.count(SimpleExtendedModel.class, "id = ?", new String[]{"a"})); + assertEquals(0L, count(SimpleExtendedModel.class, id, new String[]{"3"})); + assertEquals(0L, count(SimpleExtendedModel.class, id, new String[]{"a"})); } @Test public void whereBrokenCountTest() throws Exception { save(new SimpleExtendedModel()); save(new SimpleExtendedModel()); - assertEquals(-1L, SugarRecord.count(SimpleExtendedModel.class, "di = ?", new String[]{"1"})); + assertEquals(-1L, count(SimpleExtendedModel.class, "di = ?", new String[]{"1"})); } @Test public void saveMethodTest() throws Exception { SimpleExtendedModel model = new SimpleExtendedModel(); model.save(); - assertEquals(-1L, SugarRecord.count(SimpleExtendedModel.class, "di = ?", new String[]{"1"})); + assertEquals(-1L, count(SimpleExtendedModel.class, "di = ?", new String[]{"1"})); } @Test public void deleteTest() throws Exception { SimpleExtendedModel model = new SimpleExtendedModel(); save(model); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); - assertTrue(SugarRecord.delete(model)); - assertEquals(0L, SugarRecord.count(SimpleExtendedModel.class)); + assertEquals(1L, count(SimpleExtendedModel.class)); + assertTrue(delete(model)); + assertEquals(0L, count(SimpleExtendedModel.class)); } @Test public void deleteUnsavedTest() throws Exception { SimpleExtendedModel model = new SimpleExtendedModel(); - assertEquals(0L, SugarRecord.count(SimpleExtendedModel.class)); - assertFalse(SugarRecord.delete(model)); - assertEquals(0L, SugarRecord.count(SimpleExtendedModel.class)); + assertEquals(0L, count(SimpleExtendedModel.class)); + assertFalse(delete(model)); + assertEquals(0L, count(SimpleExtendedModel.class)); } @Test public void deleteWrongTest() throws Exception { SimpleExtendedModel model = new SimpleExtendedModel(); save(model); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); + assertEquals(1L, count(SimpleExtendedModel.class)); Field idField = model.getClass().getSuperclass().getDeclaredField("id"); idField.setAccessible(true); idField.set(model, Long.MAX_VALUE); - assertFalse(SugarRecord.delete(model)); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); + assertFalse(delete(model)); + assertEquals(1L, count(SimpleExtendedModel.class)); } @Test @@ -121,20 +139,19 @@ public void deleteAllTest() throws Exception { for (int i = 1; i <= elementNumber; i++) { save(new SimpleExtendedModel()); } - assertEquals(elementNumber, SugarRecord.deleteAll(SimpleExtendedModel.class)); - assertEquals(0L, SugarRecord.count(SimpleExtendedModel.class)); + assertEquals(elementNumber, deleteAll(SimpleExtendedModel.class)); + assertEquals(0L, count(SimpleExtendedModel.class)); } @Test + @SuppressWarnings("all") public void deleteAllWhereTest() throws Exception { int elementNumber = 100; for (int i = 1; i <= elementNumber; i++) { save(new SimpleExtendedModel()); } - assertEquals(elementNumber - 1, SugarRecord.deleteAll(SimpleExtendedModel.class, - "id > ?", - new String[]{"1"})); - assertEquals(1L, SugarRecord.count(SimpleExtendedModel.class)); + assertEquals(elementNumber - 1, deleteAll(SimpleExtendedModel.class, "id > ?", new String[]{"1"})); + assertEquals(1L, count(SimpleExtendedModel.class)); } @Test @@ -145,9 +162,9 @@ public void deleteInTransactionFewTest() throws Exception { save(first); save(second); // Not saving last model - assertEquals(2L, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(2, SugarRecord.deleteInTx(first, second, third)); - assertEquals(0L, SugarRecord.count(SimpleExtendedModel.class)); + assertEquals(2L, count(SimpleExtendedModel.class)); + assertEquals(2, deleteInTx(first, second, third)); + assertEquals(0L, count(SimpleExtendedModel.class)); } @Test @@ -162,15 +179,15 @@ public void deleteInTransactionManyTest() throws Exception { save(model); } } - assertEquals(elementNumber - 1, SugarRecord.count(SimpleExtendedModel.class)); - assertEquals(elementNumber - 1, SugarRecord.deleteInTx(models)); - assertEquals(0L, SugarRecord.count(SimpleExtendedModel.class)); + assertEquals(elementNumber - 1, count(SimpleExtendedModel.class)); + assertEquals(elementNumber - 1, deleteInTx(models)); + assertEquals(0L, count(SimpleExtendedModel.class)); } @Test public void saveInTransactionTest() throws Exception { - SugarRecord.saveInTx(new SimpleExtendedModel(), new SimpleExtendedModel()); - assertEquals(2L, SugarRecord.count(SimpleExtendedModel.class)); + saveInTx(new SimpleExtendedModel(), new SimpleExtendedModel()); + assertEquals(2L, count(SimpleExtendedModel.class)); } @Test @@ -178,10 +195,10 @@ public void listAllTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new SimpleExtendedModel()); } - List models = SugarRecord.listAll(SimpleExtendedModel.class); + List models = listAll(SimpleExtendedModel.class); assertEquals(100, models.size()); for (long i = 1; i <= 100; i++) { - assertEquals(new Long(i), models.get((int) i - 1).getId()); + assertEquals(Long.valueOf(i), models.get((int) i - 1).getId()); } } @@ -189,10 +206,9 @@ public void listAllTest() throws Exception { public void findTest() throws Exception { save(new SimpleExtendedModel()); save(new SimpleExtendedModel()); - List models = - SugarRecord.find(SimpleExtendedModel.class, "id = ?", "2"); + List models = find(SimpleExtendedModel.class, "id = ?", "2"); assertEquals(1, models.size()); - assertEquals(new Long(2L), models.get(0).getId()); + assertEquals(Long.valueOf(2L), models.get(0).getId()); } @Test @@ -200,40 +216,39 @@ public void findWithQueryTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new SimpleExtendedModel()); } - List models = - SugarRecord.findWithQuery(SimpleExtendedModel.class, "Select * from " + - NamingHelper.toSQLName(SimpleExtendedModel.class) + + List models = findWithQuery(SimpleExtendedModel.class, "Select * from " + + NamingHelper.toTableName(SimpleExtendedModel.class) + " where id >= ? ", "50"); for (SimpleExtendedModel model : models) { - assertEquals(new Long(75), model.getId(), 25L); + assertEquals(75, model.getId(), 25L); } } @Test + @SuppressWarnings("all") public void findByIdTest() throws Exception { save(new SimpleExtendedModel()); - assertEquals(new Long(1L), SugarRecord.findById(SimpleExtendedModel.class, 1L).getId()); + assertEquals(Long.valueOf(1L), findById(SimpleExtendedModel.class, 1L).getId()); } @Test public void findByIdIntegerTest() throws Exception { save(new SimpleExtendedModel()); - assertEquals(new Long(1L), SugarRecord.findById(SimpleExtendedModel.class, 1).getId()); + assertEquals(Long.valueOf(1L), findById(SimpleExtendedModel.class, 1).getId()); } @Test public void findByIdStringsNullTest() throws Exception { save(new SimpleExtendedModel()); - assertEquals(0, SugarRecord.findById(SimpleExtendedModel.class, new String[]{""}).size()); + assertEquals(0, findById(SimpleExtendedModel.class, new String[]{""}).size()); } @Test public void findByIdStringsOneTest() throws Exception { save(new SimpleExtendedModel()); - List models = - SugarRecord.findById(SimpleExtendedModel.class, new String[]{"1"}); + List models = findById(SimpleExtendedModel.class, new String[]{"1"}); assertEquals(1, models.size()); - assertEquals(new Long(1L), models.get(0).getId()); + assertEquals(Long.valueOf(1L), models.get(0).getId()); } @Test @@ -241,11 +256,12 @@ public void findByIdStringsTwoTest() throws Exception { save(new SimpleExtendedModel()); save(new SimpleExtendedModel()); save(new SimpleExtendedModel()); - List models = - SugarRecord.findById(SimpleExtendedModel.class, new String[]{"1", "3"}); + + List models = findById(SimpleExtendedModel.class, new String[]{"1", "3"}); + assertEquals(2, models.size()); - assertEquals(new Long(1L), models.get(0).getId()); - assertEquals(new Long(3L), models.get(1).getId()); + assertEquals(Long.valueOf(1L), models.get(0).getId()); + assertEquals(Long.valueOf(3L), models.get(1).getId()); } @Test @@ -253,13 +269,14 @@ public void findByIdStringsManyTest() throws Exception { for (int i = 1; i <= 10; i++) { save(new SimpleExtendedModel()); } - List models = - SugarRecord.findById(SimpleExtendedModel.class, new String[]{"1", "3", "6", "10"}); + + List models = findById(SimpleExtendedModel.class, new String[]{"1", "3", "6", "10"}); + assertEquals(4, models.size()); - assertEquals(new Long(1L), models.get(0).getId()); - assertEquals(new Long(3L), models.get(1).getId()); - assertEquals(new Long(6L), models.get(2).getId()); - assertEquals(new Long(10L), models.get(3).getId()); + assertEquals(Long.valueOf(1L), models.get(0).getId()); + assertEquals(Long.valueOf(3L), models.get(1).getId()); + assertEquals(Long.valueOf(6L), models.get(2).getId()); + assertEquals(Long.valueOf(10L), models.get(3).getId()); } @Test @@ -267,20 +284,21 @@ public void findByIdStringsOrderTest() throws Exception { for (int i = 1; i <= 10; i++) { save(new SimpleExtendedModel()); } - List models = - SugarRecord.findById(SimpleExtendedModel.class, new String[]{"10", "6", "3", "1"}); + + List models = findById(SimpleExtendedModel.class, new String[]{"10", "6", "3", "1"}); + assertEquals(4, models.size()); // The order of the query doesn't matter - assertEquals(new Long(1L), models.get(0).getId()); - assertEquals(new Long(3L), models.get(1).getId()); - assertEquals(new Long(6L), models.get(2).getId()); - assertEquals(new Long(10L), models.get(3).getId()); + assertEquals(Long.valueOf(1L), models.get(0).getId()); + assertEquals(Long.valueOf(3L), models.get(1).getId()); + assertEquals(Long.valueOf(6L), models.get(2).getId()); + assertEquals(Long.valueOf(10L), models.get(3).getId()); } @Test public void findByIdNullTest() throws Exception { save(new SimpleExtendedModel()); - assertNull(SugarRecord.findById(SimpleExtendedModel.class, 2L)); + assertNull(findById(SimpleExtendedModel.class, 2L)); } @Test @@ -288,12 +306,14 @@ public void findAllTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new SimpleExtendedModel()); } - Iterator cursor = SugarRecord.findAll(SimpleExtendedModel.class); + + Iterator cursor = findAll(SimpleExtendedModel.class); + for (int i = 1; i <= 100; i++) { assertTrue(cursor.hasNext()); SimpleExtendedModel model = cursor.next(); assertNotNull(model); - assertEquals(new Long(i), model.getId()); + assertEquals(Long.valueOf(i), model.getId()); } } @@ -302,13 +322,14 @@ public void findAsIteratorTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new SimpleExtendedModel()); } - Iterator cursor = SugarRecord.findAsIterator(SimpleExtendedModel.class, - "id >= ?", "50"); + + Iterator cursor = findAsIterator(SimpleExtendedModel.class, "id >= ?", "50"); + for (int i = 50; i <= 100; i++) { assertTrue(cursor.hasNext()); SimpleExtendedModel model = cursor.next(); assertNotNull(model); - assertEquals(new Long(i), model.getId()); + assertEquals(Long.valueOf(i), model.getId()); } } @@ -317,28 +338,27 @@ public void findWithQueryAsIteratorTest() throws Exception { for (int i = 1; i <= 100; i++) { save(new SimpleExtendedModel()); } - Iterator cursor = - SugarRecord.findWithQueryAsIterator(SimpleExtendedModel.class, + + Iterator cursor = findWithQueryAsIterator(SimpleExtendedModel.class, "Select * from " + - NamingHelper.toSQLName(SimpleExtendedModel.class) + + NamingHelper.toTableName(SimpleExtendedModel.class) + " where id >= ? ", "50"); for (int i = 50; i <= 100; i++) { assertTrue(cursor.hasNext()); SimpleExtendedModel model = cursor.next(); assertNotNull(model); - assertEquals(new Long(i), model.getId()); + assertEquals(Long.valueOf(i), model.getId()); } } @Test(expected=NoSuchElementException.class) public void findAsIteratorOutOfBoundsTest() throws Exception { save(new SimpleExtendedModel()); - Iterator cursor = SugarRecord.findAsIterator(SimpleExtendedModel.class, - "id = ?", "1"); + Iterator cursor = findAsIterator(SimpleExtendedModel.class, id, "1"); assertTrue(cursor.hasNext()); SimpleExtendedModel model = cursor.next(); assertNotNull(model); - assertEquals(new Long(1), model.getId()); + assertEquals(Long.valueOf(1), model.getId()); // This should throw a NoSuchElementException cursor.next(); } @@ -346,18 +366,17 @@ public void findAsIteratorOutOfBoundsTest() throws Exception { @Test(expected=UnsupportedOperationException.class) public void disallowRemoveCursorTest() throws Exception { save(new SimpleExtendedModel()); - Iterator cursor = SugarRecord.findAsIterator(SimpleExtendedModel.class, - "id = ?", "1"); + Iterator cursor = findAsIterator(SimpleExtendedModel.class, id, "1"); assertTrue(cursor.hasNext()); SimpleExtendedModel model = cursor.next(); assertNotNull(model); - assertEquals(new Long(1), model.getId()); + assertEquals(Long.valueOf(1), model.getId()); // This should throw a UnsupportedOperationException cursor.remove(); } @Test public void vacuumTest() throws Exception { - SugarRecord.executeQuery("Vacuum"); + executeQuery("Vacuum"); } } \ No newline at end of file diff --git a/example/src/test/java/com/example/sugartest/StringFieldTests.java b/library/src/test/java/com/orm/record/StringFieldTests.java similarity index 51% rename from example/src/test/java/com/example/sugartest/StringFieldTests.java rename to library/src/test/java/com/orm/record/StringFieldTests.java index afecdf3d..d9641ad7 100644 --- a/example/src/test/java/com/example/sugartest/StringFieldTests.java +++ b/library/src/test/java/com/orm/record/StringFieldTests.java @@ -1,48 +1,51 @@ -package com.example.sugartest; +package com.orm.record; - -import com.example.models.StringFieldAnnotatedModel; -import com.example.models.StringFieldExtendedModel; -import com.orm.SugarRecord; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.StringFieldAnnotatedModel; +import com.orm.model.StringFieldExtendedModel; import org.junit.Test; import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import static com.orm.SugarRecord.save; +import static com.orm.SugarRecord.findById; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @RunWith(RobolectricGradleTestRunner.class) -@Config(sdk=18) -public class StringFieldTests { +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class StringFieldTests { + private String string = "Test String"; + @Test public void nullStringExtendedTest() { save(new StringFieldExtendedModel()); - StringFieldExtendedModel model = SugarRecord.findById(StringFieldExtendedModel.class, 1); + StringFieldExtendedModel model = findById(StringFieldExtendedModel.class, 1); assertNull(model.getString()); } @Test public void nullStringAnnotatedTest() { save(new StringFieldAnnotatedModel()); - StringFieldAnnotatedModel model = SugarRecord.findById(StringFieldAnnotatedModel.class, 1); + StringFieldAnnotatedModel model = findById(StringFieldAnnotatedModel.class, 1); assertNull(model.getString()); } @Test public void stringExtendedTest() { - String string = "Test String"; save(new StringFieldExtendedModel(string)); - StringFieldExtendedModel model = SugarRecord.findById(StringFieldExtendedModel.class, 1); + StringFieldExtendedModel model = findById(StringFieldExtendedModel.class, 1); assertEquals(string, model.getString()); } @Test public void stringAnnotatedTest() { - String string = "Test String"; save(new StringFieldAnnotatedModel(string)); - StringFieldAnnotatedModel model = SugarRecord.findById(StringFieldAnnotatedModel.class, 1); + StringFieldAnnotatedModel model = findById(StringFieldAnnotatedModel.class, 1); assertEquals(string, model.getString()); } } diff --git a/library/src/test/java/com/orm/record/UpdateInTxTest.java b/library/src/test/java/com/orm/record/UpdateInTxTest.java new file mode 100644 index 00000000..2c5a032f --- /dev/null +++ b/library/src/test/java/com/orm/record/UpdateInTxTest.java @@ -0,0 +1,70 @@ +package com.orm.record; + +import com.orm.SugarRecord; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.TestRecord; + +import junit.framework.Assert; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.util.List; + +/** + * @author jonatan.salas + */ +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class UpdateInTxTest { + + @Test + public void testUpdateInTx() { + final TestRecord record = new TestRecord(); + record.setName("lalala"); + + Long id = SugarRecord.save(record); + record.setId(id); + + final TestRecord record1 = new TestRecord(); + record1.setName("lalala"); + + Long id1 = SugarRecord.save(record1); + record1.setId(id1); + + final TestRecord record2 = new TestRecord(); + record2.setName("lalala"); + + Long id2 = SugarRecord.save(record2); + record2.setId(id2); + + final TestRecord record3 = new TestRecord(); + record3.setName("lalala"); + + Long id3 = SugarRecord.save(record3); + record3.setId(id3); + + final TestRecord record4 = new TestRecord(); + record4.setName("lalala"); + + Long id4 = SugarRecord.save(record4); + record.setId(id4); + + record.setName("fulano"); + record1.setName("fulano"); + record2.setName("fulano"); + record3.setName("fulano"); + record4.setName("fulano"); + + SugarRecord.updateInTx(record, record1, record2, record3, record4); + + List list = SugarRecord.listAll(TestRecord.class); + + for (TestRecord r: list) { + Assert.assertEquals(record.getName(), r.getName()); + } + } +} diff --git a/library/src/test/java/com/orm/util/ContextUtilTest.java b/library/src/test/java/com/orm/util/ContextUtilTest.java new file mode 100644 index 00000000..9ce16c7d --- /dev/null +++ b/library/src/test/java/com/orm/util/ContextUtilTest.java @@ -0,0 +1,62 @@ +package com.orm.util; + +import android.content.Context; + +import com.orm.app.ClientApp; +import com.orm.SugarContext; +import com.orm.dsl.BuildConfig; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import static junit.framework.Assert.assertNotNull; +import static junit.framework.Assert.assertNull; +import static com.orm.util.ContextUtil.*; + +/** + * @author jonatan.salas + */ +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class ContextUtilTest { + + @Test(expected = IllegalAccessException.class) + public void testPrivateConstructor() throws Exception { + ContextUtil contextUtil = ContextUtil.class.getDeclaredConstructor().newInstance(); + assertNull(contextUtil); + } + + + @Test + public void testInitContext() { + assertNotNull(getContext()); + } + + @Test + public void testGetAssets() { + assertNotNull(getAssets()); + } + + @Test + public void testGetPackageManager() { + assertNotNull(getPackageManager()); + } + + @Test + public void testGetPackageName() { + assertNotNull(getPackageName()); + } + + @Test + public void testGetPreferences() { + assertNotNull(getSharedPreferences("lala", Context.MODE_PRIVATE)); + } + + @Test + public void testTerminateContext() { + SugarContext.terminate(); + assertNull(getContext()); + } +} diff --git a/library/src/test/java/com/orm/util/KeyWordUtilTest.java b/library/src/test/java/com/orm/util/KeyWordUtilTest.java new file mode 100644 index 00000000..417f1b21 --- /dev/null +++ b/library/src/test/java/com/orm/util/KeyWordUtilTest.java @@ -0,0 +1,36 @@ +package com.orm.util; + +import org.junit.Test; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertNull; + +/** + * @author jonatan.salas + */ +public final class KeyWordUtilTest { + + @Test(expected = IllegalAccessException.class) + public void testPrivateConstructor() throws Exception { + KeyWordUtil keyWordUtil = KeyWordUtil.class.getDeclaredConstructor().newInstance(); + assertNull(keyWordUtil); + } + + @Test + public void testKeyWord() { + assertEquals(true, KeyWordUtil.isKeyword("SELECT")); + assertEquals(true, KeyWordUtil.isKeyword("TRANSACTION")); + assertEquals(true, KeyWordUtil.isKeyword("MATCH")); + assertEquals(true, KeyWordUtil.isKeyword("AS")); + assertEquals(true, KeyWordUtil.isKeyword("NOTNULL")); + assertEquals(true, KeyWordUtil.isKeyword("NOT")); + assertEquals(false, KeyWordUtil.isKeyword("PERSONS")); + assertEquals(false, KeyWordUtil.isKeyword("NAME")); + assertEquals(false, KeyWordUtil.isKeyword("LOCATION")); + } + + @Test + public void testNullKeyword() { + assertEquals(false, KeyWordUtil.isKeyword(null)); + } +} diff --git a/library/src/test/java/com/orm/util/MigrationFileParserTest.java b/library/src/test/java/com/orm/util/MigrationFileParserTest.java new file mode 100644 index 00000000..9b2d87ce --- /dev/null +++ b/library/src/test/java/com/orm/util/MigrationFileParserTest.java @@ -0,0 +1,44 @@ +package com.orm.util; + +import org.junit.Test; + +import java.lang.String; + +import static junit.framework.Assert.assertEquals; + +public final class MigrationFileParserTest { + + @Test + public void testSingleLineStatement() { + MigrationFileParser singleLineComment = new MigrationFileParser("insert into table--comment"); + + String statements[] = singleLineComment.getStatements(); + assertEquals("Testing single line statement size",1,statements.length); + assertEquals("Testing single line statement content","insert into table",statements[0]); + + singleLineComment = new MigrationFileParser("insert into table--comment\n"); + + singleLineComment.getStatements(); + assertEquals("Testing single line statement size",1,statements.length); + assertEquals("Testing single line statement content","insert into table",statements[0]); + } + + @Test + public void testMultiLineComment() { + MigrationFileParser multiLineComment = new MigrationFileParser("insert into table /**comment \n new line 2 \n new line 3 */hello"); + + String statements[] = multiLineComment.getStatements(); + assertEquals("Testing multiline statement size",1,statements.length); + assertEquals("Testing multiline comment","insert into table hello",statements[0]); + } + + @Test + public void testMixedComment() { + MigrationFileParser mixedComment = new MigrationFileParser("insert into/*multiline\n **comment*/--comment"); + + String statements[] = mixedComment.getStatements(); + + assertEquals("Testing mixed comment statement size",1,statements.length); + assertEquals("Testing mixed comment statments", "insert into", statements[0]); + } +} diff --git a/library/src/test/java/com/orm/util/NumberComparatorTest.java b/library/src/test/java/com/orm/util/NumberComparatorTest.java new file mode 100644 index 00000000..aaabf453 --- /dev/null +++ b/library/src/test/java/com/orm/util/NumberComparatorTest.java @@ -0,0 +1,48 @@ +package com.orm.util; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * @author jonatan.salas + */ +public final class NumberComparatorTest { + private NumberComparator comparator; + + @Before + public void setUp() { + comparator = new NumberComparator(); + } + + @Test + public void testNumberComparatorWithoutNumbers() { + int result = comparator.compare("hola", "hola"); + assertEquals(0, result); + } + + @Test + public void testNumberComparatorWithNumbers() { + int result = comparator.compare("1", "2"); + assertEquals(-1, result); + } + + @Test + public void testComparatorWithNumbers() { + int result = comparator.compare("4", "2"); + assertEquals(1, result); + } + + @Test + public void testCompareRight() { + int result = comparator.compareRight("hola", "hola"); + assertEquals(0, result); + } + + @Test + public void testCharAt() { + Character c = NumberComparator.charAt("Hola", 0); + assertEquals("H", c.toString()); + } +} diff --git a/library/src/test/java/com/orm/util/ReflectionUtilTest.java b/library/src/test/java/com/orm/util/ReflectionUtilTest.java new file mode 100644 index 00000000..a93e059a --- /dev/null +++ b/library/src/test/java/com/orm/util/ReflectionUtilTest.java @@ -0,0 +1,99 @@ +package com.orm.util; + +import android.content.ContentValues; +import android.database.Cursor; + +import com.orm.SugarContext; +import com.orm.SugarRecord; +import com.orm.app.ClientApp; +import com.orm.dsl.BuildConfig; +import com.orm.model.TestRecord; +import com.orm.model.foreignnull.OriginRecord; +import com.orm.query.Select; + +import junit.framework.Assert; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +/** + * @author jonatan.salas + */ +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE) +public final class ReflectionUtilTest { + + @Test(expected = IllegalAccessException.class) + public void testPrivateConstructor() throws Exception { + ReflectionUtil reflectionUtil = ReflectionUtil.class.getDeclaredConstructor().newInstance(); + Assert.assertNull(reflectionUtil); + } + + @Test + public void testGetTableFields() { + List fieldList = ReflectionUtil.getTableFields(TestRecord.class); + List strings = new ArrayList<>(); + + for (Field field: fieldList) { + strings.add(field.getName()); + } + + Assert.assertEquals(true, strings.contains("id")); + Assert.assertEquals(true, strings.contains("name")); + } + + @Test(expected = NoSuchFieldException.class) + public void testAddFieldValueToColumn() throws NoSuchFieldException { + SugarContext context = SugarContext.getSugarContext(); + TestRecord record = new TestRecord(); + record.setName("lala"); + + Field column = TestRecord.class.getField("name"); + ContentValues values = new ContentValues(); + + ReflectionUtil.addFieldValueToColumn(values, column, record, context.getEntitiesMap()); + + Assert.assertEquals(record.getName(), values.getAsString("NAME")); + } + + @Test + public void testSetFieldValueForId() { + TestRecord record = new TestRecord(); + record.setName("Bla bla"); + + ReflectionUtil.setFieldValueForId(record, 1L); + Assert.assertEquals(1L, record.getId().longValue()); + } + + @Test + public void testGetAllClasses() { + List classes = ReflectionUtil.getDomainClasses(); + Assert.assertEquals(46, classes.size()); + } + + @Test(expected = NoSuchFieldException.class) + public void testSetFieldValueFromCursor() throws NoSuchFieldException { + final TestRecord record = new TestRecord().setName("bla bla"); + Long id = record.save(); + record.setId(id); + + Cursor cursor = Select.from(TestRecord.class).getCursor(); + + TestRecord testRecord = new TestRecord(); + Field field = TestRecord.class.getField("name"); + + ReflectionUtil.setFieldValueFromCursor(cursor, field, testRecord); + } + + @Test + public void testForeignNull() throws NoSuchFieldException { + final OriginRecord record = new OriginRecord(null,null); + SugarRecord.save(record); + } +} diff --git a/library/src/test/java/com/orm/util/SugarConfigTest.java b/library/src/test/java/com/orm/util/SugarConfigTest.java new file mode 100644 index 00000000..82943e9e --- /dev/null +++ b/library/src/test/java/com/orm/util/SugarConfigTest.java @@ -0,0 +1,33 @@ +package com.orm.util; + +import com.orm.model.TestRecord; + +import junit.framework.Assert; + +import org.junit.Test; + +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.List; + +/** + * @author jonatan.salas + */ +public final class SugarConfigTest { + + @Test + public void testSetGetFields() { + Field[] fields = TestRecord.class.getFields(); + + List fieldList = Arrays.asList(fields); + SugarConfig.setFields(TestRecord.class, fieldList); + + Assert.assertEquals(fieldList, SugarConfig.getFields(TestRecord.class)); + } + + @Test + public void testClearCache() { + SugarConfig.clearCache(); + Assert.assertEquals(true, SugarConfig.fields.isEmpty()); + } +} diff --git a/sugar.iml b/sugar.iml deleted file mode 100644 index e19b5594..00000000 --- a/sugar.iml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file