Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

refactored the tests to reuse more code and clean up connections better

new properties files support to change replication configuration
  • Loading branch information...
commit 00120d5e4d180fcefa47be77929a52e2aa4c9030 1 parent 731ac55
Marty Schoch mschoch authored
Showing with 775 additions and 708 deletions.
  1. +3 −0  TouchDB-Android-TestApp/.gitignore
  2. +1 −0  TouchDB-Android-TestApp/AndroidManifest.xml
  3. +8 −26 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/ektorp/tests/Attachments.java
  4. +15 −32 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/ektorp/tests/CRUDOperations.java
  5. +261 −0 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/ektorp/tests/Replicator.java
  6. +63 −49 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/ektorp/tests/Views.java
  7. +2 −21 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/javascript/tests/JavaScriptDesignDocument.java
  8. +28 −38 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/Attachments.java
  9. +18 −40 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/CRUDOperations.java
  10. +5 −6 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/ChangeTracker.java
  11. +3 −11 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/Changes.java
  12. +10 −32 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/LocalDocs.java
  13. +16 −77 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/Replicator.java
  14. +13 −21 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/RevTree.java
  15. +3 −189 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/Router.java
  16. +5 −36 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/Server.java
  17. +0 −10 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/TestConstants.java
  18. +255 −0 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/TouchDBTestCase.java
  19. +9 −19 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/Validations.java
  20. +46 −101 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/Views.java
  21. +11 −0 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/test.properties
