internal static Document CreateDocWithAttachment(Database database, string attachmentName, string content)
        {
            var properties = new Dictionary<string, object>();
            properties.Put("foo", "bar");

            var doc = CreateDocumentWithProperties(database, properties);
            var rev = doc.CurrentRevision;
            var attachment = rev.GetAttachment(attachmentName);
            Assert.AreEqual(rev.Attachments.Count(), 0);
            Assert.AreEqual(rev.AttachmentNames.Count(), 0);
            Assert.IsNull(attachment);

            var body = new MemoryStream(Encoding.UTF8.GetBytes(content));
            var rev2 = doc.CreateRevision();
            rev2.SetAttachment(attachmentName, "text/plain; charset=utf-8", body);
            var rev3 = rev2.Save();
            rev2.Dispose();
            Assert.IsNotNull(rev3);
            Assert.AreEqual(rev3.Attachments.Count(), 1);
            Assert.AreEqual(rev3.AttachmentNames.Count(), 1);

            attachment = rev3.GetAttachment(attachmentName);
            Assert.IsNotNull(attachment);
            Assert.AreEqual(doc, attachment.Document);
            Assert.AreEqual(attachmentName, attachment.Name);

            var attNames = new List<string>();
            attNames.AddItem(attachmentName);
            Assert.AreEqual(rev3.AttachmentNames, attNames);
            Assert.AreEqual("text/plain; charset=utf-8", attachment.ContentType);
            Assert.AreEqual(Encoding.UTF8.GetString(attachment.Content.ToArray()), content);
            Assert.AreEqual(Encoding.UTF8.GetBytes(content).Length, attachment.Length);
            attachment.Dispose();

            return doc;
        }          
        public void TestViewGroupedStrings()
        {
            IDictionary<string, object> docProperties1 = new Dictionary<string, object>();
            docProperties1["name"] = "Alice";
            PutDoc(database, docProperties1);
            IDictionary<string, object> docProperties2 = new Dictionary<string, object>();
            docProperties2["name"] = "Albert";
            PutDoc(database, docProperties2);
            IDictionary<string, object> docProperties3 = new Dictionary<string, object>();
            docProperties3["name"] = "Naomi";
            PutDoc(database, docProperties3);
            IDictionary<string, object> docProperties4 = new Dictionary<string, object>();
            docProperties4["name"] = "Jens";
            PutDoc(database, docProperties4);
            IDictionary<string, object> docProperties5 = new Dictionary<string, object>();
            docProperties5["name"] = "Jed";
            PutDoc(database, docProperties5);

            View view = database.GetView("default/names");
            view.SetMapReduce((document, emitter) =>
            {
                string name = (string)document["name"];
                if (name != null)
                {
                    emitter(Sharpen.Runtime.Substring(name, 0, 1), 1);
                }
            }, BuiltinReduceFunctions.Sum, "1.0");

            view.UpdateIndex();
            QueryOptions options = new QueryOptions();
            options.GroupLevel = 1;

            IList<QueryRow> rows = view.QueryWithOptions(options).ToList();
            IList<IDictionary<string, object>> expectedRows = new List<IDictionary<string, object>>();
            IDictionary<string, object> row1 = new Dictionary<string, object>();
            row1["key"] = "A";
            row1["value"] = 2;
            expectedRows.AddItem(row1);

            IDictionary<string, object> row2 = new Dictionary<string, object>();
            row2["key"] = "J";
            row2["value"] = 2;
            expectedRows.AddItem(row2);

            IDictionary<string, object> row3 = new Dictionary<string, object>();
            row3["key"] = "N";
            row3["value"] = 1;
            expectedRows.AddItem(row3);

            Assert.AreEqual(row1["key"], rows[0].Key);
            Assert.AreEqual(row1["value"], rows[0].Value);
            Assert.AreEqual(row2["key"], rows[1].Key);
            Assert.AreEqual(row2["value"], rows[1].Value);
            Assert.AreEqual(row3["key"], rows[2].Key);
            Assert.AreEqual(row3["value"], rows[2].Value);
        }
        public void TestViewCollation()
        {
            IList<object> list1 = new List<object>();
            list1.AddItem("a");
            IList<object> list2 = new List<object>();
            list2.AddItem("b");
            IList<object> list3 = new List<object>();
            list3.AddItem("b");
            list3.AddItem("c");
            IList<object> list4 = new List<object>();
            list4.AddItem("b");
            list4.AddItem("c");
            list4.AddItem("a");
            IList<object> list5 = new List<object>();
            list5.AddItem("b");
            list5.AddItem("d");
            IList<object> list6 = new List<object>();
            list6.AddItem("b");
            list6.AddItem("d");
            list6.AddItem("e");

            // Based on CouchDB's "view_collation.js" test
            IList<object> testKeys = new List<object>();
            testKeys.AddItem(null);
            testKeys.AddItem(false);
            testKeys.AddItem(true);
            testKeys.AddItem(0);
            testKeys.AddItem(2.5);
            testKeys.AddItem(10);
            testKeys.AddItem(" ");
            testKeys.AddItem("_");
            testKeys.AddItem("~");
            testKeys.AddItem("a");
            testKeys.AddItem("A");
            testKeys.AddItem("aa");
            testKeys.AddItem("b");
            testKeys.AddItem("B");
            testKeys.AddItem("ba");
            testKeys.AddItem("bb");
            testKeys.AddItem(list1);
            testKeys.AddItem(list2);
            testKeys.AddItem(list3);
            testKeys.AddItem(list4);
            testKeys.AddItem(list5);
            testKeys.AddItem(list6);

            int i = 0;
            foreach (object key in testKeys)
            {
                IDictionary<string, object> docProperties = new Dictionary<string, object>();
                docProperties.Put("_id", Sharpen.Extensions.ToString(i++));
                docProperties["name"] = key;
                PutDoc(database, docProperties);
            }

            View view = database.GetView("default/names");
            view.SetMapReduce((IDictionary<string, object> document, EmitDelegate emitter) => 
            emitter(document["name"], null), null, "1.0");

            QueryOptions options = new QueryOptions();
            IList<QueryRow> rows = view.QueryWithOptions(options).ToList();
            i = 0;
            foreach (QueryRow row in rows)
            {
                Assert.AreEqual(testKeys[i++], row.Key);
            }
        }
        public void TestAllDocsQuery()
        {
            var docs = PutDocs(database);
            var expectedRow = new List<QueryRow>();
            foreach (RevisionInternal rev in docs)
            {
                var value = new Dictionary<string, object>();
                value.Put("rev", rev.GetRevId());
                value.Put("_conflicts", new List<string>());

                var queryRow = new QueryRow(rev.GetDocId(), 0, rev.GetDocId(), value, null);
                queryRow.Database = database;
                expectedRow.AddItem(queryRow);
            }

            var options = new QueryOptions();
            var allDocs = database.GetAllDocs(options);
            var expectedRows = new List<QueryRow>();
            expectedRows.AddItem(expectedRow[2]);
            expectedRows.AddItem(expectedRow[0]);
            expectedRows.AddItem(expectedRow[3]);
            expectedRows.AddItem(expectedRow[1]);
            expectedRows.AddItem(expectedRow[4]);

            var expectedQueryResult = CreateExpectedQueryResult(expectedRows, 0);
            //CollectionAssert.AreEqual(expectedQueryResult, allDocs);
            AssertPropertiesAreEqual(expectedQueryResult, allDocs);

            // Start/end key query:
            options = new QueryOptions();
            options.SetStartKey("2");
            options.SetEndKey("44444");
            allDocs = database.GetAllDocs(options);
            expectedRows = new List<QueryRow>();
            expectedRows.AddItem(expectedRow[0]);
            expectedRows.AddItem(expectedRow[3]);
            expectedRows.AddItem(expectedRow[1]);
            expectedQueryResult = CreateExpectedQueryResult(expectedRows, 0);
            Assert.AreEqual(expectedQueryResult.Select(kvp => kvp.Key).OrderBy(k => k), allDocs.Select(kvp => kvp.Key).OrderBy(k => k));

            // Start/end query without inclusive end:
            options.SetInclusiveEnd(false);
            allDocs = database.GetAllDocs(options);
            expectedRows = new List<QueryRow>();
            expectedRows.AddItem(expectedRow[0]);
            expectedRows.AddItem(expectedRow[3]);
            expectedQueryResult = CreateExpectedQueryResult(expectedRows, 0);
            Assert.AreEqual(expectedQueryResult.Select(kvp => kvp.Key).OrderBy(k => k), allDocs.Select(kvp => kvp.Key).OrderBy(k => k));

            // Get all documents: with default QueryOptions
            options = new QueryOptions();
            allDocs = database.GetAllDocs(options);
            expectedRows = new List<QueryRow>();
            expectedRows.AddItem(expectedRow[2]);
            expectedRows.AddItem(expectedRow[0]);
            expectedRows.AddItem(expectedRow[3]);
            expectedRows.AddItem(expectedRow[1]);
            expectedRows.AddItem(expectedRow[4]);
            expectedQueryResult = CreateExpectedQueryResult(expectedRows, 0);
            Assert.AreEqual(expectedQueryResult.Select(kvp => kvp.Key).OrderBy(k => k), allDocs.Select(kvp => kvp.Key).OrderBy(k => k));

            // Get specific documents:
            options = new QueryOptions();
            IList<object> docIds = new List<object>();
            QueryRow expected2 = expectedRow[2];
            docIds.AddItem(expected2.Document.Id);
            options.SetKeys(docIds);
            allDocs = database.GetAllDocs(options);
            expectedRows = new List<QueryRow>();
            expectedRows.AddItem(expected2);
            expectedQueryResult = CreateExpectedQueryResult(expectedRows, 0);
            Assert.AreEqual(expectedQueryResult.Select(kvp => kvp.Key).OrderBy(k => k), allDocs.Select(kvp => kvp.Key).OrderBy(k => k));
        }
        public void TestViewGrouped()
        {
            IDictionary<string, object> docProperties1 = new Dictionary<string, object>();
            docProperties1["_id"] = "1";
            docProperties1["artist"] = "Gang Of Four";
            docProperties1["album"] = "Entertainment!";
            docProperties1["track"] = "Ether";
            docProperties1["time"] = 231;
            PutDoc(database, docProperties1);

            IDictionary<string, object> docProperties2 = new Dictionary<string, object>();
            docProperties2["_id"] = "2";
            docProperties2["artist"] = "Gang Of Four";
            docProperties2["album"] = "Songs Of The Free";
            docProperties2["track"] = "I Love A Man In Uniform";
            docProperties2["time"] = 248;
            PutDoc(database, docProperties2);

            IDictionary<string, object> docProperties3 = new Dictionary<string, object>();
            docProperties3["_id"] = "3";
            docProperties3["artist"] = "Gang Of Four";
            docProperties3["album"] = "Entertainment!";
            docProperties3["track"] = "Natural's Not In It";
            docProperties3["time"] = 187;
            PutDoc(database, docProperties3);

            IDictionary<string, object> docProperties4 = new Dictionary<string, object>();
            docProperties4["_id"] = "4";
            docProperties4["artist"] = "PiL";
            docProperties4["album"] = "Metal Box";
            docProperties4["track"] = "Memories";
            docProperties4["time"] = 309;
            PutDoc(database, docProperties4);

            IDictionary<string, object> docProperties5 = new Dictionary<string, object>();
            docProperties5["_id"] = "5";
            docProperties5["artist"] = "Gang Of Four";
            docProperties5["album"] = "Entertainment!";
            docProperties5["track"] = "Not Great Men";
            docProperties5["time"] = 187;
            PutDoc(database, docProperties5);

            View view = database.GetView("grouper");
            view.SetMapReduce((document, emitter) =>
            {
                    IList<object> key = new List<object>();
                    key.AddItem(document["artist"]);
                    key.AddItem(document["album"]);
                    key.AddItem(document["track"]);
                    emitter(key, document["time"]);
            }, BuiltinReduceFunctions.Sum, "1");
                
            view.UpdateIndex();
            QueryOptions options = new QueryOptions();
            options.Reduce = true;

            IList<QueryRow> rows = view.QueryWithOptions(options).ToList();
            IList<IDictionary<string, object>> expectedRows = new List<IDictionary<string, object>>();
            IDictionary<string, object> row1 = new Dictionary<string, object>();
            row1["key"] = null;
            row1["value"] = 1162.0;
            expectedRows.AddItem(row1);
            Assert.AreEqual(row1["key"], rows[0].Key);
            Assert.AreEqual(row1["value"], rows[0].Value);

            //now group
            options.Group = true;
            rows = view.QueryWithOptions(options).ToList();
            expectedRows = new List<IDictionary<string, object>>();
            row1 = new Dictionary<string, object>();
            IList<string> key1 = new List<string>();
            key1.AddItem("Gang Of Four");
            key1.AddItem("Entertainment!");
            key1.AddItem("Ether");
            row1["key"] = key1;
            row1["value"] = 231.0;
            expectedRows.AddItem(row1);

            IDictionary<string, object> row2 = new Dictionary<string, object>();
            IList<string> key2 = new List<string>();
            key2.AddItem("Gang Of Four");
            key2.AddItem("Entertainment!");
            key2.AddItem("Natural's Not In It");
            row2["key"] = key2;
            row2["value"] = 187.0;
            expectedRows.AddItem(row2);

            IDictionary<string, object> row3 = new Dictionary<string, object>();
            IList<string> key3 = new List<string>();
            key3.AddItem("Gang Of Four");
            key3.AddItem("Entertainment!");
            key3.AddItem("Not Great Men");
            row3["key"] = key3;
            row3["value"] = 187.0;
            expectedRows.AddItem(row3);

            IDictionary<string, object> row4 = new Dictionary<string, object>();
            IList<string> key4 = new List<string>();
            key4.AddItem("Gang Of Four");
            key4.AddItem("Songs Of The Free");
            key4.AddItem("I Love A Man In Uniform");
            row4["key"] = key4;
            row4["value"] = 248.0;
            expectedRows.AddItem(row4);

            IDictionary<string, object> row5 = new Dictionary<string, object>();
            IList<string> key5 = new List<string>();
            key5.AddItem("PiL");
            key5.AddItem("Metal Box");
            key5.AddItem("Memories");
            row5["key"] = key5;
            row5["value"] = 309.0;
            expectedRows.AddItem(row5);
            Assert.AreEqual(row1["key"], rows[0].Key.AsList<string>());
            Assert.AreEqual(row1["value"], rows[0].Value);
            Assert.AreEqual(row2["key"], rows[1].Key.AsList<string>());
            Assert.AreEqual(row2["value"], rows[1].Value);
            Assert.AreEqual(row3["key"], rows[2].Key.AsList<string>());
            Assert.AreEqual(row3["value"], rows[2].Value);
            Assert.AreEqual(row4["key"], rows[3].Key.AsList<string>());
            Assert.AreEqual(row4["value"], rows[3].Value);
            Assert.AreEqual(row5["key"], rows[4].Key.AsList<string>());
            Assert.AreEqual(row5["value"], rows[4].Value);

            //group level 1
            options.GroupLevel = 1;
            rows = view.QueryWithOptions(options).ToList();
            expectedRows = new List<IDictionary<string, object>>();
            row1 = new Dictionary<string, object>();
            key1 = new List<string>();
            key1.AddItem("Gang Of Four");
            row1["key"] = key1;
            row1["value"] = 853.0;

            expectedRows.AddItem(row1);
            row2 = new Dictionary<string, object>();
            key2 = new List<string>();
            key2.AddItem("PiL");
            row2["key"] = key2;
            row2["value"] = 309.0;
            expectedRows.AddItem(row2);
            Assert.AreEqual(row1["key"], rows[0].Key.AsList<object>());
            Assert.AreEqual(row1["value"], rows[0].Value);
            Assert.AreEqual(row2["key"], rows[1].Key.AsList<object>());
            Assert.AreEqual(row2["value"], rows[1].Value);

            //group level 2
            options.GroupLevel = 2;
            rows = view.QueryWithOptions(options).ToList();
            expectedRows = new List<IDictionary<string, object>>();
            row1 = new Dictionary<string, object>();
            key1 = new List<string>();
            key1.AddItem("Gang Of Four");
            key1.AddItem("Entertainment!");
            row1["key"] = key1;
            row1["value"] = 605.0;
            expectedRows.AddItem(row1);
            row2 = new Dictionary<string, object>();
            key2 = new List<string>();
            key2.AddItem("Gang Of Four");
            key2.AddItem("Songs Of The Free");
            row2["key"] = key2;
            row2["value"] = 248.0;
            expectedRows.AddItem(row2);
            row3 = new Dictionary<string, object>();
            key3 = new List<string>();
            key3.AddItem("PiL");
            key3.AddItem("Metal Box");
            row3["key"] = key3;
            row3["value"] = 309.0;
            expectedRows.AddItem(row3);
            Assert.AreEqual(row1["key"], rows[0].Key.AsList<object>());
            Assert.AreEqual(row1["value"], rows[0].Value);
            Assert.AreEqual(row2["key"], rows[1].Key.AsList<object>());
            Assert.AreEqual(row2["value"], rows[1].Value);
            Assert.AreEqual(row3["key"], rows[2].Key.AsList<object>());
            Assert.AreEqual(row3["value"], rows[2].Value);
        }
        public void TestChangeTrackerWithDocsIds()
        {
            var testURL = GetReplicationURL();
            var changeTracker = new ChangeTracker(testURL, ChangeTrackerMode
                .LongPoll, 0, false, null);

            var docIds = new List<string>();
            docIds.AddItem("doc1");
            docIds.AddItem("doc2");
            changeTracker.SetDocIDs(docIds);

            var docIdsJson = "[\"doc1\",\"doc2\"]";
            var docIdsEncoded = Uri.EscapeUriString(docIdsJson);
            var expectedFeedPath = string.Format("_changes?feed=longpoll&limit=50&heartbeat=300000&since=0&filter=_doc_ids&doc_ids={0}", 
                docIdsEncoded);
            string changesFeedPath = changeTracker.GetChangesFeedPath();
            Assert.AreEqual(expectedFeedPath, changesFeedPath);

            changeTracker.UsePost = true;
            var parameters = changeTracker.GetChangesFeedParams();
            Assert.AreEqual("_doc_ids", parameters["filter"]);
            AssertEnumerablesAreEqual(docIds, (IEnumerable)parameters["doc_ids"]);

            var body = changeTracker.GetChangesFeedPostBody();
            Assert.IsTrue(body.Contains(docIdsJson));
        }
        public void TestRevTree()
        {
            var rev = new RevisionInternal("MyDocId", "4-abcd", false);
            var revProperties = new Dictionary<string, object>();
            revProperties.Put("_id", rev.GetDocId());
            revProperties.Put("_rev", rev.GetRevId());
            revProperties["message"] = "hi";
            rev.SetProperties(revProperties);

            var revHistory = new List<string>();
            revHistory.AddItem(rev.GetRevId());
            revHistory.AddItem("3-abcd");
            revHistory.AddItem("2-abcd");
            revHistory.AddItem("1-abcd");
            database.ForceInsert(rev, revHistory, null);
            Assert.AreEqual(1, database.DocumentCount);

            VerifyHistory(database, rev, revHistory);
            var conflict = new RevisionInternal("MyDocId", "5-abcd", false);
            var conflictProperties = new Dictionary<string, object>();
            conflictProperties.Put("_id", conflict.GetDocId());
            conflictProperties.Put("_rev", conflict.GetRevId());
            conflictProperties["message"] = "yo";
            conflict.SetProperties(conflictProperties);
            
            var conflictHistory = new List<string>();
            conflictHistory.AddItem(conflict.GetRevId());
            conflictHistory.AddItem("4-bcde");
            conflictHistory.AddItem("3-bcde");
            conflictHistory.AddItem("2-abcd");
            conflictHistory.AddItem("1-abcd");
            database.ForceInsert(conflict, conflictHistory, null);
            Assert.AreEqual(1, database.DocumentCount);
            VerifyHistory(database, conflict, conflictHistory);
            
            // Add an unrelated document:
            var other = new RevisionInternal("AnotherDocID", "1-cdef", false);
            var otherProperties = new Dictionary<string, object>();
            otherProperties["language"] = "jp";
            other.SetProperties(otherProperties);
            var otherHistory = new List<string>();
            otherHistory.AddItem(other.GetRevId());
            database.ForceInsert(other, otherHistory, null);
            
            // Fetch one of those phantom revisions with no body:
            var rev2 = database.GetDocument(rev.GetDocId(), "2-abcd", 
                true);
            Assert.IsNull(rev2);

            // Make sure no duplicate rows were inserted for the common revisions:
            Assert.IsTrue(database.LastSequenceNumber <= 8);
            // Make sure the revision with the higher revID wins the conflict:
            var current = database.GetDocument(rev.GetDocId(), null, 
                true);
            Assert.AreEqual(conflict, current);
            
            // Get the _changes feed and verify only the winner is in it:
            var options = new ChangesOptions();
            var changes = database.ChangesSince(0, options, null, null);
            var expectedChanges = new RevisionList();
            expectedChanges.AddItem(conflict);
            expectedChanges.AddItem(other);
            Assert.AreEqual(expectedChanges, changes);
            options.IncludeConflicts = true;
            changes = database.ChangesSince(0, options, null, null);
            expectedChanges = new RevisionList();
            expectedChanges.AddItem(rev);
            expectedChanges.AddItem(conflict);
            expectedChanges.AddItem(other);
            var expectedChangesAlt = new RevisionList();
            expectedChangesAlt.AddItem(conflict);
            expectedChangesAlt.AddItem(rev);
            expectedChangesAlt.AddItem(other);
            Assert.IsTrue(expectedChanges.SequenceEqual(changes) || expectedChangesAlt.SequenceEqual(changes));
        }