3  TouchDB-Android-TestApp/.gitignore
View
@@ -12,6 +12,9 @@
/bin/
/gen/
+# Local test configuration
+/src/com/couchbase/touchdb/testapp/tests/local-test.properties
+
# Local configuration file (sdk path, etc)
local.properties
build.properties
1  TouchDB-Android-TestApp/AndroidManifest.xml
View
@@ -12,6 +12,7 @@
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.couchbase.touchdb.testapp" />
<uses-permission android:name="android.permission.INTERNET"/>
+<uses-sdk android:minSdkVersion="8"/>
<application
android:icon="@drawable/ic_launcher"
34 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/ektorp/tests/Attachments.java
View
@@ -13,48 +13,30 @@
import org.ektorp.http.HttpClient;
import org.ektorp.impl.StdCouchDbInstance;
-import android.test.AndroidTestCase;
-
-import com.couchbase.touchdb.TDDatabase;
-import com.couchbase.touchdb.TDServer;
import com.couchbase.touchdb.ektorp.TouchDBHttpClient;
-import com.couchbase.touchdb.router.TDURLStreamHandlerFactory;
-
-public class Attachments extends AndroidTestCase {
+import com.couchbase.touchdb.testapp.tests.TouchDBTestCase;
- //static inializer to ensure that touchdb:// URLs are handled properly
- {
- TDURLStreamHandlerFactory.registerSelfIgnoreError();
- }
+public class Attachments extends TouchDBTestCase {
public void testAttachments() throws IOException {
- String filesDir = getContext().getFilesDir().getAbsolutePath();
- TDServer tdserver = new TDServer(filesDir);
-
- //ensure the test is repeatable
- TDDatabase old = tdserver.getExistingDatabaseNamed("ektorp_attachments_test");
- if(old != null) {
- old.deleteDatabase();
- }
-
- HttpClient httpClient = new TouchDBHttpClient(tdserver);
- CouchDbInstance server = new StdCouchDbInstance(httpClient);
+ HttpClient httpClient = new TouchDBHttpClient(server);
+ CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
- CouchDbConnector db = server.createConnector("ektorp_attachments_test", true);
+ CouchDbConnector dbConnector = dbInstance.createConnector(DEFAULT_TEST_DB, true);
TestObject test = new TestObject(1, false, "ektorp");
//create a document
- db.create(test);
+ dbConnector.create(test);
//attach file to it
byte[] attach1 = "This is the body of attach1".getBytes();
ByteArrayInputStream b = new ByteArrayInputStream(attach1);
AttachmentInputStream a = new AttachmentInputStream("attach", b, "text/plain");
- db.createAttachment(test.getId(), test.getRevision(), a);
+ dbConnector.createAttachment(test.getId(), test.getRevision(), a);
- AttachmentInputStream readAttachment = db.getAttachment(test.getId(), "attach");
+ AttachmentInputStream readAttachment = dbConnector.getAttachment(test.getId(), "attach");
Assert.assertEquals("text/plain", readAttachment.getContentType());
Assert.assertEquals("attach", readAttachment.getId());
47 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/ektorp/tests/CRUDOperations.java
View
@@ -14,47 +14,30 @@
import org.ektorp.http.HttpClient;
import org.ektorp.impl.StdCouchDbInstance;
-import android.test.AndroidTestCase;
import android.util.Log;
-import com.couchbase.touchdb.TDDatabase;
-import com.couchbase.touchdb.TDServer;
import com.couchbase.touchdb.ektorp.TouchDBHttpClient;
-import com.couchbase.touchdb.router.TDURLStreamHandlerFactory;
+import com.couchbase.touchdb.testapp.tests.TouchDBTestCase;
-public class CRUDOperations extends AndroidTestCase {
-
- //static inializer to ensure that touchdb:// URLs are handled properly
- {
- TDURLStreamHandlerFactory.registerSelfIgnoreError();
- }
+public class CRUDOperations extends TouchDBTestCase {
public static final String TAG = "Ektorp-CRUDOperations";
public void testCRUDOperations() throws IOException {
- String filesDir = getContext().getFilesDir().getAbsolutePath();
- TDServer tdserver = new TDServer(filesDir);
-
- //ensure the test is repeatable
- TDDatabase old = tdserver.getExistingDatabaseNamed("ektorp_crud_test");
- if(old != null) {
- old.deleteDatabase();
- }
-
- HttpClient httpClient = new TouchDBHttpClient(tdserver);
- CouchDbInstance server = new StdCouchDbInstance(httpClient);
+ HttpClient httpClient = new TouchDBHttpClient(server);
+ CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
- CouchDbConnector db = server.createConnector("ektorp_crud_test", true);
+ CouchDbConnector dbConnector = dbInstance.createConnector(DEFAULT_TEST_DB, true);
TestObject test = new TestObject(1, false, "ektorp");
- db.create(test);
+ dbConnector.create(test);
Assert.assertTrue(test.getId().length() >= 10);
Assert.assertTrue(test.getRevision().startsWith("1-"));
//read it back
- TestObject read = db.get(TestObject.class, test.getId());
+ TestObject read = dbConnector.get(TestObject.class, test.getId());
Assert.assertNotNull(read);
Assert.assertEquals(read.getFoo(), test.getFoo());
Assert.assertEquals(read.getBar(), test.getBar());
@@ -62,18 +45,18 @@ public void testCRUDOperations() throws IOException {
//now update it
read.setStatus("updated!");
- db.update(read);
+ dbConnector.update(read);
Assert.assertEquals(test.getId(), read.getId());
Assert.assertTrue(read.getRevision().startsWith("2-"));
//read it back
- read = db.get(TestObject.class, read.getId());
+ read = dbConnector.get(TestObject.class, read.getId());
Assert.assertNotNull(read);
Assert.assertEquals("updated!", read.getStatus());
// try to update the first rev, which should fail:
try {
- db.update(test);
+ dbConnector.update(test);
fail("expected update conflict exception");
} catch (UpdateConflictException e) {
//expected
@@ -81,23 +64,23 @@ public void testCRUDOperations() throws IOException {
// check the changes feed
ChangesCommand changesCommand = new ChangesCommand.Builder().continuous(false).since(0l).build();
- List<DocumentChange> changes = db.changes(changesCommand);
+ List<DocumentChange> changes = dbConnector.changes(changesCommand);
Log.v(TAG, "changes: " + changes);
Assert.assertEquals(1, changes.size());
// delete it
try {
- db.delete(test);
+ dbConnector.delete(test);
fail("expected update conflict exception");
} catch (UpdateConflictException e) {
//expected
}
- String deletedRev = db.delete(read);
+ String deletedRev = dbConnector.delete(read);
Assert.assertTrue(deletedRev.startsWith("3-"));
// delete nonexistent doc
try {
- db.delete("fakeid", "6-");
+ dbConnector.delete("fakeid", "6-");
fail("expected document not found exception");
} catch (DocumentNotFoundException e) {
//expected
@@ -105,7 +88,7 @@ public void testCRUDOperations() throws IOException {
//read back the deleted document
try {
- read = db.get(TestObject.class, test.getId());
+ read = dbConnector.get(TestObject.class, test.getId());
fail("expected document not found exception");
} catch (DocumentNotFoundException e) {
//expected
261 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/ektorp/tests/Replicator.java
View
@@ -0,0 +1,261 @@
+package com.couchbase.touchdb.testapp.ektorp.tests;
+
+import java.io.IOException;
+
+import junit.framework.Assert;
+
+import org.apache.http.HttpException;
+import org.apache.http.HttpHost;
+import org.apache.http.HttpRequest;
+import org.apache.http.HttpRequestInterceptor;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.AuthState;
+import org.apache.http.auth.Credentials;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.client.protocol.ClientContext;
+import org.apache.http.impl.auth.BasicScheme;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.protocol.ExecutionContext;
+import org.apache.http.protocol.HttpContext;
+import org.ektorp.CouchDbConnector;
+import org.ektorp.CouchDbInstance;
+import org.ektorp.ReplicationCommand;
+import org.ektorp.ReplicationStatus;
+import org.ektorp.http.HttpClient;
+import org.ektorp.impl.StdCouchDbInstance;
+
+import com.couchbase.touchdb.TDDatabase;
+import com.couchbase.touchdb.TDFilterBlock;
+import com.couchbase.touchdb.TDRevision;
+import com.couchbase.touchdb.ektorp.TouchDBHttpClient;
+import com.couchbase.touchdb.support.HttpClientFactory;
+import com.couchbase.touchdb.testapp.tests.TouchDBTestCase;
+
+public class Replicator extends TouchDBTestCase {
+
+ public void testPush() throws IOException {
+
+ HttpClient httpClient = new TouchDBHttpClient(server);
+ CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
+
+ // create a local database
+ CouchDbConnector dbConnector = dbInstance.createConnector(DEFAULT_TEST_DB, true);
+
+ // create 3 objects
+ TestObject test1 = new TestObject(1, false, "ektorp-1");
+ TestObject test2 = new TestObject(2, false, "ektorp-2");
+ TestObject test3 = new TestObject(3, false, "ektorp-3");
+
+ // save these objects in the database
+ dbConnector.create(test1);
+ dbConnector.create(test2);
+ dbConnector.create(test3);
+
+ // push this database to the test replication server
+ ReplicationCommand pushCommand = new ReplicationCommand.Builder()
+ .source(DEFAULT_TEST_DB)
+ .target(getReplicationURL().toExternalForm())
+ .continuous(false)
+ .createTarget(true)
+ .build();
+
+ ReplicationStatus status = dbInstance.replicate(pushCommand);
+ try {
+ Thread.sleep(60*1000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ Assert.assertNotNull(status.getSessionId());
+
+ }
+
+ public void testFilteredPush() throws IOException {
+
+ // install the filter
+ database.defineFilter("evenFoo", new TDFilterBlock() {
+
+ @Override
+ public boolean filter(TDRevision revision) {
+ Integer foo = (Integer)revision.getProperties().get("foo");
+ if(foo != null && foo.intValue() % 2 == 0) {
+ return true;
+ }
+ return false;
+ }
+ });
+
+ HttpClient httpClient = new TouchDBHttpClient(server);
+ CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
+
+ // create a local database
+ CouchDbConnector dbConnector = dbInstance.createConnector(DEFAULT_TEST_DB, true);
+
+ // create 3 objects
+ TestObject test1 = new TestObject(1, false, "ektorp-1");
+ TestObject test2 = new TestObject(2, false, "ektorp-2");
+ TestObject test3 = new TestObject(3, false, "ektorp-3");
+
+ // save these objects in the database
+ dbConnector.create(test1);
+ dbConnector.create(test2);
+ dbConnector.create(test3);
+
+ // push this database to the test replication server
+ ReplicationCommand pushCommand = new ReplicationCommand.Builder()
+ .source(DEFAULT_TEST_DB)
+ .target(getReplicationURL().toExternalForm())
+ .continuous(false)
+ .filter("evenFoo")
+ .build();
+
+ ReplicationStatus status = dbInstance.replicate(pushCommand);
+ try {
+ Thread.sleep(60*1000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ Assert.assertNotNull(status.getSessionId());
+
+ }
+
+ public void testPull() throws IOException {
+
+ HttpClient httpClient = new TouchDBHttpClient(server);
+ CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
+
+ // create a local database
+ CouchDbConnector dbConnector = dbInstance.createConnector(DEFAULT_TEST_DB, true);
+
+ // push this database to the test replication server
+ ReplicationCommand pushCommand = new ReplicationCommand.Builder()
+ .source(getReplicationURL().toExternalForm())
+ .target(DEFAULT_TEST_DB)
+ .continuous(false)
+ .build();
+
+ ReplicationStatus status = dbInstance.replicate(pushCommand);
+ try {
+ Thread.sleep(60*1000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ Assert.assertNotNull(status.getSessionId());
+
+ }
+
+ public void testPullWithoutCredentialsInURL() throws IOException {
+
+ server.setDefaultHttpClientFactory(new HttpClientFactory() {
+
+ @Override
+ public org.apache.http.client.HttpClient getHttpClient() {
+ DefaultHttpClient httpClient = new DefaultHttpClient();
+
+ BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
+
+ //store whatever credentials we have in the credentials provider
+ AuthScope authScope = new AuthScope(getReplicationServer(), getReplicationPort());
+ Credentials authCredentials = new UsernamePasswordCredentials(getReplicationAdminUser(), getReplicationAdminPassword());
+ credsProvider.setCredentials(authScope, authCredentials);
+
+ httpClient.setCredentialsProvider(credsProvider);
+
+ //set credentials pre-emptively
+ HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
+
+ @Override
+ public void process(HttpRequest request,
+ HttpContext context) throws HttpException,
+ IOException {
+ AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
+ CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
+ ClientContext.CREDS_PROVIDER);
+ HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
+
+ if (authState.getAuthScheme() == null) {
+ AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
+ Credentials creds = credsProvider.getCredentials(authScope);
+ authState.setCredentials(creds);
+ authState.setAuthScheme(new BasicScheme());
+ }
+ }
+ };
+
+ httpClient.addRequestInterceptor(preemptiveAuth, 0);
+
+ return httpClient;
+ }
+ });
+
+ HttpClient httpClient = new TouchDBHttpClient(server);
+ CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
+
+ // create a local database
+ CouchDbConnector dbConnector = dbInstance.createConnector(DEFAULT_TEST_DB, true);
+
+ // push this database to the test replication server
+ ReplicationCommand pushCommand = new ReplicationCommand.Builder()
+ .source(getReplicationURLWithoutCredentials().toExternalForm())
+ .target(DEFAULT_TEST_DB)
+ .continuous(false)
+ .build();
+
+ ReplicationStatus status = dbInstance.replicate(pushCommand);
+ try {
+ Thread.sleep(60*1000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ Assert.assertNotNull(status.getSessionId());
+
+ }
+
+ public void testPushToLocal() throws IOException {
+
+ TDDatabase other = server.getExistingDatabaseNamed(DEFAULT_TEST_DB + "2");
+ if(other != null) {
+ other.deleteDatabase();
+ }
+
+ HttpClient httpClient = new TouchDBHttpClient(server);
+ CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
+
+ // create a local database
+ CouchDbConnector dbConnector = dbInstance.createConnector(DEFAULT_TEST_DB, true);
+
+ // create 3 objects
+ TestObject test1 = new TestObject(1, false, "ektorp-1");
+ TestObject test2 = new TestObject(2, false, "ektorp-2");
+ TestObject test3 = new TestObject(3, false, "ektorp-3");
+
+ // save these objects in the database
+ dbConnector.create(test1);
+ dbConnector.create(test2);
+ dbConnector.create(test3);
+
+ // push this database to the test replication server
+ ReplicationCommand pushCommand = new ReplicationCommand.Builder()
+ .source(DEFAULT_TEST_DB)
+ .target(DEFAULT_TEST_DB + "2")
+ .continuous(false)
+ .createTarget(true)
+ .build();
+
+ ReplicationStatus status = dbInstance.replicate(pushCommand);
+ try {
+ Thread.sleep(60*1000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ Assert.assertNotNull(status.getSessionId());
+
+ }
+
+}
112 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/ektorp/tests/Views.java
View
@@ -14,23 +14,15 @@
import org.ektorp.http.HttpClient;
import org.ektorp.impl.StdCouchDbInstance;
-import android.test.AndroidTestCase;
-
import com.couchbase.touchdb.TDDatabase;
-import com.couchbase.touchdb.TDServer;
import com.couchbase.touchdb.TDView;
import com.couchbase.touchdb.TDViewMapBlock;
import com.couchbase.touchdb.TDViewMapEmitBlock;
import com.couchbase.touchdb.TDViewReduceBlock;
import com.couchbase.touchdb.ektorp.TouchDBHttpClient;
-import com.couchbase.touchdb.router.TDURLStreamHandlerFactory;
-
-public class Views extends AndroidTestCase {
+import com.couchbase.touchdb.testapp.tests.TouchDBTestCase;
- //static inializer to ensure that touchdb:// URLs are handled properly
- {
- TDURLStreamHandlerFactory.registerSelfIgnoreError();
- }
+public class Views extends TouchDBTestCase {
public static final String dDocName = "ddoc";
public static final String dDocId = "_design/" + dDocName;
@@ -97,26 +89,16 @@ public Object reduce(List<Object> keys, List<Object> values,
public void testViewQuery() throws IOException {
- String filesDir = getContext().getFilesDir().getAbsolutePath();
- TDServer tdserver = new TDServer(filesDir);
-
- //ensure the test is repeatable
- TDDatabase old = tdserver.getExistingDatabaseNamed("ektorp_views_test");
- if(old != null) {
- old.deleteDatabase();
- }
+ HttpClient httpClient = new TouchDBHttpClient(server);
+ CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
- HttpClient httpClient = new TouchDBHttpClient(tdserver);
- CouchDbInstance server = new StdCouchDbInstance(httpClient);
+ CouchDbConnector dbConnector = dbInstance.createConnector(DEFAULT_TEST_DB, true);
- CouchDbConnector db = server.createConnector("ektorp_views_test", true);
- TDDatabase tdDb = tdserver.getExistingDatabaseNamed("ektorp_views_test");
-
- putDocs(db);
- createView(tdDb);
+ putDocs(dbConnector);
+ createView(database);
ViewQuery query = new ViewQuery().designDocId(dDocId).viewName(viewName);
- ViewResult result = db.queryView(query);
+ ViewResult result = dbConnector.queryView(query);
Assert.assertEquals(5, result.getTotalRows());
Assert.assertEquals("five", result.getRows().get(0).getKey());
Assert.assertEquals("four", result.getRows().get(1).getKey());
@@ -126,7 +108,7 @@ public void testViewQuery() throws IOException {
// Start/end key query:
query = new ViewQuery().designDocId(dDocId).viewName(viewName).startKey("a").endKey("one");
- result = db.queryView(query);
+ result = dbConnector.queryView(query);
Assert.assertEquals(3, result.getTotalRows());
Assert.assertEquals("five", result.getRows().get(0).getKey());
Assert.assertEquals("four", result.getRows().get(1).getKey());
@@ -134,21 +116,21 @@ public void testViewQuery() throws IOException {
// Start/end query without inclusive end:
query = new ViewQuery().designDocId(dDocId).viewName(viewName).startKey("a").endKey("one").inclusiveEnd(false);
- result = db.queryView(query);
+ result = dbConnector.queryView(query);
Assert.assertEquals(2, result.getTotalRows());
Assert.assertEquals("five", result.getRows().get(0).getKey());
Assert.assertEquals("four", result.getRows().get(1).getKey());
// Reversed:
query = new ViewQuery().designDocId(dDocId).viewName(viewName).startKey("o").endKey("five").inclusiveEnd(true).descending(true);
- result = db.queryView(query);
+ result = dbConnector.queryView(query);
Assert.assertEquals(2, result.getTotalRows());
Assert.assertEquals("four", result.getRows().get(0).getKey());
Assert.assertEquals("five", result.getRows().get(1).getKey());
// Reversed, no inclusive end:
query = new ViewQuery().designDocId(dDocId).viewName(viewName).startKey("o").endKey("five").inclusiveEnd(false).descending(true);
- result = db.queryView(query);
+ result = dbConnector.queryView(query);
Assert.assertEquals(1, result.getTotalRows());
Assert.assertEquals("four", result.getRows().get(0).getKey());
@@ -157,14 +139,14 @@ public void testViewQuery() throws IOException {
keys.add("two");
keys.add("four");
query = new ViewQuery().designDocId(dDocId).viewName(viewName).keys(keys);
- result = db.queryView(query);
+ result = dbConnector.queryView(query);
Assert.assertEquals(2, result.getTotalRows());
Assert.assertEquals("four", result.getRows().get(0).getKey());
Assert.assertEquals("two", result.getRows().get(1).getKey());
// Limit
query = new ViewQuery().designDocId(dDocId).viewName(viewName).limit(3);
- result = db.queryView(query);
+ result = dbConnector.queryView(query);
Assert.assertEquals(3, result.getTotalRows());
Assert.assertEquals("five", result.getRows().get(0).getKey());
Assert.assertEquals("four", result.getRows().get(1).getKey());
@@ -172,7 +154,7 @@ public void testViewQuery() throws IOException {
// Limit & Skip
query = new ViewQuery().designDocId(dDocId).viewName(viewName).limit(2).skip(1);
- result = db.queryView(query);
+ result = dbConnector.queryView(query);
Assert.assertEquals(2, result.getTotalRows());
Assert.assertEquals("four", result.getRows().get(0).getKey());
Assert.assertEquals("one", result.getRows().get(1).getKey());
@@ -180,28 +162,60 @@ public void testViewQuery() throws IOException {
public void testViewReduceQuery() throws IOException {
- String filesDir = getContext().getFilesDir().getAbsolutePath();
- TDServer tdserver = new TDServer(filesDir);
-
- //ensure the test is repeatable
- TDDatabase old = tdserver.getExistingDatabaseNamed("ektorp_views_test");
- if(old != null) {
- old.deleteDatabase();
- }
+ HttpClient httpClient = new TouchDBHttpClient(server);
+ CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
- HttpClient httpClient = new TouchDBHttpClient(tdserver);
- CouchDbInstance server = new StdCouchDbInstance(httpClient);
+ CouchDbConnector dbConnector = dbInstance.createConnector(DEFAULT_TEST_DB, true);
- CouchDbConnector db = server.createConnector("ektorp_views_test", true);
- TDDatabase tdDb = tdserver.getExistingDatabaseNamed("ektorp_views_test");
+ putDocs(dbConnector);
+ createViewWithReduce(database);
- putDocs(db);
- createViewWithReduce(tdDb);
- ViewQuery query = new ViewQuery().designDocId(dDocId).viewName(viewReduceName).reduce(true);
- ViewResult result = db.queryView(query);
+ //because this view has a reduce function it should default to reduce=true
+ ViewQuery query = new ViewQuery().designDocId(dDocId).viewName(viewReduceName);
+ ViewResult result = dbConnector.queryView(query);
Assert.assertEquals(1, result.getTotalRows());
Assert.assertEquals(5, result.getRows().get(0).getValueAsInt());
+
+ //we should still be able to override it and force reduce=false
+ query = new ViewQuery().designDocId(dDocId).viewName(viewReduceName).reduce(false);
+ result = dbConnector.queryView(query);
+
+ Assert.assertEquals(5, result.getTotalRows());
+ }
+
+ public void testViewQueryFromWeb() throws IOException {
+
+ HttpClient httpClient = new TouchDBHttpClient(server);
+ CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
+
+ CouchDbConnector couchDbConnector = dbInstance.createConnector(DEFAULT_TEST_DB, true);
+
+ String dDocName = "ddoc";
+ String viewName = "people";
+ TDView view = database.getViewNamed(String.format("%s/%s", dDocName, viewName));
+
+ view.setMapReduceBlocks(new TDViewMapBlock() {
+
+ @Override
+ public void map(Map<String, Object> document, TDViewMapEmitBlock emitter) {
+ String type = (String)document.get("type");
+ if("person".equals(type)) {
+ emitter.emit(null, document.get("_id"));
+ }
+ }
+ }, new TDViewReduceBlock() {
+ public Object reduce(List<Object> keys, List<Object> values, boolean rereduce) {
+ return null;
+ }
+ }, "1.0");
+
+ ViewQuery viewQuery = new ViewQuery().designDocId("_design/" + dDocName).viewName(viewName);
+ //viewQuery.descending(true); //use this to reverse the sorting order of the view
+ ViewResult viewResult = couchDbConnector.queryView(viewQuery);
+
+ Assert.assertEquals(0, viewResult.getTotalRows());
+
}
}
23 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/javascript/tests/JavaScriptDesignDocument.java
View
@@ -1,28 +1,19 @@
package com.couchbase.touchdb.testapp.javascript.tests;
-import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import com.couchbase.touchdb.TDServer;
import com.couchbase.touchdb.TDStatus;
import com.couchbase.touchdb.TDView;
import com.couchbase.touchdb.javascript.TDJavaScriptViewCompiler;
-import com.couchbase.touchdb.testapp.tests.Router;
+import com.couchbase.touchdb.testapp.tests.TouchDBTestCase;
-public class JavaScriptDesignDocument extends Router {
+public class JavaScriptDesignDocument extends TouchDBTestCase {
public void testJavaScriptDesignDocument() {
- TDServer server = null;
- try {
- server = new TDServer(getServerPath());
- } catch (IOException e) {
- fail("Creating server caused IOException");
- }
-
//register the javascript view compilter
TDView.setCompiler(new TDJavaScriptViewCompiler());
@@ -80,18 +71,10 @@ public void testJavaScriptDesignDocument() {
// Query the view and check the result:
send(server, "GET", "/db/_design/doc/_view/test", TDStatus.OK, expectedResult);
- server.close();
}
public void testRealJavaScriptDesignDocument() {
- TDServer server = null;
- try {
- server = new TDServer(getServerPath());
- } catch (IOException e) {
- fail("Creating server caused IOException");
- }
-
//register the javascript view compilter
TDView.setCompiler(new TDJavaScriptViewCompiler());
@@ -178,8 +161,6 @@ public void testRealJavaScriptDesignDocument() {
// Query the view and check the result:
Object res = send(server, "GET", "/rhinodb/_design/doc/_view/test", TDStatus.OK, expectedResult);
-
- server.close();
}
}
66 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/Attachments.java
View
@@ -29,8 +29,6 @@
import org.apache.commons.io.IOUtils;
-import android.test.AndroidTestCase;
-
import com.couchbase.touchdb.TDAttachment;
import com.couchbase.touchdb.TDBlobKey;
import com.couchbase.touchdb.TDBlobStore;
@@ -39,17 +37,14 @@
import com.couchbase.touchdb.TDStatus;
import com.couchbase.touchdb.support.Base64;
-public class Attachments extends AndroidTestCase {
+public class Attachments extends TouchDBTestCase {
public static final String TAG = "Attachments";
@SuppressWarnings("unchecked")
public void testAttachments() throws Exception {
- String filesDir = getContext().getFilesDir().getAbsolutePath();
-
- TDDatabase db = TDDatabase.createEmptyDBAtPath(filesDir + "/touch_couch_test.sqlite3");
- TDBlobStore attachments = db.getAttachments();
+ TDBlobStore attachments = database.getAttachments();
Assert.assertEquals(0, attachments.count());
Assert.assertEquals(new HashSet<Object>(), attachments.allKeys());
@@ -58,15 +53,15 @@ public void testAttachments() throws Exception {
Map<String,Object> rev1Properties = new HashMap<String,Object>();
rev1Properties.put("foo", 1);
rev1Properties.put("bar", false);
- TDRevision rev1 = db.putRevision(new TDRevision(rev1Properties), null, false, status);
+ TDRevision rev1 = database.putRevision(new TDRevision(rev1Properties), null, false, status);
Assert.assertEquals(TDStatus.CREATED, status.getCode());
byte[] attach1 = "This is the body of attach1".getBytes();
- status = db.insertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream(attach1), rev1.getSequence(), "attach", "text/plain", rev1.getGeneration());
+ status = database.insertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream(attach1), rev1.getSequence(), "attach", "text/plain", rev1.getGeneration());
Assert.assertEquals(TDStatus.CREATED, status.getCode());
- TDAttachment attachment = db.getAttachmentForSequence(rev1.getSequence(), "attach", status);
+ TDAttachment attachment = database.getAttachmentForSequence(rev1.getSequence(), "attach", status);
Assert.assertEquals(TDStatus.OK, status.getCode());
Assert.assertEquals("text/plain", attachment.getContentType());
byte[] data = IOUtils.toByteArray(attachment.getContentStream());
@@ -81,20 +76,20 @@ public void testAttachments() throws Exception {
Map<String,Object> attachmentDict = new HashMap<String,Object>();
attachmentDict.put("attach", innerDict);
- Map<String,Object> attachmentDictForSequence = db.getAttachmentsDictForSequenceWithContent(rev1.getSequence(), false);
+ Map<String,Object> attachmentDictForSequence = database.getAttachmentsDictForSequenceWithContent(rev1.getSequence(), false);
Assert.assertEquals(attachmentDict, attachmentDictForSequence);
- TDRevision gotRev1 = db.getDocumentWithIDAndRev(rev1.getDocId(), rev1.getRevId(), EnumSet.noneOf(TDDatabase.TDContentOptions.class));
+ TDRevision gotRev1 = database.getDocumentWithIDAndRev(rev1.getDocId(), rev1.getRevId(), EnumSet.noneOf(TDDatabase.TDContentOptions.class));
Map<String,Object> gotAttachmentDict = (Map<String,Object>)gotRev1.getProperties().get("_attachments");
Assert.assertEquals(attachmentDict, gotAttachmentDict);
// Check the attachment dict, with attachments included:
innerDict.remove("stub");
innerDict.put("data", Base64.encodeBytes(attach1));
- attachmentDictForSequence = db.getAttachmentsDictForSequenceWithContent(rev1.getSequence(), true);
+ attachmentDictForSequence = database.getAttachmentsDictForSequenceWithContent(rev1.getSequence(), true);
Assert.assertEquals(attachmentDict, attachmentDictForSequence);
- gotRev1 = db.getDocumentWithIDAndRev(rev1.getDocId(), rev1.getRevId(), EnumSet.of(TDDatabase.TDContentOptions.TDIncludeAttachments));
+ gotRev1 = database.getDocumentWithIDAndRev(rev1.getDocId(), rev1.getRevId(), EnumSet.of(TDDatabase.TDContentOptions.TDIncludeAttachments));
gotAttachmentDict = (Map<String,Object>)gotRev1.getProperties().get("_attachments");
Assert.assertEquals(attachmentDict, gotAttachmentDict);
@@ -104,10 +99,10 @@ public void testAttachments() throws Exception {
rev2Properties.put("_id", rev1.getDocId());
rev2Properties.put("foo", 2);
rev2Properties.put("bazz", false);
- TDRevision rev2 = db.putRevision(new TDRevision(rev2Properties), rev1.getRevId(), false, status);
+ TDRevision rev2 = database.putRevision(new TDRevision(rev2Properties), rev1.getRevId(), false, status);
Assert.assertEquals(TDStatus.CREATED, status.getCode());
- status = db.copyAttachmentNamedFromSequenceToSequence("attach", rev1.getSequence(), rev2.getSequence());
+ status = database.copyAttachmentNamedFromSequenceToSequence("attach", rev1.getSequence(), rev2.getSequence());
Assert.assertEquals(TDStatus.OK, status.getCode());
// Add a third revision of the same document:
@@ -115,22 +110,22 @@ public void testAttachments() throws Exception {
rev3Properties.put("_id", rev2.getDocId());
rev3Properties.put("foo", 2);
rev3Properties.put("bazz", false);
- TDRevision rev3 = db.putRevision(new TDRevision(rev3Properties), rev2.getRevId(), false, status);
+ TDRevision rev3 = database.putRevision(new TDRevision(rev3Properties), rev2.getRevId(), false, status);
Assert.assertEquals(TDStatus.CREATED, status.getCode());
byte[] attach2 = "<html>And this is attach2</html>".getBytes();
- status = db.insertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream(attach2), rev3.getSequence(), "attach", "text/html", rev2.getGeneration());
+ status = database.insertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream(attach2), rev3.getSequence(), "attach", "text/html", rev2.getGeneration());
Assert.assertEquals(TDStatus.CREATED, status.getCode());
// Check the 2nd revision's attachment:
- TDAttachment attachment2 = db.getAttachmentForSequence(rev2.getSequence(), "attach", status);
+ TDAttachment attachment2 = database.getAttachmentForSequence(rev2.getSequence(), "attach", status);
Assert.assertEquals(TDStatus.OK, status.getCode());
Assert.assertEquals("text/plain", attachment2.getContentType());
data = IOUtils.toByteArray(attachment2.getContentStream());
Assert.assertTrue(Arrays.equals(attach1, data));
// Check the 3rd revision's attachment:
- TDAttachment attachment3 = db.getAttachmentForSequence(rev3.getSequence(), "attach", status);
+ TDAttachment attachment3 = database.getAttachmentForSequence(rev3.getSequence(), "attach", status);
Assert.assertEquals(TDStatus.OK, status.getCode());
Assert.assertEquals("text/html", attachment3.getContentType());
data = IOUtils.toByteArray(attachment3.getContentStream());
@@ -144,24 +139,19 @@ public void testAttachments() throws Exception {
Assert.assertEquals(expected, attachments.allKeys());
- status = db.compact(); // This clears the body of the first revision
+ status = database.compact(); // This clears the body of the first revision
Assert.assertEquals(TDStatus.OK, status.getCode());
Assert.assertEquals(1, attachments.count());
Set<TDBlobKey> expected2 = new HashSet<TDBlobKey>();
expected2.add(TDBlobStore.keyForBlob(attach2));
Assert.assertEquals(expected2, attachments.allKeys());
-
- db.close();
}
@SuppressWarnings("unchecked")
public void testPutAttachment() {
- String filesDir = getContext().getFilesDir().getAbsolutePath();
-
- TDDatabase db = TDDatabase.createEmptyDBAtPath(filesDir + "/touch_couch_test.sqlite3");
- TDBlobStore attachments = db.getAttachments();
+ TDBlobStore attachments = database.getAttachments();
// Put a revision that includes an _attachments dict:
byte[] attach1 = "This is the body of attach1".getBytes();
@@ -178,14 +168,14 @@ public void testPutAttachment() {
properties.put("_attachments", attachmentDict);
TDStatus status = new TDStatus();
- TDRevision rev1 = db.putRevision(new TDRevision(properties), null, false, status);
+ TDRevision rev1 = database.putRevision(new TDRevision(properties), null, false, status);
Assert.assertEquals(TDStatus.CREATED, status.getCode());
// Examine the attachment store:
Assert.assertEquals(1, attachments.count());
// Get the revision:
- TDRevision gotRev1 = db.getDocumentWithIDAndRev(rev1.getDocId(), rev1.getRevId(), EnumSet.noneOf(TDDatabase.TDContentOptions.class));
+ TDRevision gotRev1 = database.getDocumentWithIDAndRev(rev1.getDocId(), rev1.getRevId(), EnumSet.noneOf(TDDatabase.TDContentOptions.class));
Map<String,Object> gotAttachmentDict = (Map<String,Object>)gotRev1.getProperties().get("_attachments");
Map<String,Object> innerDict = new HashMap<String,Object>();
@@ -202,17 +192,17 @@ public void testPutAttachment() {
// Update the attachment directly:
byte[] attachv2 = "Replaced body of attach".getBytes();
- db.updateAttachment("attach", new ByteArrayInputStream(attachv2), "application/foo", rev1.getDocId(), null, status);
+ database.updateAttachment("attach", new ByteArrayInputStream(attachv2), "application/foo", rev1.getDocId(), null, status);
Assert.assertEquals(TDStatus.CONFLICT, status.getCode());
- db.updateAttachment("attach", new ByteArrayInputStream(attachv2), "application/foo", rev1.getDocId(), "1-bogus", status);
+ database.updateAttachment("attach", new ByteArrayInputStream(attachv2), "application/foo", rev1.getDocId(), "1-bogus", status);
Assert.assertEquals(TDStatus.CONFLICT, status.getCode());
- TDRevision rev2 = db.updateAttachment("attach", new ByteArrayInputStream(attachv2), "application/foo", rev1.getDocId(), rev1.getRevId(), status);
+ TDRevision rev2 = database.updateAttachment("attach", new ByteArrayInputStream(attachv2), "application/foo", rev1.getDocId(), rev1.getRevId(), status);
Assert.assertEquals(TDStatus.CREATED, status.getCode());
Assert.assertEquals(rev1.getDocId(), rev2.getDocId());
Assert.assertEquals(2, rev2.getGeneration());
// Get the updated revision:
- TDRevision gotRev2 = db.getDocumentWithIDAndRev(rev2.getDocId(), rev2.getRevId(), EnumSet.noneOf(TDDatabase.TDContentOptions.class));
+ TDRevision gotRev2 = database.getDocumentWithIDAndRev(rev2.getDocId(), rev2.getRevId(), EnumSet.noneOf(TDDatabase.TDContentOptions.class));
attachmentDict = (Map<String, Object>) gotRev2.getProperties().get("_attachments");
innerDict = new HashMap<String,Object>();
@@ -227,23 +217,23 @@ public void testPutAttachment() {
Assert.assertEquals(expectAttachmentDict, attachmentDict);
// Delete the attachment:
- db.updateAttachment("nosuchattach", null, null, rev2.getDocId(), rev2.getRevId(), status);
+ database.updateAttachment("nosuchattach", null, null, rev2.getDocId(), rev2.getRevId(), status);
Assert.assertEquals(TDStatus.NOT_FOUND, status.getCode());
- db.updateAttachment("nosuchattach", null, null, "nosuchdoc", "nosuchrev", status);
+ database.updateAttachment("nosuchattach", null, null, "nosuchdoc", "nosuchrev", status);
Assert.assertEquals(TDStatus.NOT_FOUND, status.getCode());
- TDRevision rev3 = db.updateAttachment("attach", null, null, rev2.getDocId(), rev2.getRevId(), status);
+ TDRevision rev3 = database.updateAttachment("attach", null, null, rev2.getDocId(), rev2.getRevId(), status);
Assert.assertEquals(TDStatus.OK, status.getCode());
Assert.assertEquals(rev2.getDocId(), rev3.getDocId());
Assert.assertEquals(3, rev3.getGeneration());
// Get the updated revision:
- TDRevision gotRev3 = db.getDocumentWithIDAndRev(rev3.getDocId(), rev3.getRevId(), EnumSet.noneOf(TDDatabase.TDContentOptions.class));
+ TDRevision gotRev3 = database.getDocumentWithIDAndRev(rev3.getDocId(), rev3.getRevId(), EnumSet.noneOf(TDDatabase.TDContentOptions.class));
attachmentDict = (Map<String, Object>) gotRev3.getProperties().get("_attachments");
Assert.assertNull(attachmentDict);
- db.close();
+ database.close();
}
}
58 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/CRUDOperations.java
View
@@ -25,7 +25,6 @@
import java.util.Observer;
import junit.framework.Assert;
-import android.test.AndroidTestCase;
import android.util.Log;
import com.couchbase.touchdb.TDBody;
@@ -35,20 +34,16 @@
import com.couchbase.touchdb.TDRevisionList;
import com.couchbase.touchdb.TDStatus;
-public class CRUDOperations extends AndroidTestCase implements Observer {
+public class CRUDOperations extends TouchDBTestCase implements Observer {
public static final String TAG = "CRUDOperations";
public void testCRUDOperations() {
- String filesDir = getContext().getFilesDir().getAbsolutePath();
+ database.addObserver(this);
- TDDatabase db = TDDatabase.createEmptyDBAtPath(filesDir + "/touch_couch_test.sqlite3");
-
- db.addObserver(this);
-
- String privateUUID = db.privateUUID();
- String publicUUID = db.publicUUID();
+ String privateUUID = database.privateUUID();
+ String publicUUID = database.publicUUID();
Log.v(TAG, "DB private UUID = '" + privateUUID + "', public UUID = '" + publicUUID + "'");
Assert.assertTrue(privateUUID.length() >= 20);
Assert.assertTrue(publicUUID.length() >= 20);
@@ -63,7 +58,7 @@ public void testCRUDOperations() {
TDRevision rev1 = new TDRevision(body);
TDStatus status = new TDStatus();
- rev1 = db.putRevision(rev1, null, false, status);
+ rev1 = database.putRevision(rev1, null, false, status);
Assert.assertEquals(TDStatus.CREATED, status.getCode());
Log.v(TAG, "Created " + rev1);
@@ -71,7 +66,7 @@ public void testCRUDOperations() {
Assert.assertTrue(rev1.getRevId().startsWith("1-"));
//read it back
- TDRevision readRev = db.getDocumentWithIDAndRev(rev1.getDocId(), null, EnumSet.noneOf(TDDatabase.TDContentOptions.class));
+ TDRevision readRev = database.getDocumentWithIDAndRev(rev1.getDocId(), null, EnumSet.noneOf(TDDatabase.TDContentOptions.class));
Assert.assertNotNull(readRev);
Map<String,Object> readRevProps = readRev.getProperties();
Assert.assertEquals(userProperties(readRevProps), userProperties(body.getProperties()));
@@ -82,27 +77,27 @@ public void testCRUDOperations() {
body = new TDBody(documentProperties);
TDRevision rev2 = new TDRevision(body);
TDRevision rev2input = rev2;
- rev2 = db.putRevision(rev2, rev1.getRevId(), false, status);
+ rev2 = database.putRevision(rev2, rev1.getRevId(), false, status);
Assert.assertEquals(TDStatus.CREATED, status.getCode());
Log.v(TAG, "Updated " + rev1);
Assert.assertEquals(rev1.getDocId(), rev2.getDocId());
Assert.assertTrue(rev2.getRevId().startsWith("2-"));
//read it back
- readRev = db.getDocumentWithIDAndRev(rev2.getDocId(), null, EnumSet.noneOf(TDDatabase.TDContentOptions.class));
+ readRev = database.getDocumentWithIDAndRev(rev2.getDocId(), null, EnumSet.noneOf(TDDatabase.TDContentOptions.class));
Assert.assertNotNull(readRev);
Assert.assertEquals(userProperties(readRev.getProperties()), userProperties(body.getProperties()));
// Try to update the first rev, which should fail:
- db.putRevision(rev2input, rev1.getRevId(), false, status);
+ database.putRevision(rev2input, rev1.getRevId(), false, status);
Assert.assertEquals(TDStatus.CONFLICT, status.getCode());
// Check the changes feed, with and without filters:
- TDRevisionList changes = db.changesSince(0, null, null);
+ TDRevisionList changes = database.changesSince(0, null, null);
Log.v(TAG, "Changes = " + changes);
Assert.assertEquals(1, changes.size());
- changes = db.changesSince(0, null, new TDFilterBlock() {
+ changes = database.changesSince(0, null, new TDFilterBlock() {
@Override
public boolean filter(TDRevision revision) {
@@ -112,7 +107,7 @@ public boolean filter(TDRevision revision) {
});
Assert.assertEquals(1, changes.size());
- changes = db.changesSince(0, null, new TDFilterBlock() {
+ changes = database.changesSince(0, null, new TDFilterBlock() {
@Override
public boolean filter(TDRevision revision) {
@@ -125,51 +120,34 @@ public boolean filter(TDRevision revision) {
// Delete it:
TDRevision revD = new TDRevision(rev2.getDocId(), null, true);
- TDRevision revResult = db.putRevision(revD, null, false, status);
+ TDRevision revResult = database.putRevision(revD, null, false, status);
Assert.assertNull(revResult);
Assert.assertEquals(TDStatus.CONFLICT, status.getCode());
- revD = db.putRevision(revD, rev2.getRevId(), false, status);
+ revD = database.putRevision(revD, rev2.getRevId(), false, status);
Assert.assertEquals(TDStatus.OK, status.getCode());
Assert.assertEquals(revD.getDocId(), rev2.getDocId());
Assert.assertTrue(revD.getRevId().startsWith("3-"));
// Delete nonexistent doc:
TDRevision revFake = new TDRevision("fake", null, true);
- db.putRevision(revFake, null, false, status);
+ database.putRevision(revFake, null, false, status);
Assert.assertEquals(TDStatus.NOT_FOUND, status.getCode());
// Read it back (should fail):
- readRev = db.getDocumentWithIDAndRev(revD.getDocId(), null, EnumSet.noneOf(TDDatabase.TDContentOptions.class));
+ readRev = database.getDocumentWithIDAndRev(revD.getDocId(), null, EnumSet.noneOf(TDDatabase.TDContentOptions.class));
Assert.assertNull(readRev);
// Get Changes feed
- changes = db.changesSince(0, null, null);
+ changes = database.changesSince(0, null, null);
Assert.assertTrue(changes.size() == 1);
// Get Revision History
- List<TDRevision> history = db.getRevisionHistory(revD);
+ List<TDRevision> history = database.getRevisionHistory(revD);
Assert.assertEquals(revD, history.get(0));
Assert.assertEquals(rev2, history.get(1));
Assert.assertEquals(rev1, history.get(2));
-
- Log.v(TAG, "Tests complete, closing database");
- db.close();
}
-
- private static Map<String,Object> userProperties(Map<String,Object> properties) {
- Map<String,Object> result = new HashMap<String,Object>();
-
- for (String key : properties.keySet()) {
- if(!key.startsWith("_")) {
- result.put(key, properties.get(key));
- }
- }
-
- return result;
- }
-
-
@Override
public void update(Observable observable, Object changeObject) {
if(observable instanceof TDDatabase) {
11 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/ChangeTracker.java
View
@@ -9,20 +9,19 @@
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
-import android.test.InstrumentationTestCase;
import android.util.Log;
import com.couchbase.touchdb.replicator.changetracker.TDChangeTracker;
import com.couchbase.touchdb.replicator.changetracker.TDChangeTracker.TDChangeTrackerMode;
import com.couchbase.touchdb.replicator.changetracker.TDChangeTrackerClient;
-public class ChangeTracker extends InstrumentationTestCase {
+public class ChangeTracker extends TouchDBTestCase {
public static final String TAG = "ChangeTracker";
public void testChangeTracker() throws Throwable {
- URL testURL = new URL(TestConstants.replicationURL);
+ URL testURL = getReplicationURL();
TDChangeTrackerClient client = new TDChangeTrackerClient() {
@@ -61,7 +60,7 @@ public void run() {
public void testChangeTrackerLongPoll() throws Throwable {
- URL testURL = new URL(TestConstants.replicationURL);
+ URL testURL = getReplicationURL();
TDChangeTrackerClient client = new TDChangeTrackerClient() {
@@ -98,7 +97,7 @@ public void run() {
public void testChangeTrackerContinuous() throws Throwable {
- URL testURL = new URL(TestConstants.replicationURL);
+ URL testURL = getReplicationURL();
TDChangeTrackerClient client = new TDChangeTrackerClient() {
@@ -135,7 +134,7 @@ public void run() {
public void testChangeTrackerWithFilterURL() throws Throwable {
- URL testURL = new URL(TestConstants.replicationURL);
+ URL testURL = getReplicationURL();
TDChangeTracker changeTracker = new TDChangeTracker(testURL, TDChangeTrackerMode.Continuous, 0, null);
// set filter
14 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/Changes.java
View
@@ -6,23 +6,17 @@
import java.util.Observer;
import junit.framework.Assert;
-import android.test.AndroidTestCase;
import com.couchbase.touchdb.TDBody;
-import com.couchbase.touchdb.TDDatabase;
import com.couchbase.touchdb.TDRevision;
import com.couchbase.touchdb.TDStatus;
-public class Changes extends AndroidTestCase {
+public class Changes extends TouchDBTestCase {
private int changeNotifications = 0;
public void testChangeNotification() {
- String filesDir = getContext().getFilesDir().getAbsolutePath();
-
- TDDatabase db = TDDatabase.createEmptyDBAtPath(filesDir + "/touch_couch_test.sqlite3");
-
// define a listener
Observer changeListener = new Observer() {
@@ -34,7 +28,7 @@ public void update(Observable observable, Object data) {
};
// add listener to database
- db.addObserver(changeListener);
+ database.addObserver(changeListener);
// create a document
Map<String, Object> documentProperties = new HashMap<String, Object>();
@@ -46,11 +40,9 @@ public void update(Observable observable, Object data) {
TDRevision rev1 = new TDRevision(body);
TDStatus status = new TDStatus();
- rev1 = db.putRevision(rev1, null, false, status);
+ rev1 = database.putRevision(rev1, null, false, status);
Assert.assertEquals(1, changeNotifications);
-
- db.close();
}
}
42 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/LocalDocs.java
View
@@ -4,24 +4,18 @@
import java.util.Map;
import junit.framework.Assert;
-import android.test.AndroidTestCase;
import android.util.Log;
import com.couchbase.touchdb.TDBody;
-import com.couchbase.touchdb.TDDatabase;
import com.couchbase.touchdb.TDRevision;
import com.couchbase.touchdb.TDStatus;
-public class LocalDocs extends AndroidTestCase {
+public class LocalDocs extends TouchDBTestCase {
public static final String TAG = "LocalDocs";
public void testLocalDocs() {
- String filesDir = getContext().getFilesDir().getAbsolutePath();
-
- TDDatabase db = TDDatabase.createEmptyDBAtPath(filesDir + "/touch_couch_test.sqlite3");
-
//create a document
Map<String, Object> documentProperties = new HashMap<String, Object>();
documentProperties.put("_id", "_local/doc1");
@@ -32,7 +26,7 @@ public void testLocalDocs() {
TDRevision rev1 = new TDRevision(body);
TDStatus status = new TDStatus();
- rev1 = db.putLocalRevision(rev1, null, status);
+ rev1 = database.putLocalRevision(rev1, null, status);
Assert.assertEquals(TDStatus.CREATED, status.getCode());
Log.v(TAG, "Created " + rev1);
@@ -40,7 +34,7 @@ public void testLocalDocs() {
Assert.assertTrue(rev1.getRevId().startsWith("1-"));
//read it back
- TDRevision readRev = db.getLocalDocument(rev1.getDocId(), null);
+ TDRevision readRev = database.getLocalDocument(rev1.getDocId(), null);
Assert.assertNotNull(readRev);
Map<String,Object> readRevProps = readRev.getProperties();
Assert.assertEquals(rev1.getDocId(), readRev.getProperties().get("_id"));
@@ -53,53 +47,37 @@ public void testLocalDocs() {
body = new TDBody(documentProperties);
TDRevision rev2 = new TDRevision(body);
TDRevision rev2input = rev2;
- rev2 = db.putLocalRevision(rev2, rev1.getRevId(), status);
+ rev2 = database.putLocalRevision(rev2, rev1.getRevId(), status);
Assert.assertEquals(TDStatus.CREATED, status.getCode());
Log.v(TAG, "Updated " + rev1);
Assert.assertEquals(rev1.getDocId(), rev2.getDocId());
Assert.assertTrue(rev2.getRevId().startsWith("2-"));
//read it back
- readRev = db.getLocalDocument(rev2.getDocId(), null);
+ readRev = database.getLocalDocument(rev2.getDocId(), null);
Assert.assertNotNull(readRev);
Assert.assertEquals(userProperties(readRev.getProperties()), userProperties(body.getProperties()));
// Try to update the first rev, which should fail:
- db.putLocalRevision(rev2input, rev1.getRevId(), status);
+ database.putLocalRevision(rev2input, rev1.getRevId(), status);
Assert.assertEquals(TDStatus.CONFLICT, status.getCode());
// Delete it:
TDRevision revD = new TDRevision(rev2.getDocId(), null, true);
- TDRevision revResult = db.putLocalRevision(revD, null, status);
+ TDRevision revResult = database.putLocalRevision(revD, null, status);
Assert.assertNull(revResult);
Assert.assertEquals(TDStatus.CONFLICT, status.getCode());
- revD = db.putLocalRevision(revD, rev2.getRevId(), status);
+ revD = database.putLocalRevision(revD, rev2.getRevId(), status);
Assert.assertEquals(TDStatus.OK, status.getCode());
// Delete nonexistent doc:
TDRevision revFake = new TDRevision("_local/fake", null, true);
- db.putLocalRevision(revFake, null, status);
+ database.putLocalRevision(revFake, null, status);
Assert.assertEquals(TDStatus.NOT_FOUND, status.getCode());
// Read it back (should fail):
- readRev = db.getLocalDocument(revD.getDocId(), null);
+ readRev = database.getLocalDocument(revD.getDocId(), null);
Assert.assertNull(readRev);
-
- Log.v(TAG, "Tests complete, closing database");
- db.close();
-
- }
-
- private static Map<String,Object> userProperties(Map<String,Object> properties) {
- Map<String,Object> result = new HashMap<String,Object>();
-
- for (String key : properties.keySet()) {
- if(!key.startsWith("_")) {
- result.put(key, properties.get(key));
- }
- }
-
- return result;
}
}
93 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/Replicator.java
View
@@ -1,64 +1,29 @@
package com.couchbase.touchdb.testapp.tests;
-import java.io.IOException;
-import java.net.HttpURLConnection;
import java.net.URL;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import junit.framework.Assert;
-import android.test.InstrumentationTestCase;
import android.util.Log;
import com.couchbase.touchdb.TDBody;
import com.couchbase.touchdb.TDDatabase;
import com.couchbase.touchdb.TDRevision;
-import com.couchbase.touchdb.TDServer;
import com.couchbase.touchdb.TDStatus;
import com.couchbase.touchdb.replicator.TDPusher;
import com.couchbase.touchdb.replicator.TDReplicator;
-public class Replicator extends InstrumentationTestCase {
+public class Replicator extends TouchDBTestCase {
public static final String TAG = "Replicator";
- private static void deleteRemoteDB() {
- try {
- Log.v(TAG, String.format("Deleting %s", TestConstants.replicationURL));
- URL url = new URL(TestConstants.replicationURL);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("DELETE");
- conn.connect();
- int responseCode = conn.getResponseCode();
- Assert.assertTrue(responseCode < 300 || responseCode == 404);
- } catch (Exception e) {
- Log.e(TAG, "Exceptiong deleting remote db", e);
- }
- }
-
public void testPusher() throws Throwable {
- String filesDir = getInstrumentation().getContext().getFilesDir().getAbsolutePath();
-
- TDServer server = null;
- try {
- server = new TDServer(filesDir);
- } catch (IOException e) {
- fail("Creating server caused IOException");
- }
-
- //to ensure this test is easily repeatable we will explicitly remove
- //any stale foo.touchdb
- TDDatabase old = server.getExistingDatabaseNamed("db");
- if(old != null) {
- old.deleteDatabase();
- }
-
- final TDDatabase db = server.getDatabaseNamed("db");
- db.open();
+ URL remote = getReplicationURL();
- deleteRemoteDB();
+ deleteRemoteDB(remote);
// Create some documents:
Map<String, Object> documentProperties = new HashMap<String, Object>();
@@ -70,14 +35,14 @@ public void testPusher() throws Throwable {
TDRevision rev1 = new TDRevision(body);
TDStatus status = new TDStatus();
- rev1 = db.putRevision(rev1, null, false, status);
+ rev1 = database.putRevision(rev1, null, false, status);
Assert.assertEquals(TDStatus.CREATED, status.getCode());
documentProperties.put("_rev", rev1.getRevId());
documentProperties.put("UPDATED", true);
@SuppressWarnings("unused")
- TDRevision rev2 = db.putRevision(new TDRevision(documentProperties), rev1.getRevId(), false, status);
+ TDRevision rev2 = database.putRevision(new TDRevision(documentProperties), rev1.getRevId(), false, status);
Assert.assertEquals(TDStatus.CREATED, status.getCode());
documentProperties = new HashMap<String, Object>();
@@ -85,14 +50,10 @@ public void testPusher() throws Throwable {
documentProperties.put("baz", 666);
documentProperties.put("fnord", true);
- db.putRevision(new TDRevision(documentProperties), null, false, status);
+ database.putRevision(new TDRevision(documentProperties), null, false, status);
Assert.assertEquals(TDStatus.CREATED, status.getCode());
-
-
-
- URL remote = new URL(TestConstants.replicationURL);
- final TDReplicator repl = db.getReplicator(remote, true, false);
+ final TDReplicator repl = database.getReplicator(remote, true, false);
((TDPusher)repl).setCreateTarget(true);
runTestOnUiThread(new Runnable() {
@@ -109,35 +70,16 @@ public void run() {
Thread.sleep(1000);
}
Assert.assertEquals("3", repl.getLastSequence());
-
- db.close();
- server.deleteDatabaseNamed("db");
- server.close();
}
public void testPuller() throws Throwable {
- String filesDir = getInstrumentation().getContext().getFilesDir().getAbsolutePath();
-
- TDServer server = null;
- try {
- server = new TDServer(filesDir);
- } catch (IOException e) {
- fail("Creating server caused IOException");
- }
-
- //to ensure this test is easily repeatable we will explicitly remove
- //any stale foo.touchdb
- TDDatabase old = server.getExistingDatabaseNamed("db");
- if(old != null) {
- old.deleteDatabase();
- }
+ //force a push first, to ensure that we have data to pull
+ testPusher();
- final TDDatabase db = server.getDatabaseNamed("db");
- db.open();
+ URL remote = getReplicationURL();
- URL remote = new URL(TestConstants.replicationURL);
- final TDReplicator repl = db.getReplicator(remote, false, false);
+ final TDReplicator repl = database.getReplicator(remote, false, false);
runTestOnUiThread(new Runnable() {
@Override
@@ -154,7 +96,7 @@ public void run() {
}
String lastSequence = repl.getLastSequence();
Assert.assertTrue("2".equals(lastSequence) || "3".equals(lastSequence));
- Assert.assertEquals(2, db.getDocumentCount());
+ Assert.assertEquals(2, database.getDocumentCount());
//wait for a short time here
@@ -162,7 +104,7 @@ public void run() {
//writing its local state to the server
Thread.sleep(2*1000);
- final TDReplicator repl2 = db.getReplicator(remote, false, false);
+ final TDReplicator repl2 = database.getReplicator(remote, false, false);
runTestOnUiThread(new Runnable() {
@Override
@@ -177,21 +119,18 @@ public void run() {
Log.i(TAG, "Waiting for replicator2 to finish");
Thread.sleep(1000);
}
- Assert.assertEquals(3, db.getLastSequence());
+ Assert.assertEquals(3, database.getLastSequence());
- TDRevision doc = db.getDocumentWithIDAndRev("doc1", null, EnumSet.noneOf(TDDatabase.TDContentOptions.class));
+ TDRevision doc = database.getDocumentWithIDAndRev("doc1", null, EnumSet.noneOf(TDDatabase.TDContentOptions.class));
Assert.assertNotNull(doc);
Assert.assertTrue(doc.getRevId().startsWith("2-"));
Assert.assertEquals(1, doc.getProperties().get("foo"));
- doc = db.getDocumentWithIDAndRev("doc2", null, EnumSet.noneOf(TDDatabase.TDContentOptions.class));
+ doc = database.getDocumentWithIDAndRev("doc2", null, EnumSet.noneOf(TDDatabase.TDContentOptions.class));
Assert.assertNotNull(doc);
Assert.assertTrue(doc.getRevId().startsWith("1-"));
Assert.assertEquals(true, doc.getProperties().get("fnord"));
- db.close();
- server.deleteDatabaseNamed("db");
- server.close();
}
}
34 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/RevTree.java
View
@@ -24,7 +24,6 @@
import java.util.Map;
import junit.framework.Assert;
-import android.test.AndroidTestCase;
import com.couchbase.touchdb.TDChangesOptions;
import com.couchbase.touchdb.TDDatabase;
@@ -32,16 +31,12 @@
import com.couchbase.touchdb.TDRevisionList;
import com.couchbase.touchdb.TDStatus;
-public class RevTree extends AndroidTestCase {
+public class RevTree extends TouchDBTestCase {
public static final String TAG = "RevTree";
public void testRevTree() {
- String filesDir = getContext().getFilesDir().getAbsolutePath();
-
- TDDatabase db = TDDatabase.createEmptyDBAtPath(filesDir + "/touch_couch_test.sqlite3");
-
TDRevision rev = new TDRevision("MyDocId", "4-foxy", false);
Map<String, Object> revProperties = new HashMap<String, Object>();
@@ -56,10 +51,10 @@ public void testRevTree() {
revHistory.add("2-too");
revHistory.add("1-won");
- TDStatus status = db.forceInsert(rev, revHistory, null);
+ TDStatus status = database.forceInsert(rev, revHistory, null);
Assert.assertEquals(201, status.getCode());
- Assert.assertEquals(1, db.getDocumentCount());
- verifyHistory(db, rev, revHistory);
+ Assert.assertEquals(1, database.getDocumentCount());
+ verifyHistory(database, rev, revHistory);
TDRevision conflict = new TDRevision("MyDocId", "5-epsilon", false);
@@ -76,10 +71,10 @@ public void testRevTree() {
conflictHistory.add("2-too");
conflictHistory.add("1-won");
- status = db.forceInsert(conflict, conflictHistory, null);
+ status = database.forceInsert(conflict, conflictHistory, null);
Assert.assertEquals(201, status.getCode());
- Assert.assertEquals(1, db.getDocumentCount());
- verifyHistory(db, conflict, conflictHistory);
+ Assert.assertEquals(1, database.getDocumentCount());
+ verifyHistory(database, conflict, conflictHistory);
// Add an unrelated document:
TDRevision other = new TDRevision("AnotherDocID", "1-ichi", false);
@@ -88,39 +83,36 @@ public void testRevTree() {
other.setProperties(otherProperties);
List<String> otherHistory = new ArrayList<String>();
otherHistory.add(other.getRevId());
- status = db.forceInsert(other, otherHistory, null);
+ status = database.forceInsert(other, otherHistory, null);
Assert.assertEquals(TDStatus.CREATED, status.getCode());
// Fetch one of those phantom revisions with no body:
- TDRevision rev2 = db.getDocumentWithIDAndRev(rev.getDocId(), "2-too", EnumSet.noneOf(TDDatabase.TDContentOptions.class));
+ TDRevision rev2 = database.getDocumentWithIDAndRev(rev.getDocId(), "2-too", EnumSet.noneOf(TDDatabase.TDContentOptions.class));
Assert.assertEquals(rev.getDocId(), rev2.getDocId());
Assert.assertEquals("2-too", rev2.getRevId());
//Assert.assertNull(rev2.getBody());
// Make sure no duplicate rows were inserted for the common revisions:
- Assert.assertEquals(8, db.getLastSequence());
+ Assert.assertEquals(8, database.getLastSequence());
// Make sure the revision with the higher revID wins the conflict:
- TDRevision current = db.getDocumentWithIDAndRev(rev.getDocId(), null, EnumSet.noneOf(TDDatabase.TDContentOptions.class));
+ TDRevision current = database.getDocumentWithIDAndRev(rev.getDocId(), null, EnumSet.noneOf(TDDatabase.TDContentOptions.class));
Assert.assertEquals(conflict, current);
// Get the _changes feed and verify only the winner is in it:
TDChangesOptions options = new TDChangesOptions();
- TDRevisionList changes = db.changesSince(0, options, null);
+ TDRevisionList changes = database.changesSince(0, options, null);
TDRevisionList expectedChanges = new TDRevisionList();
expectedChanges.add(conflict);
expectedChanges.add(other);
Assert.assertEquals(changes, expectedChanges);
options.setIncludeConflicts(true);
- changes = db.changesSince(0, options, null);
+ changes = database.changesSince(0, options, null);
expectedChanges = new TDRevisionList();
expectedChanges.add(rev);
expectedChanges.add(conflict);
expectedChanges.add(other);
Assert.assertEquals(changes, expectedChanges);
-
-
- db.close();
}
private static void verifyHistory(TDDatabase db, TDRevision rev, List<String> history) {
192 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/Router.java
View
@@ -1,133 +1,26 @@
package com.couchbase.touchdb.testapp.tests;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
-
-import org.codehaus.jackson.map.ObjectMapper;
-
-import android.test.InstrumentationTestCase;
import android.util.Log;
-import com.couchbase.touchdb.TDBody;
import com.couchbase.touchdb.TDDatabase;
-import com.couchbase.touchdb.TDServer;
import com.couchbase.touchdb.TDStatus;
import com.couchbase.touchdb.TDView;
import com.couchbase.touchdb.TDViewMapBlock;
import com.couchbase.touchdb.TDViewMapEmitBlock;
import com.couchbase.touchdb.router.TDRouter;
import com.couchbase.touchdb.router.TDURLConnection;
-import com.couchbase.touchdb.router.TDURLStreamHandlerFactory;
-import com.couchbase.touchdb.support.FileDirUtils;
-public class Router extends InstrumentationTestCase {
- private static boolean initializedUrlHandler = false;
+public class Router extends TouchDBTestCase {
public static final String TAG = "Router";
- private ObjectMapper mapper = new ObjectMapper();
-
- protected String getServerPath() {
- String filesDir = getInstrumentation().getContext().getFilesDir().getAbsolutePath() + "/tests";
- return filesDir;
- }
-
- @Override
- protected void setUp() throws Exception {
-
- //delete and recreate the server path
- String serverPath = getServerPath();
- File serverPathFile = new File(serverPath);
- FileDirUtils.deleteRecursive(serverPathFile);
- serverPathFile.mkdir();
-
- //for some reason a traditional static initializer causes junit to die
- if(!initializedUrlHandler) {
- TDURLStreamHandlerFactory.registerSelfIgnoreError();
- initializedUrlHandler = true;
- }
- }
-
- protected TDURLConnection sendRequest(TDServer server, String method, String path, Map<String,String> headers, Object bodyObj) {
- try {
- URL url = new URL("touchdb://" + path);
- TDURLConnection conn = (TDURLConnection)url.openConnection();
- conn.setDoOutput(true);
- conn.setRequestMethod(method);
- if(headers != null) {
- for (String header : headers.keySet()) {
- conn.setRequestProperty(header, headers.get(header));
- }
- }
- Map<String, List<String>> allProperties = conn.getRequestProperties();
- if(bodyObj != null) {
- conn.setDoInput(true);
- ByteArrayInputStream bais = new ByteArrayInputStream(mapper.writeValueAsBytes(bodyObj));
- conn.setRequestInputStream(bais);
- }
-
- TDRouter router = new TDRouter(server, conn);
- router.start();
- return conn;
- } catch (MalformedURLException e) {
- fail();
- } catch(IOException e) {
- fail();
- }
- return null;
- }
-
- protected Object parseJSONResponse(TDURLConnection conn) {
- Object result = null;
- TDBody responseBody = conn.getResponseBody();
- if(responseBody != null) {
- byte[] json = responseBody.getJson();
- String jsonString = null;
- if(json != null) {
- jsonString = new String(json);
- try {
- result = mapper.readValue(jsonString, Object.class);
- } catch (Exception e) {
- fail();
- }
- }
- }
- return result;
- }
-
- protected Object sendBody(TDServer server, String method, String path, Object bodyObj, int expectedStatus, Object expectedResult) {
- TDURLConnection conn = sendRequest(server, method, path, null, bodyObj);
- Object result = parseJSONResponse(conn);
- Log.v(TAG, String.format("%s %s --> %d", method, path, conn.getResponseCode()));
- Assert.assertEquals(expectedStatus, conn.getResponseCode());
- if(expectedResult != null) {
- Assert.assertEquals(expectedResult, result);
- }
- return result;
- }
-
- protected Object send(TDServer server, String method, String path, int expectedStatus, Object expectedResult) {
- return sendBody(server, method, path, null, expectedStatus, expectedResult);
- }
-
public void testServer() {
-
- TDServer server = null;
- try {
- server = new TDServer(getServerPath());
- } catch (IOException e) {
- fail("Creating server caused IOException");
- }
-
Map<String,Object> responseBody = new HashMap<String,Object>();
responseBody.put("TouchDB", "Welcome");
responseBody.put("couchdb", "Welcome");
@@ -145,25 +38,16 @@ public void testServer() {
send(server, "GET", "/_session", TDStatus.OK, session);
List<String> allDbs = new ArrayList<String>();
+ allDbs.add("touchdb-test");
send(server, "GET", "/_all_dbs", TDStatus.OK, allDbs);
send(server, "GET", "/non-existant", TDStatus.NOT_FOUND, null);
send(server, "GET", "/BadName", TDStatus.BAD_REQUEST, null);
send(server, "PUT", "/", TDStatus.BAD_REQUEST, null);
send(server, "POST", "/", TDStatus.BAD_REQUEST, null);
-
- server.close();
}
public void testDatabase() {
-
- TDServer server = null;
- try {
- server = new TDServer(getServerPath());
- } catch (IOException e) {
- fail("Creating server caused IOException");
- }
-
send(server, "PUT", "/database", TDStatus.CREATED, null);
Map<String,Object> dbInfo = (Map<String,Object>)send(server, "GET", "/database", TDStatus.OK, null);
@@ -177,6 +61,7 @@ public void testDatabase() {
List<String> allDbs = new ArrayList<String>();
allDbs.add("database");
allDbs.add("database2");
+ allDbs.add("touchdb-test");
send(server, "GET", "/_all_dbs", TDStatus.OK, allDbs);
dbInfo = (Map<String,Object>)send(server, "GET", "/database2", TDStatus.OK, null);
Assert.assertEquals("database2", dbInfo.get("db_name"));
@@ -188,19 +73,9 @@ public void testDatabase() {
send(server, "PUT", "/database%2Fwith%2Fslashes", TDStatus.CREATED, null);
dbInfo = (Map<String,Object>)send(server, "GET", "/database%2Fwith%2Fslashes", TDStatus.OK, null);
Assert.assertEquals("database/with/slashes", dbInfo.get("db_name"));
-
- server.close();
}
public void testDocs() {
-
- TDServer server = null;
- try {
- server = new TDServer(getServerPath());
- } catch (IOException e) {
- fail("Creating server caused IOException");
- }
-
send(server, "PUT", "/db", TDStatus.CREATED, null);
// PUT:
@@ -313,19 +188,9 @@ public void testDocs() {
results.remove(result1);
expectedChanges.put("results", results);
send(server, "GET", "/db/_changes?since=5", TDStatus.OK, expectedChanges);
-
- server.close();
}
public void testLocalDocs() {
-
- TDServer server = null;
- try {
- server = new TDServer(getServerPath());
- } catch (IOException e) {
- fail("Creating server caused IOException");
- }
-
send(server, "PUT", "/db", TDStatus.CREATED, null);
// PUT a local doc:
@@ -345,18 +210,9 @@ public void testLocalDocs() {
expectedChanges.put("last_seq", 0);
expectedChanges.put("results", new ArrayList<Object>());
send(server, "GET", "/db/_changes", TDStatus.OK, expectedChanges);
-
- server.close();
}
public void testAllDocs() {
- TDServer server = null;
- try {
- server = new TDServer(getServerPath());
- } catch (IOException e) {
- fail("Creating server caused IOException");
- }
-
send(server, "PUT", "/db", TDStatus.CREATED, null);
Map<String,Object> result;
@@ -430,19 +286,9 @@ public void testAllDocs() {
rows = (List<Map<String,Object>>)result.get("rows");
Assert.assertEquals(expectedRowsWithDocs, rows);
-
- server.close();
}
public void testViews() {
-
- TDServer server = null;
- try {
- server = new TDServer(getServerPath());
- } catch (IOException e) {
- fail("Creating server caused IOException");
- }
-
send(server, "PUT", "/db", TDStatus.CREATED, null);
Map<String,Object> result;
@@ -515,19 +361,9 @@ public void map(Map<String, Object> document, TDViewMapEmitBlock emitter) {
Assert.assertEquals(TDStatus.OK, conn.getResponseCode());
result = (Map<String,Object>)parseJSONResponse(conn);
Assert.assertEquals(4, result.get("total_rows"));
-
- server.close();
}
public void testPostBulkDocs() {
-
- TDServer server = null;
- try {
- server = new TDServer(getServerPath());
- } catch (IOException e) {
- fail("Creating server caused IOException");
- }
-
send(server, "PUT", "/db", TDStatus.CREATED, null);
Map<String,Object> bulk_doc1 = new HashMap<String,Object>();
@@ -553,20 +389,9 @@ public void testPostBulkDocs() {
Assert.assertNotNull(bulk_result.get(0).get("rev"));
Assert.assertEquals(bulk_result.get(1).get("id"), bulk_doc2.get("_id"));
Assert.assertNotNull(bulk_result.get(1).get("rev"));
-
- server.close();
-
}
public void testPostKeysView() {
-
- TDServer server = null;
- try {
- server = new TDServer(getServerPath());
- } catch (IOException e) {
- fail("Creating server caused IOException");
- }
-
send(server, "PUT", "/db", TDStatus.CREATED, null);
Map<String,Object> result;
@@ -601,18 +426,10 @@ public void map(Map<String, Object> document, TDViewMapEmitBlock emitter) {
TDURLConnection conn = sendRequest(server, "POST", "/db/_design/design/_view/view", null, bodyObj);
result = (Map<String, Object>) parseJSONResponse(conn);
Assert.assertEquals(1, result.get("total_rows"));
- server.close();
}
public void testRevsDiff() {
- TDServer server = null;
- try {
- server = new TDServer(getServerPath());
- } catch (IOException e) {
- fail("Creating server caused IOException");
- }
-
send(server, "PUT", "/db", TDStatus.CREATED, null);
Map<String,Object> doc = new HashMap<String,Object>();
@@ -685,9 +502,6 @@ public void testRevsDiff() {
revsDiffResponse.put("99999", doc9missingMap);
sendBody(server, "POST", "/db/_revs_diff", revsDiffRequest, TDStatus.OK, revsDiffResponse);
-
- server.close();
-
}
}
41 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/Server.java
View
@@ -1,44 +1,15 @@
package com.couchbase.touchdb.testapp.tests;
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
import java.util.List;
import junit.framework.Assert;
-import android.test.AndroidTestCase;
import com.couchbase.touchdb.TDDatabase;
-import com.couchbase.touchdb.TDServer;
-import com.couchbase.touchdb.support.FileDirUtils;
-public class Server extends AndroidTestCase {
-
- protected String getServerPath() {
- String filesDir = getContext().getFilesDir().getAbsolutePath() + "/tests";
- return filesDir;
- }
-
- @Override
- protected void setUp() throws Exception {
- //delete and recreate the server path
- String serverPath = getServerPath();
- File serverPathFile = new File(serverPath);
- FileDirUtils.deleteRecursive(serverPathFile);
- serverPathFile.mkdir();
- }
+public class Server extends TouchDBTestCase {
public void testServer() {
-
-
- TDServer server = null;
- try {
- server = new TDServer(getServerPath());
- } catch (IOException e) {
- fail("Creating server caused IOException");
- }
-
//to ensure this test is easily repeatable we will explicitly remove
//any stale foo.touchdb
TDDatabase old = server.getExistingDatabaseNamed("foo");
@@ -55,19 +26,17 @@ public void testServer() {
Assert.assertEquals(db, server.getDatabaseNamed("foo"));
// because foo doesn't exist yet
- List<String> databaseNames = new ArrayList<String>();
- Assert.assertEquals(databaseNames, server.allDatabaseNames());
+ List<String> databaseNames = server.allDatabaseNames();
+ Assert.assertTrue(!databaseNames.contains("foo"));
Assert.assertTrue(db.open());
Assert.assertTrue(db.exists());
- databaseNames.add("foo");
- Assert.assertEquals(databaseNames, server.allDatabaseNames());
+ databaseNames = server.allDatabaseNames();
+ Assert.assertTrue(databaseNames.contains("foo"));
db.close();
server.deleteDatabaseNamed("foo");
- server.close();
-
}
}
10 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/TestConstants.java
View
@@ -1,10 +0,0 @@
-package com.couchbase.touchdb.testapp.tests;
-
-public interface TestConstants {
-
- //10.0.2.2 is your local machine from within the android emulator
- String replicationServer = "http://10.0.2.2:5984";
- String replicationURL = replicationServer + "/tdreplicator_test";
-
-
-}
255 TouchDB-Android-TestApp/src/com/couchbase/touchdb/testapp/tests/TouchDBTestCase.java
View
@@ -0,0 +1,255 @@
+package com.couchbase.touchdb.testapp.tests;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import junit.framework.Assert;
+
+import org.codehaus.jackson.map.ObjectMapper;
+
+import android.test.InstrumentationTestCase;
+import android.util.Base64;
+import android.util.Log;
+
+import com.couchbase.touchdb.TDBody;
+import com.couchbase.touchdb.TDDatabase;
+import com.couchbase.touchdb.TDServer;
+import com.couchbase.touchdb.router.TDRouter;
+import com.couchbase.touchdb.router.TDURLConnection;
+import com.couchbase.touchdb.router.TDURLStreamHandlerFactory;
+import com.couchbase.touchdb.support.FileDirUtils;
+
+public abstract class TouchDBTestCase extends InstrumentationTestCase {
+
+ public static final String TAG = "TouchDBTestCase";
+
+ private static boolean initializedUrlHandler = false;
+
+ protected ObjectMapper mapper = new ObjectMapper();
+
+ protected TDServer server = null;
+ protected TDDatabase database = null;
+ protected String DEFAULT_TEST_DB = "touchdb-test";
+
+ @Override
+ protected void setUp() throws Exception {
+ Log.v(TAG, "setUp");
+ super.setUp();
+
+ //for some reason a traditional static initializer causes junit to die
+ if(!initializedUrlHandler) {
+ TDURLStreamHandlerFactory.registerSelfIgnoreError();
+ initializedUrlHandler = true;
+ }
+
+ loadCustomProperties();
+ startTouchDB();
+ startDatabase();
+ }
+
+ protected String getServerPath() {
+ String filesDir = getInstrumentation().getContext().getFilesDir().getAbsolutePath();
+ return filesDir;
+ }
+
+ protected void startTouchDB() {
+ try {
+ String serverPath = getServerPath();
+ File serverPathFile = new File(serverPath);
+ FileDirUtils.deleteRecursive(serverPathFile);
+ serverPathFile.mkdir();
+ server = new TDServer(getServerPath());
+ } catch (IOException e) {
+ fail("Creating server caused IOException");
+ }
+ }
+
+ protected void stopTouchDB() {
+ if(server != null) {
+ server.close();
+ }
+ }
+
+ protected void startDatabase() {
+ database = ensureEmptyDatabase(DEFAULT_TEST_DB);
+ boolean status = database.open();
+ Assert.assertTrue(status);
+ }
+
+ protected void stopDatabse() {
+ if(database != null) {
+ database.close();
+ }
+ }
+
+ protected TDDatabase ensureEmptyDatabase(String dbName) {
+ TDDatabase db = server.getExistingDatabaseNamed(dbName);
+ if(db != null) {
+ boolean status = db.deleteDatabase();
+ Assert.assertTrue(status);
+ }
+ db = server.getDatabaseNamed(dbName, true);
+ return db;
+ }
+
+ protected void loadCustomProperties() throws IOException {
+ Properties systemProperties = System.getProperties();
+ InputStream mainProperties = TouchDBTestCase.class.getResourceAsStream("test.properties");
+ if(mainProperties != null) {
+ systemProperties.load(mainProperties);
+ }
+ InputStream localProperties = TouchDBTestCase.class.getResourceAsStream("local-test.properties");
+ if(localProperties != null) {
+ systemProperties.load(localProperties);
+ }
+ }
+
+ protected String getReplicationProtocol() {
+ return System.getProperty("replicationProtocol");
+ }
+
+ protected String getReplicationServer() {
+ return System.getProperty("replicationServer");
+ }
+
+ protected int getReplicationPort() {
+ return