Beispiel #8
0
 public void TestListAddItem()
 {
     List list = new List("list");
     Assert.AreEqual(list, list.AddItem("item"));
 }
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        private IList<RevisionInternal> PutDocs(Database db)
        {
            var result = new List<RevisionInternal>();

            var dict2 = new Dictionary<string, object>();
            dict2["_id"] = "22222";
            dict2["key"] = "two";
            result.AddItem(PutDoc(db, dict2));

            var dict4 = new Dictionary<string, object>();
            dict4["_id"] = "44444";
            dict4["key"] = "four";
            result.AddItem(PutDoc(db, dict4));

            var dict1 = new Dictionary<string, object>();
            dict1["_id"] = "11111";
            dict1["key"] = "one";
            result.AddItem(PutDoc(db, dict1));

            var dict3 = new Dictionary<string, object>();
            dict3["_id"] = "33333";
            dict3["key"] = "three";
            result.AddItem(PutDoc(db, dict3));

            var dict5 = new Dictionary<string, object>();
            dict5["_id"] = "55555";
            dict5["key"] = "five";
            result.AddItem(PutDoc(db, dict5));

            return result;
        }
 /// <summary>https://github.com/couchbase/couchbase-lite-java-core/issues/188</summary>
 /// <exception cref="System.Exception"></exception>
 public virtual void TestServerDoesNotSupportMultipart()
 {
     NUnit.Framework.Assert.AreEqual(0, database.GetLastSequenceNumber());
     IDictionary<string, object> properties1 = new Dictionary<string, object>();
     properties1.Put("dynamic", 1);
     Document doc = CreateDocWithProperties(properties1);
     SavedRevision doc1Rev = doc.GetCurrentRevision();
     // Add attachment to document
     UnsavedRevision doc2UnsavedRev = doc.CreateRevision();
     InputStream attachmentStream = GetAsset("attachment.png");
     doc2UnsavedRev.SetAttachment("attachment.png", "image/png", attachmentStream);
     SavedRevision doc2Rev = doc2UnsavedRev.Save();
     NUnit.Framework.Assert.IsNotNull(doc2Rev);
     CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient();
     mockHttpClient.AddResponderFakeLocalDocumentUpdate404();
     Queue<CustomizableMockHttpClient.Responder> responders = new List<CustomizableMockHttpClient.Responder
         >();
     //first http://url/db/foo (foo==docid)
     //Reject multipart PUT with response code 415
     responders.AddItem(new _Responder_1691());
     // second http://url/db/foo (foo==docid)
     // second call should be plain json, return good response
     responders.AddItem(new _Responder_1701(doc));
     ResponderChain responderChain = new ResponderChain(responders);
     mockHttpClient.SetResponder(doc.GetId(), responderChain);
     // create replication and add observer
     manager.SetDefaultHttpClientFactory(MockFactoryFactory(mockHttpClient));
     Replication pusher = database.CreatePushReplication(GetReplicationURL());
     RunReplication(pusher);
     IList<HttpWebRequest> captured = mockHttpClient.GetCapturedRequests();
     int entityIndex = 0;
     foreach (HttpWebRequest httpRequest in captured)
     {
         // verify that there are no PUT requests with attachments
         if (httpRequest is HttpPut)
         {
             HttpPut httpPut = (HttpPut)httpRequest;
             HttpEntity entity = httpPut.GetEntity();
             if (entityIndex++ == 0)
             {
                 NUnit.Framework.Assert.IsTrue("PUT request with attachment is not multipart", entity
                      is MultipartEntity);
             }
             else
             {
                 NUnit.Framework.Assert.IsFalse("PUT request with attachment is multipart", entity
                      is MultipartEntity);
             }
         }
     }
 }
        public void TestMakeRevisionHistoryDict()
        {
            var revs = new List<RevisionInternal>();
            revs.AddItem(Mkrev("4-jkl"));
            revs.AddItem(Mkrev("3-ghi"));
            revs.AddItem(Mkrev("2-def"));

            var expectedSuffixes = new List<string>();
            expectedSuffixes.AddItem("jkl");
            expectedSuffixes.AddItem("ghi");
            expectedSuffixes.AddItem("def");

            var expectedHistoryDict = new Dictionary<string, object>();
            expectedHistoryDict["start"] = 4;
            expectedHistoryDict["ids"] = expectedSuffixes;

            var historyDict = Database.MakeRevisionHistoryDict(revs);
            Assert.AreEqual(expectedHistoryDict, historyDict);
            
            revs = new List<RevisionInternal>();
            revs.AddItem(Mkrev("4-jkl"));
            revs.AddItem(Mkrev("2-def"));
            
            expectedSuffixes = new List<string>();
            expectedSuffixes.AddItem("4-jkl");
            expectedSuffixes.AddItem("2-def");
            
            expectedHistoryDict = new Dictionary<string, object>();
            expectedHistoryDict["ids"] = expectedSuffixes;
            historyDict = Database.MakeRevisionHistoryDict(revs);
            Assert.AreEqual(expectedHistoryDict, historyDict);

            revs = new List<RevisionInternal>();
            revs.AddItem(Mkrev("12345"));
            revs.AddItem(Mkrev("6789"));
            
            expectedSuffixes = new List<string>();
            expectedSuffixes.AddItem("12345");
            expectedSuffixes.AddItem("6789");
            
            expectedHistoryDict = new Dictionary<string, object>();
            expectedHistoryDict["ids"] = expectedSuffixes;
            historyDict = Database.MakeRevisionHistoryDict(revs);
            
            Assert.AreEqual(expectedHistoryDict, historyDict);
        }
 /// <summary>https://github.com/couchbase/couchbase-lite-android/issues/247</summary>
 /// <exception cref="System.Exception"></exception>
 public virtual void RunPushReplicationWithTransientError(int statusCode, string statusMsg
     , bool expectReplicatorError)
 {
     IDictionary<string, object> properties1 = new Dictionary<string, object>();
     properties1.Put("doc1", "testPushReplicationTransientError");
     CreateDocWithProperties(properties1);
     CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient();
     mockHttpClient.AddResponderFakeLocalDocumentUpdate404();
     CustomizableMockHttpClient.Responder sentinal = CustomizableMockHttpClient.FakeBulkDocsResponder
         ();
     Queue<CustomizableMockHttpClient.Responder> responders = new List<CustomizableMockHttpClient.Responder
         >();
     responders.AddItem(CustomizableMockHttpClient.TransientErrorResponder(statusCode, 
         statusMsg));
     ResponderChain responderChain = new ResponderChain(responders, sentinal);
     mockHttpClient.SetResponder("_bulk_docs", responderChain);
     // create a replication observer to wait until replication finishes
     CountDownLatch replicationDoneSignal = new CountDownLatch(1);
     LiteTestCase.ReplicationFinishedObserver replicationFinishedObserver = new LiteTestCase.ReplicationFinishedObserver
         (replicationDoneSignal);
     // create replication and add observer
     manager.SetDefaultHttpClientFactory(MockFactoryFactory(mockHttpClient));
     Replication pusher = database.CreatePushReplication(GetReplicationURL());
     pusher.AddChangeListener(replicationFinishedObserver);
     // save the checkpoint id for later usage
     string checkpointId = pusher.RemoteCheckpointDocID();
     // kick off the replication
     pusher.Start();
     // wait for it to finish
     bool success = replicationDoneSignal.Await(60, TimeUnit.Seconds);
     NUnit.Framework.Assert.IsTrue(success);
     Log.D(Tag, "replicationDoneSignal finished");
     if (expectReplicatorError == true)
     {
         NUnit.Framework.Assert.IsNotNull(pusher.GetLastError());
     }
     else
     {
         NUnit.Framework.Assert.IsNull(pusher.GetLastError());
     }
     // workaround for the fact that the replicationDoneSignal.wait() call will unblock before all
     // the statements in Replication.stopped() have even had a chance to execute.
     // (specifically the ones that come after the call to notifyChangeListeners())
     Sharpen.Thread.Sleep(500);
     string localLastSequence = database.LastSequenceWithCheckpointId(checkpointId);
     if (expectReplicatorError == true)
     {
         NUnit.Framework.Assert.IsNull(localLastSequence);
     }
     else
     {
         NUnit.Framework.Assert.IsNotNull(localLastSequence);
     }
 }
Beispiel #13
0
		public virtual void Test005_PutGetStringList()
		{
			Config c = new Config();
			List<string> values = new List<string>();
			values.AddItem("value1");
			values.AddItem("value2");
			c.SetStringList("my", null, "somename", values);
			object[] expArr = Sharpen.Collections.ToArray(values);
			string[] actArr = c.GetStringList("my", null, "somename");
			CollectionAssert.AreEquivalent(expArr, actArr);
			string expText = "[my]\n\tsomename = value1\n\tsomename = value2\n";
			NUnit.Framework.Assert.AreEqual(expText, c.ToText());
		}
 public HttpClient GetHttpClient()
 {
     CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient();
     CustomizableMockHttpClient.Responder sentinal = this.DefaultChangesResponder();
     Queue<CustomizableMockHttpClient.Responder> responders = new List<CustomizableMockHttpClient.Responder
         >();
     responders.AddItem(this.DefaultChangesResponder());
     responders.AddItem(CustomizableMockHttpClient.TransientErrorResponder(errorCode, 
         statusMessage));
     ResponderChain responderChain = new ResponderChain(responders, sentinal);
     mockHttpClient.SetResponder("_changes", responderChain);
     return mockHttpClient;
 }
Beispiel #15
0
        public void TestCreateNewRevisions()
        {
            var properties = new Dictionary<String, Object>();
            properties["testName"] = "testCreateRevisions";
            properties["tag"] = 1337;
            var db = database;

            var doc = db.CreateDocument();
            var newRev = doc.CreateRevision();
            var newRevDocument = newRev.Document;
            Assert.AreEqual(doc, newRevDocument);
            Assert.AreEqual(db, newRev.Database);
            Assert.IsNull(newRev.ParentId);
            Assert.IsNull(newRev.Parent);

            var expectProperties = new Dictionary<String, Object>();
            expectProperties["_id"] = doc.Id;
            Assert.AreEqual(expectProperties, newRev.Properties);
            Assert.IsTrue(!newRev.IsDeletion);
            Assert.AreEqual(newRev.Sequence, 0);

            //ios support another approach to set properties::
            //newRev.([@"testName"] = @"testCreateRevisions";
            //newRev[@"tag"] = @1337;
            newRev.SetUserProperties(properties);
            Assert.AreEqual(newRev.UserProperties, properties);

            var rev1 = newRev.Save();
            Assert.IsNotNull(rev1, "Save 1 failed");
            Assert.AreEqual(doc.CurrentRevision, rev1);
            Assert.IsNotNull(rev1.Id.StartsWith("1-"));
            Assert.AreEqual(1, rev1.Sequence);
            Assert.IsNull(rev1.ParentId);
            Assert.IsNull(rev1.Parent);

            newRev = rev1.CreateRevision();
            newRevDocument = newRev.Document;
            Assert.AreEqual(doc, newRevDocument);
            Assert.AreEqual(db, newRev.Database);
            Assert.AreEqual(rev1.Id, newRev.ParentId);
            Assert.AreEqual(rev1, newRev.Parent);
            Assert.AreEqual(rev1.Properties, newRev.Properties);
            Assert.AreEqual(rev1.UserProperties, newRev.UserProperties);
            Assert.IsTrue(!newRev.IsDeletion);

            // we can't add/modify one property as on ios. need  to add separate method?
            // newRev[@"tag"] = @4567;
            properties["tag"] = 4567;
            newRev.SetUserProperties(properties);
            var rev2 = newRev.Save();
            Assert.IsNotNull(rev2, "Save 2 failed");
            Assert.AreEqual(doc.CurrentRevision, rev2);
            Assert.IsTrue(rev2.Id.StartsWith("2-"));
            Assert.AreEqual(2, rev2.Sequence);
            Assert.AreEqual(rev1.Id, rev2.ParentId);
            Assert.AreEqual(rev1, rev2.Parent);
            Assert.IsTrue(doc.CurrentRevisionId.StartsWith("2-"), "Document revision ID is still " + doc.CurrentRevisionId);

            // Add a deletion/tombstone revision:
            newRev = doc.CreateRevision();
            Assert.AreEqual(rev2.Id, newRev.ParentId);
            Assert.AreEqual(rev2, newRev.Parent);

            newRev.IsDeletion = true;
            var rev3 = newRev.Save();
            Assert.IsNotNull(rev3, "Save 3 failed");
            Assert.IsTrue (rev3.Id.StartsWith ("3-", StringComparison.Ordinal), "Unexpected revID " + rev3.Id);
            Assert.AreEqual(3, rev3.Sequence);
            Assert.IsTrue(rev3.IsDeletion);
            Assert.IsTrue(doc.Deleted);
            Assert.IsNull(doc.CurrentRevision);
            var leafRevs = new List<SavedRevision>();
            leafRevs.AddItem(rev3);
            Assert.AreEqual(doc.LeafRevisions, leafRevs);

            var doc2 = db.GetDocument(doc.Id);
            Assert.AreEqual(doc, doc2);
            Assert.IsNull(db.GetExistingDocument(doc.Id));
        }
        // http://wiki.apache.org/couchdb/Introduction_to_CouchDB_views#Linked_documents
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        private IList<RevisionInternal> PutLinkedDocs(Database db)
        {
            var result = new List<RevisionInternal>();

            var dict1 = new Dictionary<string, object>();
            dict1["_id"] = "11111";
            result.AddItem(PutDoc(db, dict1));

            var dict2 = new Dictionary<string, object>();
            dict2["_id"] = "22222";
            dict2["value"] = "hello";
            dict2["ancestors"] = new string[] { "11111" };
            result.AddItem(PutDoc(db, dict2));

            var dict3 = new Dictionary<string, object>();
            dict3["_id"] = "33333";
            dict3["value"] = "world";
            dict3["ancestors"] = new string[] { "22222", "11111" };
            result.AddItem(PutDoc(db, dict3));

            return result;
        }
Beispiel #17
0
        public void TestConflict()
        {
            var prop = new Dictionary<String, Object>();
            prop["foo"] = "bar";

            var db = database;

            var doc = CreateDocumentWithProperties(db, prop);

            var rev1 = doc.CurrentRevision;

            var properties = new Dictionary<String, Object>(doc.Properties);
            properties["tag"] = 2;

            var rev2a = doc.PutProperties(properties);
            properties = new Dictionary<String, Object>(rev1.Properties);
            properties["tag"] = 3;
            var newRev = rev1.CreateRevision();
            newRev.SetProperties(properties);
            var rev2b = newRev.Save(allowConflict: true);
            Assert.IsNotNull(rev2b, "Failed to create a a conflict");

            var confRevs = new List<SavedRevision>();
            confRevs.AddItem(rev2b);
            confRevs.AddItem(rev2a);
            Assert.AreEqual(confRevs, doc.ConflictingRevisions);
            Assert.AreEqual(confRevs, doc.LeafRevisions);

            SavedRevision defaultRev;
            SavedRevision otherRev;
            if (String.CompareOrdinal (rev2a.Id, rev2b.Id) > 0)
            {
                defaultRev = rev2a;
                otherRev = rev2b;
            }
            else
            {
                defaultRev = rev2b;
                otherRev = rev2a;
            }
            Assert.AreEqual(doc.CurrentRevision, defaultRev);

            var query = db.CreateAllDocumentsQuery();
            query.AllDocsMode = AllDocsMode.ShowConflicts;
            var rows = query.Run();
            Assert.AreEqual(1, rows.Count);

            var row = rows.GetRow(0);
            var revs = row.GetConflictingRevisions().ToList();
            Assert.AreEqual(2, revs.Count);
            Assert.AreEqual(defaultRev, revs[0]);
            Assert.AreEqual(otherRev, revs[1]);
        }
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        public virtual void PutNDocs(Database db, int n)
        {
            for (int i = 0; i < n; i++)
            {
                var doc = new Dictionary<string, object>();
                doc.Put("_id", string.Format("{0}", i));

                var key = new List<string>();
                for (int j = 0; j < 256; j++)
                {
                    key.AddItem("key");
                }
                key.AddItem(string.Format("key-{0}", i));
                doc["key"] = key;

                PutDocViaUntitledDoc(db, doc);
            }
        }
        public void TestChannels()
        {
            Uri remote = GetReplicationURL();
            Replication replicator = database.CreatePullReplication(remote);

            var channels = new List<string>();
            channels.AddItem("chan1");
            channels.AddItem("chan2");
            replicator.Channels = channels;
            Assert.AreEqual(channels, replicator.Channels);

            replicator.Channels = null;
            Assert.IsTrue(replicator.Channels.ToList().Count == 0);
        }
        public void TestViewQuery()
        {
            PutDocs(database);
            var view = CreateView(database);
            view.UpdateIndex();

            // Query all rows:
            QueryOptions options = new QueryOptions();
            IList<QueryRow> rows = view.QueryWithOptions(options).ToList();

            var expectedRows = new List<object>();

            var dict5 = new Dictionary<string, object>();
            dict5["id"] = "55555";
            dict5["key"] = "five";
            expectedRows.AddItem(dict5);

            var dict4 = new Dictionary<string, object>();
            dict4["id"] = "44444";
            dict4["key"] = "four";
            expectedRows.AddItem(dict4);

            var dict1 = new Dictionary<string, object>();
            dict1["id"] = "11111";
            dict1["key"] = "one";
            expectedRows.AddItem(dict1);

            var dict3 = new Dictionary<string, object>();
            dict3["id"] = "33333";
            dict3["key"] = "three";
            expectedRows.AddItem(dict3);

            var dict2 = new Dictionary<string, object>();
            dict2["id"] = "22222";
            dict2["key"] = "two";
            expectedRows.AddItem(dict2);
            Assert.AreEqual(5, rows.Count);
            Assert.AreEqual(dict5["key"], rows[0].Key);
            Assert.AreEqual(dict4["key"], rows[1].Key);
            Assert.AreEqual(dict1["key"], rows[2].Key);
            Assert.AreEqual(dict3["key"], rows[3].Key);
            Assert.AreEqual(dict2["key"], rows[4].Key);

            // Start/end key query:
            options = new QueryOptions();
            options.StartKey = "a";
            options.EndKey = "one";

            rows = view.QueryWithOptions(options).ToList();
            expectedRows = new List<object>();
            expectedRows.AddItem(dict5);
            expectedRows.AddItem(dict4);
            expectedRows.AddItem(dict1);
            Assert.AreEqual(3, rows.Count);
            Assert.AreEqual(dict5["key"], rows[0].Key);
            Assert.AreEqual(dict4["key"], rows[1].Key);
            Assert.AreEqual(dict1["key"], rows[2].Key);

            // Start/end query without inclusive end:
            options.InclusiveEnd = false;
            rows = view.QueryWithOptions(options).ToList();
            expectedRows = new List<object>();
            expectedRows.AddItem(dict5);
            expectedRows.AddItem(dict4);
            Assert.AreEqual(2, rows.Count);
            Assert.AreEqual(dict5["key"], rows[0].Key);
            Assert.AreEqual(dict4["key"], rows[1].Key);

            // Reversed:
            options.Descending = true;
            options.StartKey = "o";
            options.EndKey = "five";
            options.InclusiveEnd = true;
            rows = view.QueryWithOptions(options).ToList();
            expectedRows = new List<object>();
            expectedRows.AddItem(dict4);
            expectedRows.AddItem(dict5);
            Assert.AreEqual(2, rows.Count);
            Assert.AreEqual(dict4["key"], rows[0].Key);
            Assert.AreEqual(dict5["key"], rows[1].Key);

            // Reversed, no inclusive end:
            options.InclusiveEnd = false;
            rows = view.QueryWithOptions(options).ToList();
            expectedRows = new List<object>();
            expectedRows.AddItem(dict4);
            Assert.AreEqual(1, rows.Count);
            Assert.AreEqual(dict4["key"], rows[0].Key);

            // Specific keys: (note that rows should be in same order as input keys, not sorted)
            options = new QueryOptions();
            var keys = new List<object>();
            keys.AddItem("two");
            keys.AddItem("four");
            options.Keys = keys;
            rows = view.QueryWithOptions(options).ToList();
            expectedRows = new List<object>();
            expectedRows.AddItem(dict4);
            expectedRows.AddItem(dict2);
            Assert.AreEqual(2, rows.Count);
            Assert.AreEqual(dict2["key"], rows[0].Key);
            Assert.AreEqual(dict4["key"], rows[1].Key);
        }
        public void TestChannels()
        {
            if (!Boolean.Parse((string)Runtime.Properties["replicationTestsEnabled"]))
            {
                Assert.Inconclusive("Replication tests disabled.");
                return;
            }
            var remote = GetReplicationURL();
            var replicator = database.CreatePullReplication(remote);

            var channels = new List<string>();
            channels.AddItem("chan1");
            channels.AddItem("chan2");
            replicator.Channels = channels;
            Assert.AreEqual(channels, replicator.Channels);

            replicator.Channels = null;
            Assert.IsTrue(replicator.Channels.ToList().Count == 0);
        }
        public void TestRevTree()
        {
            var rev = new RevisionInternal("MyDocId", "4-foxy", false);
            var revProperties = new Dictionary<string, object>();
            revProperties.Put("_id", rev.GetDocId());
            revProperties.Put("_rev", rev.GetRevId());
            revProperties["message"] = "hi";
            rev.SetProperties(revProperties);

            var revHistory = new List<string>();
            revHistory.AddItem(rev.GetRevId());
            revHistory.AddItem("3-thrice");
            revHistory.AddItem("2-too");
            revHistory.AddItem("1-won");
            database.ForceInsert(rev, revHistory, null);
            Assert.AreEqual(1, database.DocumentCount);

            VerifyHistory(database, rev, revHistory);
            var conflict = new RevisionInternal("MyDocId", "5-epsilon", false);
            var conflictProperties = new Dictionary<string, object>();
            conflictProperties.Put("_id", conflict.GetDocId());
            conflictProperties.Put("_rev", conflict.GetRevId());
            conflictProperties["message"] = "yo";
            conflict.SetProperties(conflictProperties);
            
            var conflictHistory = new List<string>();
            conflictHistory.AddItem(conflict.GetRevId());
            conflictHistory.AddItem("4-delta");
            conflictHistory.AddItem("3-gamma");
            conflictHistory.AddItem("2-too");
            conflictHistory.AddItem("1-won");
            database.ForceInsert(conflict, conflictHistory, null);
            Assert.AreEqual(1, database.DocumentCount);
            VerifyHistory(database, conflict, conflictHistory);
            
            // Add an unrelated document:
            var other = new RevisionInternal("AnotherDocID", "1-ichi", false);
            var otherProperties = new Dictionary<string, object>();
            otherProperties["language"] = "jp";
            other.SetProperties(otherProperties);
            var otherHistory = new List<string>();
            otherHistory.AddItem(other.GetRevId());
            database.ForceInsert(other, otherHistory, null);
            
            // Fetch one of those phantom revisions with no body:
            var rev2 = database.GetDocumentWithIDAndRev(rev.GetDocId(), "2-too", 
                DocumentContentOptions.None);
            Assert.AreEqual(rev.GetDocId(), rev2.GetDocId());
            Assert.AreEqual("2-too", rev2.GetRevId());
            
            // Make sure no duplicate rows were inserted for the common revisions:
            Assert.AreEqual(8, database.GetLastSequenceNumber());
            // Make sure the revision with the higher revID wins the conflict:
            var current = database.GetDocumentWithIDAndRev(rev.GetDocId(), null, 
                DocumentContentOptions.None);
            Assert.AreEqual(conflict, current);
            
            // Get the _changes feed and verify only the winner is in it:
            var options = new ChangesOptions();
            var changes = database.ChangesSince(0, options, null);
            var expectedChanges = new RevisionList();
            expectedChanges.AddItem(conflict);
            expectedChanges.AddItem(other);
            Assert.AreEqual(changes, expectedChanges);
            options.SetIncludeConflicts(true);
            changes = database.ChangesSince(0, options, null);
            expectedChanges = new RevisionList();
            expectedChanges.AddItem(rev);
            expectedChanges.AddItem(conflict);
            expectedChanges.AddItem(other);
            Assert.AreEqual(changes, expectedChanges);
        }