How to use Dummy class of ExampleTest package

Best Nunit code snippet using ExampleTest.Dummy

DatabaseTest.cs

Source:DatabaseTest.cs Github

copy

Full Screen

1//2//  DatabaseTest.cs3//4//  Copyright (c) 2017 Couchbase, Inc All rights reserved.5//6//  Licensed under the Apache License, Version 2.0 (the "License");7//  you may not use this file except in compliance with the License.8//  You may obtain a copy of the License at9//10//  http://www.apache.org/licenses/LICENSE-2.011//12//  Unless required by applicable law or agreed to in writing, software13//  distributed under the License is distributed on an "AS IS" BASIS,14//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15//  See the License for the specific language governing permissions and16//  limitations under the License.17//18using System;19using System.Collections.Generic;20using System.IO;21using System.Text;22using System.Threading.Tasks;23using Couchbase.Lite;24using FluentAssertions;25using LiteCore;26using LiteCore.Interop;27using System.Linq;28using System.Threading;29using Couchbase.Lite.Query;30using Couchbase.Lite.Logging;31using Couchbase.Lite.DI;32#if !WINDOWS_UWP33using Xunit;34using Xunit.Abstractions;35#else36using Fact = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;37#endif38namespace Test39{40#if WINDOWS_UWP41    [Microsoft.VisualStudio.TestTools.UnitTesting.TestClass]42#endif43    public class DatabaseTest : TestCase44    {45#if !WINDOWS_UWP46        public DatabaseTest(ITestOutputHelper output) : base(output)47        {48        }49#endif50        [Fact]51        public void TestSimpleN1QLQuery()52        {53            using (var d = new MutableDocument())54            using (var d2 = new MutableDocument())55            {56                d.SetString("firstName", "Jerry");57                d.SetString("lastName", "Ice Cream");58                Db.Save(d);59                d2.SetString("firstName", "Ben");60                d2.SetString("lastName", "Ice Cream");61                Db.Save(d2);62            }63            // Test to catch N1QL query compile error in database CreateQuery() call64            Db.Invoking(o => o.CreateQuery($"SELECT firstName, lastName FROM *")).Should().Throw<CouchbaseLiteException>("because the input N1QL query string has syntax error near character 33.");65            // With new collections implementation, N1QL call will look like "SELECT firstName, lastName FROM _" or "SELECT firstName, lastName FROM _ as whatever"66            // default collection is named _.67            // "SELECT firstName, lastName FROM {Db.Name}" is still valid as well.68            using (var q = Db.CreateQuery($"SELECT firstName, lastName FROM _"))69            {70                var res = q.Execute().AllResults();71                res.Count.Should().Be(2);72                res[0].GetString(0).Should().Be("Jerry");73                res[0].GetString(1).Should().Be("Ice Cream");74                res[1].GetString(0).Should().Be("Ben");75                res[1].GetString(1).Should().Be("Ice Cream");76            }77        }78        [Fact]79        public void TestCreate()80        {81            var dir = Path.Combine(Path.GetTempPath().Replace("cache", "files"), "CouchbaseLite");82            Database.Delete("db", dir);83            var options = new DatabaseConfiguration84            {85                Directory = dir86            };87            try {88                var db = new Database("db", options);89                options = db.Config;90                db.Dispose();91            } finally {92                Database.Delete("db", dir);93            }94            #if COUCHBASE_ENTERPRISE95            options.Invoking(o => o.EncryptionKey = new EncryptionKey("foo")).Should().Throw<InvalidOperationException>("because the configuration is in use");96            #endif97        }98        [Fact]99        public void TestCreateWithDefaultConfiguration()100        {101            using (var db = new Database("db", new DatabaseConfiguration())) {102                db.Count.Should().Be(0);103                DeleteDB(db);104            }105        }106        [Fact]107        public void TestCreateWithSpecialCharacterDBNames()108        {109            using (var db = OpenDB("`~@#$%&'()_+{}][=-.,;'")) {110                db.Name.Should().Be("`~@#$%&'()_+{}][=-.,;'", "because that is the (weird) name that was set");111                Path.GetDirectoryName(db.Path).Should().EndWith(".cblite2", "because that is the current DB extension");112                db.Count.Should().Be(0UL, "because the database is empty");113                db.Delete();114            }115        }116        [Fact]117        public void TestCreateWithEmptyDBNames()118        {119            CouchbaseLiteException e = null; ;120            try {121                OpenDB("");122            } catch (CouchbaseLiteException ex) {123                e = ex;124                ex.Error.Should().Be(CouchbaseLiteError.WrongFormat, "because the database cannot have an empty name");125                ex.Domain.Should().Be(CouchbaseLiteErrorType.CouchbaseLite, "because this is a LiteCore error");126                var exception = new CouchbaseLiteException(C4ErrorCode.NotFound, "database cannot have an empty name", ex);127            }128            e.Should().NotBeNull("because an exception is expected");129        }130        [Fact]131        public void TestCreateWithCustomDirectory()132        {133            var dir = Directory;134            Database.Delete("db", dir);135            Database.Exists("db", dir).Should().BeFalse("because it was just deleted");136            var options = new DatabaseConfiguration137                { Directory = dir };138            using (var db = new Database("db", options)) {139                Path.GetDirectoryName(db.Path).Should().EndWith(".cblite2", "because that is the current CBL extension");140                db.Path.Should().Contain(dir, "because the directory should be present in the custom path");141                Database.Exists("db", dir).Should().BeTrue("because it was just created");142                db.Count.Should().Be(0, "because the database is empty");143                DeleteDB(db);144            }145        }146        [Fact]147        public void TestGetDocumentWithEmptyStringId()148        {149            Db.GetDocument("").Should().BeNull();150        }151        [Fact]152        public void TestGetNonExistingDocWithID()153        {154            Db.GetDocument("non-exist").Should().BeNull("because it doesn't exist");155        }156        [Fact]157        public void TestGetExistingDocWithID()158        {159            var docID = "doc1";160            GenerateDocument(docID);161            VerifyGetDocument(docID);162        }163        [Fact]164        public void TestSaveAndGetMultipleDocs()165        {166            const int NumDocs = 10;167            for (var i = 0; i < NumDocs; i++) {168                using (var doc = new MutableDocument($"doc_{i:D3}")) {169                    doc.SetInt("key", i);170                    Db.Save(doc);171                }172            }173            Db.Count.Should().Be(NumDocs);174            ValidateDocs(NumDocs);175        }176        [Fact]177        public void TestGetExistingDocWithIDFromDifferentDBInstance()178        {179            var docID = "doc1";180            GenerateDocument(docID);181            using (var otherDB = OpenDB(Db.Name)) {182                otherDB.Count.Should()183                    .Be(1UL, "because the other database instance should reflect existing data");184                VerifyGetDocument(otherDB, docID);185            }186        }187        [Fact]188        public void TestGetExistingDocWithIDInBatch()189        {190            var docs = CreateDocs(10);191            Db.InBatch(() => ValidateDocs(10));192            foreach(var doc in docs) {193                doc.Dispose();194            }195        }196        [Fact]197        public void TestGetDocFromClosedDB()198        {199            using(var doc = GenerateDocument("doc1")) {200                Db.Close();201                Db.Invoking(d => d.GetDocument("doc1"))202                    .Should().Throw<InvalidOperationException>()203                    .WithMessage("Attempt to perform an operation on a closed database.",204                        "because this operation is invalid");205            }206        }207        [Fact]208        public void TestSaveNewDocWithID()209        {210            TestSaveNewDoc("doc1");211        }212        [Fact]213        public void TestSaveNewDocWithSpecialCharactersDocID()214        {215            TestSaveNewDoc("`~@#$%^&*()_+{}|\\][=-/.,<>?\":;'");216        }217        [Fact]218        public void TestSaveDoc()219        {220            var docID = "doc1";221            using(var doc = GenerateDocument(docID).ToMutable()) {222                doc.SetInt("key", 2);223                Db.Save(doc);224                Db.Count.Should().Be(1, "because a document was updated, not added");225                VerifyGetDocument(docID, 2);226            }227        }228        [Fact]229        public void TestSaveDocInDifferentDBInstance()230        {231            var docID = "doc1";232            using (var doc = GenerateDocument(docID).ToMutable())233            using (var otherDB = OpenDB(Db.Name)) {234                otherDB.Count.Should()235                    .Be(1UL, "because the other database instance should reflect existing data");236                doc.SetInt("key", 2);237                otherDB.Invoking(d => d.Save(doc))238                    .Should().Throw<CouchbaseLiteException>()239                    .Where(240                        e => e.Error == CouchbaseLiteError.InvalidParameter &&241                             e.Domain == CouchbaseLiteErrorType.CouchbaseLite,242                        "because a document cannot be saved into another database instance");243            }244        }245        [Fact]246        public void TestSaveDocInDifferentDB()247        {248            Database.Delete("otherDB", Directory);249            var docID = "doc1";250            using (var doc = GenerateDocument(docID).ToMutable())251            using (var otherDB = OpenDB("otherDB")) {252                otherDB.Count.Should()253                    .Be(0UL, "because the other database is empty");254                doc.SetInt("key", 2);255                otherDB.Invoking(d => d.Save(doc))256                    .Should().Throw<CouchbaseLiteException>()257                    .Where(258                        e => e.Error == CouchbaseLiteError.InvalidParameter &&259                             e.Domain == CouchbaseLiteErrorType.CouchbaseLite,260                        "because a document cannot be saved into another database");261                DeleteDB(otherDB);262            }263        }264        [Fact]265        public void TestSaveSameDocTwice()266        {267            var docID = "doc1";268            using(var doc = GenerateDocument(docID).ToMutable()) {269                Db.Save(doc);270                doc.Id.Should().Be(docID, "because the doc ID should never change");271                Db.Count.Should().Be(1UL, "because there is still only one document");272            }273        }274        [Fact]275        public void TestSaveInBatch()276        {277            Db.InBatch(() => CreateDocs(10));278            Db.Count.Should().Be(10UL, "because 10 documents were added");279            ValidateDocs(10);280        }281        [Fact]282        public void TestSaveConcurrencyControl()283        {284            using(var doc1a = new MutableDocument("doc1"))285            using (var doc1b = new MutableDocument("doc1")) {286                doc1a.SetString("name", "Jim");287                Db.Save(doc1a);288                doc1b.SetString("name", "Tim");289                Db.Save(doc1b, ConcurrencyControl.FailOnConflict).Should()290                    .BeFalse("beacuse a conflict should not be allowed in this mode");291                using (var gotDoc = Db.GetDocument(doc1a.Id)) {292                    gotDoc.GetString("name").Should().Be("Jim");293                }294                Db.Save(doc1b, ConcurrencyControl.LastWriteWins);295                using (var gotDoc = Db.GetDocument(doc1a.Id)) {296                    gotDoc.GetString("name").Should().Be("Tim");297                }298            }299        }300        [Fact]301        public void TestConflictHandlerSaveMergedDocument()302        {303            using (var doc1 = new MutableDocument("doc1")){304                doc1.SetString("name", "Jim");305                306                Db.Save(doc1);307                // Get two doc1 document objects (doc1a and doc1b):308                var doc1a = Db.GetDocument(doc1.Id).ToMutable();309                var doc1b = Db.GetDocument(doc1.Id).ToMutable();310                // Modify doc1a:311                doc1a.SetString("name", "Jim");312                doc1a.SetString("language", "English");313                        314                Db.Save(doc1a);315                // Modify doc1b:316                doc1b.SetString("name", "Jim");317                doc1b.SetString("language", "C#");318                doc1b.SetString("location", "Japan");        319                Db.Save(doc1b, ResolveConflict);320            }321            using (var doc1 = Db.GetDocument("doc1")) {322                doc1.GetString("name").Should().Be("Jim");323                var lanStr = doc1.GetString("language");324                lanStr.Should().Contain("English");325                lanStr.Should().Contain("C#");326                doc1.GetString("location").Should().Be("Japan");327            }328        }329        [Fact]330        public void TestConflictHandlerWhenDocumentIsPurged()331        {332            using (var doc = new MutableDocument("doc1")) {333                doc.SetString("firstName", "Tiger");334                Db.Save(doc);335            }336            using (var doc = Db.GetDocument("doc1")) {337                doc.Generation.Should().Be(1);338            }339            using (var doc1 = Db.GetDocument("doc1"))340            using (var doc1b = doc1.ToMutable()) {341                Db.Purge("doc1");342                doc1b.SetString("nickName", "Scott");343                Db.Invoking(d => Db.Save(doc1b, (updated, current) =>344                {345                    return true;346                })).Should().Throw<CouchbaseLiteException>()347                    .Where(348                        e => e.Error == CouchbaseLiteError.NotFound &&349                             e.Domain == CouchbaseLiteErrorType.CouchbaseLite,350                        "because the document is purged");351            }352        }353        [Fact]354        public void TestConflictHandlerReturnsTrue()355        {356            using (var doc1 = new MutableDocument("doc1")) {357                doc1.SetString("name", "Jim");358                Db.Save(doc1, (updated, current) => {359                    return true;360                });361                Db.GetDocument("doc1").GetString("name").Should().Be("Jim");362                var doc1a = new MutableDocument(doc1.Id);363                doc1a.SetString("name", "Kim");364                Db.Save(doc1a, (updated, current) => {365                    return true;366                });367                Db.GetDocument("doc1").GetString("name").Should().Be("Kim");368            }369        }370        [Fact]371        public void TestConflictHandlerReturnsFalse()372        {373            using (var doc1 = new MutableDocument("doc1")) {374                doc1.SetString("name", "Jim");375                Db.Save(doc1, (updated, current) => {376                    return false;377                });378                Db.GetDocument(doc1.Id).GetString("name").Should().Be("Jim");379                var doc1a = new MutableDocument(doc1.Id);380                doc1a.SetString("name", "Kim");381                Db.Save(doc1a, (updated, current) => {382                    return false;383                });384                Db.GetDocument("doc1").GetString("name").Should().Be("Jim");385            }386        }387        [Fact]388        public void TestConflictHandlerWithMultipleIncomingConflicts()389        {390            using (var doc1 = new MutableDocument("doc1"))391            using (var doc1a = new MutableDocument("doc1"))392            using (var doc1b = new MutableDocument("doc1")) {393                var waitObj = new AutoResetEvent(true);394                doc1.SetString("name", "Jim");395                Db.Save(doc1);396                Task task2 = Task.Factory.StartNew(() => {397                    doc1a.SetString("name", "Kim");398                    Db.Save(doc1a, (updated, current) => {399                        waitObj.Set();400                        Thread.Sleep(250);401                        waitObj.WaitOne(TimeSpan.FromMilliseconds(250));402                        return false;403                    });404                    waitObj.Set();405                    Thread.Sleep(250);406                });407                waitObj.WaitOne(TimeSpan.FromMilliseconds(250));408                doc1b.SetString("name", "Tim");409                Db.Save(doc1b);410                Db.GetDocument("doc1").GetString("name").Should().Be("Tim");411                waitObj.Set();412                Thread.Sleep(250);413                waitObj.WaitOne(TimeSpan.FromMilliseconds(250));414                Db.GetDocument("doc1").GetString("name").Should().Be("Tim");415            }416        }417        [Fact]418        public void TestConflictHandlerWithDeletedOldDoc()419        {420            using (var doc1 = new MutableDocument("doc1")){421                doc1.SetString("name", "Jim");422                Db.Save(doc1);423                var doc1a = Db.GetDocument("doc1").ToMutable();424                doc1a.SetString("name", "Kim");425                Document currDoc = null;426                var updatedDocName = "";427                //delete old doc428                Db.Delete(doc1);429                Db.Save(doc1a, (updated, current) =>430                {431                    currDoc = current;432                    updatedDocName = updated.GetString("name");433                    return true;434                });435                currDoc.Should().BeNull();436                updatedDocName.Should().Be("Kim");437                Db.GetDocument("doc1").GetString("name").Should().Be("Kim");438            }439        }440        [Fact]441        public void TestSaveDocToClosedDB()442        {443            Db.Close();444            var doc = new MutableDocument("doc1");445            doc.SetInt("key", 1);446            Db.Invoking(d => d.Save(doc))447                .Should().Throw<InvalidOperationException>()448                .WithMessage("Attempt to perform an operation on a closed database.",449                    "because this operation is invalid");450        }451        [Fact]452        public void TestSaveDocToDeletedDB()453        {454            DeleteDB(Db);455            var doc = new MutableDocument("doc1");456            doc.SetInt("key", 1);457            Db.Invoking(d => d.Save(doc))458                .Should().Throw<InvalidOperationException>()459                .WithMessage("Attempt to perform an operation on a closed database.",460                    "because this operation is invalid");461        }462        [Fact]463        public void TestDeletePreSaveDoc()464        {465            var doc = new MutableDocument("doc1");466            doc.SetInt("key", 1);467            Db.Invoking(d => d.Delete(doc))468                .Should().Throw<CouchbaseLiteException>()469                .Where(470                    e => e.Error == CouchbaseLiteError.NotFound &&471                         e.Domain == CouchbaseLiteErrorType.CouchbaseLite,472                    "because deleting an unsaved document is not allowed");473            Db.Count.Should().Be(0UL, "because the database should still be empty");474        }475        [Fact]476        public void TestDeleteDoc()477        {478            var docID = "doc1";479            using (var doc = GenerateDocument(docID)) {480                Db.Delete(doc);481                Db.Count.Should().Be(0UL, "because the only document was deleted");482            }483            var gotDoc = Db.GetDocument(docID);484            gotDoc.Should().BeNull("because the document was deleted");485        }486        [Fact]487        public void TestDeleteDocInDifferentDBInstance()488        {489            var docID = "doc1";490            var doc = GenerateDocument(docID);491            using (var otherDB = OpenDB(Db.Name)) {492                otherDB.Count.Should()493                    .Be(1UL, "because the other database instance should reflect existing data");494                otherDB.Invoking(d => d.Delete(doc))495                    .Should().Throw<CouchbaseLiteException>()496                    .Where(497                        e => e.Error == CouchbaseLiteError.InvalidParameter &&498                             e.Domain == CouchbaseLiteErrorType.CouchbaseLite,499                        "because a document cannot be deleted from another database instance");500                otherDB.Count.Should().Be(1UL, "because the delete failed");501                Db.Count.Should().Be(1UL, "because the delete failed");502                doc.IsDeleted.Should().BeFalse("because the delete failed");503            }504        }505        [Fact]506        public void TestDeleteDocInDifferentDB()507        {508            Database.Delete("otherDB", Directory);509            var docID = "doc1";510            var doc = GenerateDocument(docID);511            using (var otherDB = OpenDB("otherDB")) {512                otherDB.Count.Should()513                    .Be(0UL, "because the other database should be empty");514                otherDB.Invoking(d => d.Delete(doc))515                    .Should().Throw<CouchbaseLiteException>()516                    .Where(517                        e => e.Error == CouchbaseLiteError.InvalidParameter &&518                             e.Domain == CouchbaseLiteErrorType.CouchbaseLite,519                        "because a document cannot be deleted from another database");520                otherDB.Count.Should().Be(0UL, "because the database is still empty");521                Db.Count.Should().Be(1UL, "because the delete failed");522                doc.IsDeleted.Should().BeFalse("because the delete failed");523                otherDB.Delete();524            }525        }526        [Fact]527        public void TestDeleteDocInBatch()528        {529            CreateDocs(10);530            Db.InBatch(() =>531            {532                for (int i = 0; i < 10; i++) {533                    var docID = $"doc_{i:D3}";534                    var doc = Db.GetDocument(docID);535                    Db.Delete(doc);536                    Db.Count.Should().Be(9UL - (ulong)i, "because the document count should be accurate after deletion");537                }538            });539            Db.Count.Should().Be(0, "because all documents were deleted");540        }541        [Fact]542        public void TestDeleteDocOnClosedDB()543        {544            var doc = GenerateDocument("doc1");545            Db.Close();546            Db.Invoking(d => d.Delete(doc))547                .Should().Throw<InvalidOperationException>()548                .WithMessage("Attempt to perform an operation on a closed database.",549                    "because this operation is invalid");550        }551        [Fact]552        public void TestDeleteDocOnDeletedDB()553        {554            var doc = GenerateDocument("doc1");555            DeleteDB(Db);556            Db.Invoking(d => d.Delete(doc))557                .Should().Throw<InvalidOperationException>()558                .WithMessage("Attempt to perform an operation on a closed database.",559                    "because this operation is invalid");560        }561        [Fact]562        public void TestPurgePreSaveDoc()563        {564            var doc = new MutableDocument("doc1");565            doc.SetInt("key", 1);566            Db.Invoking(db => db.Purge(doc)).Should().Throw<CouchbaseLiteException>()567                .Where(e => e.Error == CouchbaseLiteError.NotFound);568            Db.Count.Should().Be(0UL, "because the database should still be empty");569        }570        [Fact]571        public void TestPurgeDoc()572        {573            var doc = GenerateDocument("doc1");574            PurgeDocAndVerify(doc);575            Db.Count.Should().Be(0UL, "because the only document was purged");576        }577        [Fact]578        public void TestPurgeDocInDifferentDBInstance()579        {580            var docID = "doc1";581            var doc = GenerateDocument(docID);582            using (var otherDB = OpenDB(Db.Name)) {583                otherDB.Count.Should()584                    .Be(1UL, "because the other database instance should reflect existing data");585                otherDB.Invoking(d => d.Purge(doc))586                    .Should().Throw<CouchbaseLiteException>()587                    .Where(588                        e => e.Error == CouchbaseLiteError.InvalidParameter &&589                             e.Domain == CouchbaseLiteErrorType.CouchbaseLite, "because a document cannot be purged from another database instance");590                otherDB.Count.Should().Be(1UL, "because the delete failed");591                Db.Count.Should().Be(1UL, "because the delete failed");592                doc.IsDeleted.Should().BeFalse("because the delete failed");593            }594        }595        [Fact]596        public void TestPurgeDocInDifferentDB()597        {598            var docID = "doc1";599            var doc = GenerateDocument(docID);600            Database.Delete("otherDB", Directory);601            using (var otherDB = OpenDB("otherDB")) {602                otherDB.Count.Should()603                    .Be(0UL, "because the other database should be empty");604                otherDB.Invoking(d => d.Purge(doc))605                    .Should().Throw<CouchbaseLiteException>()606                    .Where(607                        e => e.Error == CouchbaseLiteError.InvalidParameter &&608                             e.Domain == CouchbaseLiteErrorType.CouchbaseLite, "because a document cannot be purged from another database");609                otherDB.Count.Should().Be(0UL, "because the database is still empty");610                Db.Count.Should().Be(1UL, "because the delete failed");611                doc.IsDeleted.Should().BeFalse("because the delete failed");612                otherDB.Delete();613            }614        }615        [Fact]616        public void TestPurgeSameDocTwice()617        {618            var docID = "doc1";619            var doc = GenerateDocument(docID);620            var doc1 = Db.GetDocument(docID);621            doc1.Should().NotBeNull("because the document was just created and it should exist");622            PurgeDocAndVerify(doc);623            Db.Count.Should().Be(0UL, "because the only document was purged");624            // Second purge and throw error625            Db.Invoking(db => db.Purge(doc)).Should().Throw<CouchbaseLiteException>().Where(e =>626                e.Error == CouchbaseLiteError.NotFound && e.Domain == CouchbaseLiteErrorType.CouchbaseLite);627        }628        [Fact]629        public void TestPurgeDocInBatch()630        {631            CreateDocs(10);632            Db.InBatch(() =>633            {634                for (int i = 0; i < 10; i++) {635                    var docID = $"doc_{i:D3}";636                    var doc = Db.GetDocument(docID);637                    PurgeDocAndVerify(doc);638                    Db.Count.Should().Be(9UL - (ulong)i, "because the document count should be accurate after deletion");639                }640            });641            Db.Count.Should().Be(0, "because all documents were purged");642        }643        [Fact]644        public void TestPurgeDocOnClosedDB()645        {646            var doc = GenerateDocument("doc1");647            Db.Close();648            Db.Invoking(d => d.Purge(doc))649                .Should().Throw<InvalidOperationException>()650                .WithMessage("Attempt to perform an operation on a closed database.",651                    "because this operation is invalid");652        }653        [Fact]654        public void TestPurgeDocOnDeletedDB()655        {656            var doc = GenerateDocument("doc1");657            DeleteDB(Db);658            Db.Invoking(d => d.Purge(doc))659                .Should().Throw<InvalidOperationException>()660                .WithMessage("Attempt to perform an operation on a closed database.",661                    "because this operation is invalid");662        }663        [Fact]664        public void TestClose()665        {666            Thread.Sleep(1500);667            Db.Close();668        }669        [Fact]670        public void TestCloseTwice()671        {672            Db.Close();673            Db.Close();674        }675        [Fact]676        public void TestCloseThenAccessDoc()677        {678            var docID = "doc1";679            var doc = GenerateDocument(docID);680            Db.Close();681            doc.Id.Should().Be(docID, "because a document's ID should never change");682            doc.GetInt("key").Should().Be(1, "because the document's data should still be accessible");683            // Modification should still succeed684            var updatedDoc = doc.ToMutable();685            updatedDoc.SetInt("key", 2);686            updatedDoc.SetString("key1", "value");687        }688        [Fact]689        public void TestCloseThenAccessBlob()690        {691            using (var doc = GenerateDocument("doc1")) {692                var savedDoc = StoreBlob(Db, doc, Encoding.UTF8.GetBytes("12345"));693                Db.Close();694                var blob = savedDoc.GetBlob("data");695                blob.Should().NotBeNull("because the blob should still exist and be accessible");696                blob.Length.Should().Be(5, "because the blob's metadata should still be accessible");697                blob.Content.Should().BeNull("because the content cannot be read from a closed database");698            }699        }700        [Fact]701        public void TestCloseThenGetDatabaseName()702        {703            var name = Db.Name;704            Db.Close();705            Db.Name.Should().Be(name, "because the name of the database should still be accessible");706        }707        [Fact]708        public void TestCloseThenGetDatabasePath()709        {710            Db.Close();711            Db.Path.Should().BeNull("because a non-open database has no path");712        }713        [Fact]714        public void TestCloseThenDeleteDatabase()715        {716            Db.Dispose();717            Db.Invoking(DeleteDB).Should().Throw<InvalidOperationException>();718        }719        [Fact]720        public void TestCloseThenCallInBatch()721        {722            Db.Invoking(d => d.InBatch(() =>723            {724                Db.Close();725            }))726            .Should().Throw<CouchbaseLiteException>()727            .Where(728                e => e.Error == CouchbaseLiteError.TransactionNotClosed && e.Domain == CouchbaseLiteErrorType.CouchbaseLite,729                "because a database can't be closed in the middle of a batch");730        }731        [Fact]732        public void TestDelete()733        {734            DeleteDB(Db);735        }736        [Fact]737        public void TestDeleteTwice()738        {739            Db.Delete();740            Db.Invoking(d => d.Delete()).Should().Throw<InvalidOperationException>();741        }742        [Fact]743        public void TestDeleteThenAccessDoc()744        {745            var docID = "doc1";746            var doc = GenerateDocument(docID);747            DeleteDB(Db);748            doc.Id.Should().Be(docID, "because a document's ID should never change");749            doc.GetInt("key").Should().Be(1, "because the document's data should still be accessible");750            // Modification should still succeed751            var updatedDoc = doc.ToMutable();752            updatedDoc.SetInt("key", 2);753            updatedDoc.SetString("key1", "value");754        }755        [Fact]756        public void TestDeleteThenAccessBlob()757        {758            var doc = GenerateDocument("doc1").ToMutable();759            var savedDoc = StoreBlob(Db, doc, Encoding.UTF8.GetBytes("12345"));760            DeleteDB(Db);761            var blob = savedDoc.GetBlob("data");762            blob.Should().NotBeNull("because the blob should still exist and be accessible");763            blob.Length.Should().Be(5, "because the blob's metadata should still be accessible");764            blob.Content.Should().BeNull("because the content cannot be read from a closed database");765        }766        [Fact]767        public void TestDeleteThenGetDatabaseName()768        {769            var name = Db.Name;770            DeleteDB(Db);771            Db.Name.Should().Be(name, "because the name of the database should still be accessible");772        }773        [Fact]774        public void TestDeleteThenGetDatabasePath()775        {776            DeleteDB(Db);777            Db.Path.Should().BeNull("because a non-open database has no path");778        }779        [Fact]780        public void TestDeleteThenCallInBatch()781        {782            Db.Invoking(d => d.InBatch(() =>783            {784                Db.Delete();785            }))786            .Should().Throw<CouchbaseLiteException>()787            .Where(788                e => e.Error == CouchbaseLiteError.TransactionNotClosed && e.Domain == CouchbaseLiteErrorType.CouchbaseLite,789                "because a database can't be closed in the middle of a batch");790        }791        [Fact]792        public void TestDeleteDBOpenByOtherInstance()793        {794            using (var otherDB = OpenDB(Db.Name)) {795                Db.Invoking(d => d.Delete())796                    .Should().Throw<CouchbaseLiteException>()797                    .Where(e => e.Error == CouchbaseLiteError.Busy &&798                                         e.Domain == CouchbaseLiteErrorType.CouchbaseLite,799                        "because an in-use database cannot be deleted");800            }801        }802        803        [Fact]804        public void TestDeleteWithDefaultDirDB()805        {806            string path;807            using (var db = new Database("db")) {808                path = db.Path;809                path.Should().NotBeNull();810            }811            Database.Delete("db", null);812            System.IO.Directory.Exists(path).Should().BeFalse();813        }814        [Fact]815        public void TestDeleteOpeningDBWithDefaultDir()816        {817            using (var db = new Database("db")) {818                Action a = () =>819                {820                    Database.Delete("db", null);821                };822                a.Should().Throw<CouchbaseLiteException>().Where(e =>823                    e.Error == CouchbaseLiteError.Busy && e.Domain == CouchbaseLiteErrorType.CouchbaseLite);824            }825        }826        [Fact]827        public void TestDeleteByStaticMethod()828        {829            var dir = Directory;830            var options = new DatabaseConfiguration831            {832                Directory = dir833            };834            string path = null;835            using (var db = new Database("db", options)) {836                path = db.Path;837            }838            Database.Delete("db", dir);839            System.IO.Directory.Exists(path).Should().BeFalse("because the database was deleted");840        }841        [Fact]842        public void TestDeleteOpeningDBByStaticMethod()843        {844            var dir = Directory;845            var options = new DatabaseConfiguration846            {847                Directory = dir848            };849            using (var db = new Database("db", options)) {850                CouchbaseLiteException e = null;851                try {852                    Database.Delete("db", dir);853                } catch (CouchbaseLiteException ex) {854                    e = ex;855                    ex.Error.Should().Be(CouchbaseLiteError.Busy, "because an in-use database cannot be deleted");856                    ex.Domain.Should().Be(CouchbaseLiteErrorType.CouchbaseLite, "because this is a LiteCore error");857                }858                e.Should().NotBeNull("because an exception is expected");859            }860        }861        [Fact]862        public void TestDeleteNonExistingDBWithDefaultDir()863        {864            // Expect no-op865            Database.Delete("notexistdb", null);866        }867        [Fact]868        public void TestDeleteNonExistingDB()869        {870            // Expect no-op871            Database.Delete("notexistdb", Directory);872        }873        [Fact]874        public void TestDatabaseExistsWithDefaultDir()875        {876            Database.Delete("db", null);877            Database.Exists("db", null).Should().BeFalse();878            using (var db = new Database("db")) {879                Database.Exists("db", null).Should().BeTrue();880                DeleteDB(db);881            }882            Database.Exists("db", null).Should().BeFalse();883        }884        [Fact]885        public void TestDatabaseExistsWithDir()886        {887            var dir = Directory;888            Database.Delete("db", dir);889            Database.Exists("db", dir).Should().BeFalse("because this database has not been created");890            var options = new DatabaseConfiguration891            {892                Directory = dir893            };894            string path = null;895            using (var db = new Database("db", options)) {896                path = db.Path;897                Database.Exists("db", dir).Should().BeTrue("because the database is now created");898            }899            Database.Exists("db", dir).Should().BeTrue("because the database still exists after close");900            Database.Delete("db", dir);901            System.IO.Directory.Exists(path).Should().BeFalse("because the database was deleted");902            Database.Exists("db", dir).Should().BeFalse("because the database was deleted");903        }904        [Fact]905        public void TestDatabaseExistsAgainstNonExistDBWithDefaultDir()906        {907            Database.Exists("nonexist", null).Should().BeFalse("because that DB does not exist");908        }909        [Fact]910        public void TestDatabaseExistsAgainstNonExistDB()911        {912            Database.Exists("nonexist", Directory).Should().BeFalse("because that DB does not exist");913        }914        [Fact]915        public void TestCompact()916        {917            var docs = CreateDocs(20);918            Db.InBatch(() =>919            {920                foreach (var doc in docs) {921                    var docToUse = doc;922                    for (int i = 0; i < 25; i++) {923                        var mDoc = docToUse.ToMutable();924                        mDoc.SetInt("number", i);925                        SaveDocument(mDoc);926                    };927                }928            });929            930            foreach (var doc in docs) {931                var content = Encoding.UTF8.GetBytes(doc.Id);932                var blob = new Blob("text/plain", content);933                var mDoc = doc.ToMutable();934                mDoc.SetBlob("blob", blob);935                SaveDocument(mDoc);936            }937            Db.Count.Should().Be(20, "because that is the number of documents that were added");938            var attsDir = new DirectoryInfo(Path.Combine(Db.Path, "Attachments"));939            var atts = attsDir.EnumerateFiles();940            atts.Should().HaveCount(20, "because there should be one blob per document");941            Db.PerformMaintenance(MaintenanceType.Compact);942            foreach (var doc in docs) {943                var savedDoc = Db.GetDocument(doc.Id);944                Db.Delete(savedDoc);945                Db.GetDocument(savedDoc.Id).Should().BeNull("because the document was just deleted");946            }947            Db.Count.Should().Be(0, "because all documents were deleted");948            Db.PerformMaintenance(MaintenanceType.Compact);949            atts = attsDir.EnumerateFiles();950            atts.Should().BeEmpty("because the blobs should be collected by the compaction");951        }952        [Fact]953        public void TestPerformMaintenanceCompact()954        {955            var docs = CreateDocs(20);956            Db.InBatch(() =>957            {958                foreach (var doc in docs) {959                    var docToUse = doc;960                    for (int i = 0; i < 25; i++) {961                        var mDoc = docToUse.ToMutable();962                        mDoc.SetInt("number", i);963                        SaveDocument(mDoc);964                    };965                }966            });967            foreach (var doc in docs) {968                var content = Encoding.UTF8.GetBytes(doc.Id);969                var blob = new Blob("text/plain", content);970                var mDoc = doc.ToMutable();971                mDoc.SetBlob("blob", blob);972                SaveDocument(mDoc);973            }974            Db.Count.Should().Be(20, "because that is the number of documents that were added");975            var attsDir = new DirectoryInfo(Path.Combine(Db.Path, "Attachments"));976            var atts = attsDir.EnumerateFiles();977            atts.Should().HaveCount(20, "because there should be one blob per document");978            Db.PerformMaintenance(MaintenanceType.Compact);979            foreach (var doc in docs) {980                var savedDoc = Db.GetDocument(doc.Id);981                Db.Delete(savedDoc);982                Db.GetDocument(savedDoc.Id).Should().BeNull("because the document was just deleted");983            }984            Db.Count.Should().Be(0, "because all documents were deleted");985            Db.PerformMaintenance(MaintenanceType.Compact);986            atts = attsDir.EnumerateFiles();987            atts.Should().BeEmpty("because the blobs should be collected by the compaction");988        }989        [Fact]990        public void TestPerformMaintenanceReindex()991        {992            var docs = CreateDocs(20);993            // Reindex when there is no index994            Db.PerformMaintenance(MaintenanceType.Reindex);995            //Create an index996            var key = Expression.Property("key");997            var keyItem = ValueIndexItem.Expression(key);998            var keyIndex = IndexBuilder.ValueIndex(keyItem);999            Db.CreateIndex("KeyIndex", keyIndex);1000            Db.GetIndexes().Count.Should().Be(1);1001            var q = QueryBuilder.Select(SelectResult.Expression(key))1002                .From(DataSource.Database(Db))1003                .Where(key.GreaterThan(Expression.Int(9)));1004            q.Explain().Contains("USING INDEX KeyIndex").Should().BeTrue();1005            //Reindex1006            Db.PerformMaintenance(MaintenanceType.Reindex);1007            //Check if the index is still there and used1008            Db.GetIndexes().Count.Should().Be(1);1009            q.Explain().Contains("USING INDEX KeyIndex").Should().BeTrue();1010        }1011        [Fact]1012        public void TestPerformMaintenanceIntegrityCheck()1013        {1014            var docs = CreateDocs(20);1015            // Update each doc 25 times1016            Db.InBatch(() =>1017            {1018                foreach (var doc in docs) {1019                    var docToUse = doc;1020                    for (int i = 0; i < 25; i++) {1021                        var mDoc = docToUse.ToMutable();1022                        mDoc.SetInt("number", i);1023                        SaveDocument(mDoc);1024                    };1025                }1026            });1027            // Add each doc with a blob object1028            foreach (var doc in docs) {1029                var content = Encoding.UTF8.GetBytes(doc.Id);1030                var blob = new Blob("text/plain", content);1031                var mDoc = doc.ToMutable();1032                mDoc.SetBlob("blob", blob);1033                SaveDocument(mDoc);1034            }1035            Db.Count.Should().Be(20, "because that is the number of documents that were added");1036            // Integrity Check1037            Db.PerformMaintenance(MaintenanceType.IntegrityCheck);1038            foreach (var doc in docs) {1039                Db.Delete(doc);1040            }1041            Db.Count.Should().Be(0);1042            // Integrity Check1043            Db.PerformMaintenance(MaintenanceType.IntegrityCheck);1044        }1045        [Fact]1046        public void TestCreateConfiguration()1047        {1048            var builder1 = new DatabaseConfiguration();1049            var config1 = builder1;1050            config1.Directory.Should().NotBeNullOrEmpty("because the directory should have a default value");1051#if COUCHBASE_ENTERPRISE1052            config1.EncryptionKey.Should().BeNull("because it was not set");1053#endif1054            var builder2 = new DatabaseConfiguration()1055            {1056                Directory = "/tmp/mydb"1057            };1058            #if COUCHBASE_ENTERPRISE1059            var key = new EncryptionKey("key");1060            builder2.EncryptionKey = key;1061            #endif1062            var config2 = builder2;1063            config2.Directory.Should().Be("/tmp/mydb", "because that is what was set");1064            #if COUCHBASE_ENTERPRISE1065            config2.EncryptionKey.Should().Be(key, "because that is what was set");1066            #endif1067        }1068        [Fact]1069        public void TestGetSetConfiguration()1070        {1071            var config = new DatabaseConfiguration();1072            using (var db = new Database("db", config))1073            {1074                db.Config.Should().NotBeSameAs(config, "because the configuration should be copied and frozen");1075                db.Config.Directory.Should().Be(config.Directory, "because the directory should be the same");1076                #if COUCHBASE_ENTERPRISE1077                db.Config.EncryptionKey.Should().Be(config.EncryptionKey,1078                    "because the encryption key should be the same");1079                #endif1080            }1081        }1082        [Fact]1083        public void TestCopy()1084        {1085            for (int i = 0; i < 10; i++) {1086                var docID = $"doc{i}";1087                using (var doc = new MutableDocument(docID)) {1088                    doc.SetString("name", docID);1089                    var data = Encoding.UTF8.GetBytes(docID);1090                    var blob = new Blob("text/plain", data);1091                    doc.SetBlob("data", blob);1092                    Db.Save(doc);1093                }1094            }1095            var dbName = "nudb";1096            var config = Db.Config;1097            var dir = config.Directory;1098            Database.Delete(dbName, dir);1099            Database.Copy(Db.Path, dbName, config);1100            Database.Exists(dbName, dir).Should().BeTrue();1101            using (var nudb = new Database(dbName, config)) {1102                nudb.Count.Should().Be(10, "because it is a copy of another database with 10 items");1103                var DOCID = Meta.ID;1104                var S_DOCID = SelectResult.Expression(DOCID);1105                using (var q = QueryBuilder.Select(S_DOCID).From(DataSource.Database(nudb))) {1106                    var rs = q.Execute();1107                    foreach (var r in rs) {1108                        var docID = r.GetString(0);1109                        docID.Should().NotBeNull();1110                        var doc = nudb.GetDocument(docID);1111                        doc.Should().NotBeNull();1112                        doc.GetString("name").Should().Be(docID);1113                        var blob = doc.GetBlob("data");1114                        blob.Should().NotBeNull();1115                        var data = Encoding.UTF8.GetString(blob.Content);1116                        data.Should().Be(docID);1117                    }1118                }1119            }1120            Database.Delete(dbName, dir);1121        }1122        [Fact]1123        public void TestCreateN1QLQueryIndex()1124        {1125            Db.GetIndexes().Should().BeEmpty();1126            var index1 = new ValueIndexConfiguration(new string[] { "firstName", "lastName" });1127            Db.CreateIndex("index1", index1);1128            var index2 = new FullTextIndexConfiguration("detail");1129            Db.CreateIndex("index2", index2);1130            // '-' in "es-detail" caused Couchbase.Lite.CouchbaseLiteException : CouchbaseLiteException (LiteCoreDomain / 23): Invalid N1QL in index expression.1131            // Basically '-' is the minus sign in N1QL expression. So needs to escape the expression string.1132            // But I just couldn't get it to work...1133            // var index3 = new FullTextIndexConfiguration(new string[]{ "es"+@"\-"+"detail" }, true, "es");1134            var index3 = new FullTextIndexConfiguration(new string[] { "es_detail" }, true, "es");1135            Db.CreateIndex("index3", index3);1136            Db.GetIndexes().Should().BeEquivalentTo(new[] { "index1", "index2", "index3" });1137        }1138        [Fact]1139        public void TestCreateIndex()1140        {1141            Db.GetIndexes().Should().BeEmpty();1142            var fName = Expression.Property("firstName");1143            var lName = Expression.Property("lastName");1144            var fNameItem = ValueIndexItem.Property("firstName");1145            var lNameItem = ValueIndexItem.Expression(lName);1146            var index1 = IndexBuilder.ValueIndex(fNameItem, lNameItem);1147            Db.CreateIndex("index1", index1);1148            var detailItem = FullTextIndexItem.Property("detail");1149            var index2 = IndexBuilder.FullTextIndex(detailItem);1150            Db.CreateIndex("index2", index2);1151            var detailItem2 = FullTextIndexItem.Property("es-detail");1152            var index3 = IndexBuilder.FullTextIndex(detailItem2).IgnoreAccents(true).SetLanguage("es");1153            Db.CreateIndex("index3", index3);1154            Db.GetIndexes().Should().BeEquivalentTo(new[] { "index1", "index2", "index3" });1155        }1156        [Fact]1157        public void TestCreateSameIndexTwice()1158        {1159            var item = ValueIndexItem.Expression(Expression.Property("firstName"));1160            var index = IndexBuilder.ValueIndex(item);1161            Db.CreateIndex("myindex", index);1162            Db.CreateIndex("myindex", index);1163            Db.GetIndexes().Should().BeEquivalentTo(new[] {"myindex"});1164        }1165        [Fact]1166        public void TestCreateSameNameIndexes()1167        {1168            var fName = Expression.Property("firstName");1169            var lName = Expression.Property("lastName");1170            var fNameItem = ValueIndexItem.Expression(fName);1171            var fNameIndex = IndexBuilder.ValueIndex(fNameItem);1172            Db.CreateIndex("myindex", fNameIndex);1173            var lNameItem = ValueIndexItem.Expression(lName);1174            var lNameIndex = IndexBuilder.ValueIndex(lNameItem);1175            Db.CreateIndex("myindex", lNameIndex);1176            Db.GetIndexes().Should().BeEquivalentTo(new[] {"myindex"}, "because lNameIndex should overwrite fNameIndex");1177            var detailItem = FullTextIndexItem.Property("detail");1178            var detailIndex = IndexBuilder.FullTextIndex(detailItem);1179            Db.CreateIndex("myindex", detailIndex);1180            Db.GetIndexes().Should().BeEquivalentTo(new[] { "myindex" }, "because detailIndex should overwrite lNameIndex");1181        }1182        [Fact]1183        public void TestDeleteIndex()1184        {1185            TestCreateIndex();1186            Db.DeleteIndex("index1");1187            Db.GetIndexes().Should().BeEquivalentTo(new[] {"index2", "index3"});1188            Db.DeleteIndex("index2");1189            Db.GetIndexes().Should().BeEquivalentTo(new[] { "index3" });1190            Db.DeleteIndex("index3");1191            Db.GetIndexes().Should().BeEmpty();1192            Db.DeleteIndex("dummy");1193            Db.DeleteIndex("index1");1194            Db.DeleteIndex("index2");1195            Db.DeleteIndex("index3");1196        }1197        [Fact]1198        public void TestGetDocFromDeletedDB()1199        {1200            using(var doc = GenerateDocument("doc1")) {1201                Db.Delete();1202                Db.Invoking(d => d.GetDocument("doc1"))1203                    .Should().Throw<InvalidOperationException>()1204                    .WithMessage("Attempt to perform an operation on a closed database.",1205                        "because this operation is invalid");1206            }1207        }1208        [Fact]1209        public void TestCloseWithActiveLiveQueries()1210        {1211            WithActiveLiveQueries(true);1212        }1213        [Fact]1214        public void TestDeleteWithActiveLiveQueries()1215        {1216            WithActiveLiveQueries(false);1217        }1218        [ForIssue("couchbase-lite-android/1231")]1219        [Fact]1220        public void TestOverwriteDocWithNewDocInstance()1221        {1222            using (var mDoc1 = new MutableDocument("abc"))1223            using (var mDoc2 = new MutableDocument("abc")) {1224                mDoc1.SetString("somekey", "someVar");1225                mDoc2.SetString("somekey", "newVar");1226                // This causes a conflict, the default conflict resolver should be applied1227                Db.Save(mDoc1);1228                Db.Save(mDoc2);1229                // NOTE: Both doc1 and doc2 are generation 1.  Last write should win.1230                Db.Count.Should().Be(1UL);1231                using (var doc = Db.GetDocument("abc")) {1232                    doc.Should().NotBeNull();1233                    doc.GetString("somekey").Should().Be("newVar", "because the last write should win");1234                }  1235            }1236        }1237        [ForIssue("couchbase-lite-android/1416")]1238        [Fact]1239        public void TestDeleteAndOpenDB()1240        {1241            using (var database1 = new Database("application")) {1242                database1.Delete();1243                using (var database2 = new Database("application")) {1244                    database2.InBatch(() =>1245                    {1246                        for (var i = 0; i < 100; i++) {1247                            using (var doc = new MutableDocument()) {1248                                doc.SetInt("index", i);1249                                for (var j = 0; j < 10; j++) {1250                                    doc.SetInt($"item_{j}", j);1251                                }1252                                database2.Save(doc);1253                            }1254                        }1255                    });1256                }1257            }1258        }1259        [Fact]1260        public void TestDatabaseSaveAndGetCookies()1261        {1262            var uri = new Uri("http://example.com/");1263            var cookieStr = "id=a3fWa; Domain=.example.com; Secure; HttpOnly";1264            Db.SaveCookie(cookieStr, uri);1265            Db.GetCookies(uri).Should().Be("id=a3fWa");1266            cookieStr = "id=a3fWa; Domain=www.example.com; Secure; HttpOnly";1267            Db.SaveCookie(cookieStr, uri);1268            Db.GetCookies(uri).Should().Be("id=a3fWa");1269            uri = new Uri("http://www.example.com/");1270            cookieStr = "id=a3fWa; Domain=.example.com; Secure; HttpOnly";1271            //No longer throw exception. Will log warning messages.1272            //Action badAction = (() => Db.SaveCookie(cookieStr, uri));1273            //badAction.Should().Throw<CouchbaseLiteException>(); //CouchbaseLiteException (LiteCoreDomain / 9): Invalid cookie.1274            cookieStr = "id=a3fWa; Domain=www.example.com; Secure; HttpOnly";1275            Db.SaveCookie(cookieStr, uri);1276            Db.GetCookies(uri).Should().Be("id=a3fWa; id=a3fWa");1277            uri = new Uri("http://exampletest.com/");1278            cookieStr = "id=a3fWa; Expires=Wed, 20 Oct 2100 05:54:52 GMT; Secure; HttpOnly";1279            Db.SaveCookie(cookieStr, uri);1280            Db.GetCookies(uri).Should().Be("id=a3fWa");1281            cookieStr = "id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly";1282            Db.SaveCookie(cookieStr, uri);1283            Db.GetCookies(uri).Should().BeNull("cookie is expired");1284        }1285        private void WithActiveLiveQueries(bool isCloseNotDelete)1286        {1287            Database.Delete("closeDB", Db.Config.Directory);1288            using (var otherDb = new Database("closeDB", Db.Config)) {1289                var query = QueryBuilder.Select(SelectResult.Expression(Meta.ID)).From(DataSource.Database(otherDb));1290                var query1 = QueryBuilder.Select(SelectResult.Expression(Meta.ID)).From(DataSource.Database(otherDb));1291                var doc1Listener = new WaitAssert();1292                var token = query.AddChangeListener(null, (sender, args) => {1293                    foreach (var row in args.Results) {1294                        if (row.GetString("id") == "doc1") {1295                            doc1Listener.Fulfill();1296                        }1297                    }1298                });1299                var doc1Listener1 = new WaitAssert();1300                var token1 = query1.AddChangeListener(null, (sender, args) => {1301                    foreach (var row in args.Results) {1302                        if (row.GetString("id") == "doc1") {1303                            doc1Listener1.Fulfill();1304                        }1305                    }1306                });1307                using (var doc = new MutableDocument("doc1")) {1308                    doc.SetString("value", "string");1309                    otherDb.Save(doc); // Should still trigger since it is pointing to the same DB1310                }1311                otherDb.ActiveStoppables.Count.Should().Be(2);1312                doc1Listener.WaitForResult(TimeSpan.FromSeconds(20));1313                doc1Listener1.WaitForResult(TimeSpan.FromSeconds(20));1314                if (isCloseNotDelete)1315                    otherDb.Close();1316                else1317                    otherDb.Delete();1318                otherDb.ActiveStoppables.Count.Should().Be(0);1319                otherDb.IsClosedLocked.Should().Be(true);1320            }1321            Database.Delete("closeDB", Db.Config.Directory);1322        }1323        private bool ResolveConflict(MutableDocument updatedDoc, Document currentDoc)1324        {1325            var updateDocDict = updatedDoc.ToDictionary();1326            var curDocDict = currentDoc.ToDictionary();1327            foreach (var value in curDocDict)1328                if (updateDocDict.ContainsKey(value.Key) && !value.Value.Equals(updateDocDict[value.Key]))1329                    updateDocDict[value.Key] = value.Value + ", " + updateDocDict[value.Key];1330                else if (!updateDocDict.ContainsKey(value.Key))1331                    updateDocDict.Add(value.Key, value.Value);1332            updatedDoc.SetData(updateDocDict);1333            return true;1334        }1335        private void DeleteDB(Database db)1336        {1337            var path = db.Path;1338            if (path != null) {1339                System.IO.Directory.Exists(path).Should()1340                    .BeTrue("because the database should exist if it is going to be deleted");1341            }1342            db.Delete();1343            if (path != null) {1344                System.IO.Directory.Exists(path).Should().BeFalse("because the database should not exist anymore");1345            }1346        }1347        private MutableDocument GenerateDocument(string docID)1348        {1349            var doc = new MutableDocument(docID);1350            doc.SetInt("key", 1);1351            Db.Save(doc);1352            Db.Count.Should().Be(1UL, "because this is the first document");1353            doc.Sequence.Should().Be(1UL, "because this is the first document");1354            return doc;1355        }1356        private void VerifyGetDocument(string docID)1357        {1358            VerifyGetDocument(docID, 1);1359        }1360        private void VerifyGetDocument(string docID, int value)1361        {1362            VerifyGetDocument(Db, docID, value);1363        }1364        private void VerifyGetDocument(Database db, string docID)1365        {1366            VerifyGetDocument(db, docID, 1);1367        }1368        private void VerifyGetDocument(Database db, string docID, int value)1369        {1370            var doc = Db.GetDocument(docID);1371            doc.Id.Should().Be(docID, "because that was the requested ID");1372            doc.IsDeleted.Should().BeFalse("because the test uses a non-deleted document");1373            doc.GetInt("key").Should().Be(value, "because that is the value that was passed as expected");1374        }1375        private IList<Document> CreateDocs(int n)1376        {1377            var docs = new List<Document>();1378            for (int i = 0; i < n; i++) {1379                var doc = new MutableDocument($"doc_{i:D3}");1380                doc.SetInt("key", i);1381                Db.Save(doc);1382                docs.Add(doc);1383            }1384            Db.Count.Should().Be((ulong)n, "because otherwise an incorrect number of documents were made");1385            return docs;1386        }1387        private void ValidateDocs(int n)1388        {1389            for (int i = 0; i < n; i++) {1390                VerifyGetDocument($"doc_{i:D3}", i);1391            }1392        }1393        private void TestSaveNewDoc(string docID)1394        {1395            GenerateDocument(docID);1396            Db.Count.Should().Be(1UL, "because the database only has one document");1397            VerifyGetDocument(docID);1398        }1399        private void PurgeDocAndVerify(Document doc)1400        {1401            var docID = doc.Id;1402            Db.Purge(doc);1403            Db.GetDocument(docID).Should().BeNull("because it no longer exists");1404        }1405        private Document StoreBlob(Database db, MutableDocument doc, byte[] content)1406        {1407            var blob = new Blob("text/plain", content);1408            doc.SetBlob("data", blob);1409            Db.Save(doc);1410            return Db.GetDocument(doc.Id);1411        }1412    }1413}...

Full Screen

Full Screen

EqualConstraintTests.cs

Source:EqualConstraintTests.cs Github

copy

Full Screen

...565        {566            var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(0, new System.IntPtr(0)));567            Assert.AreEqual(ex.Message, "  Expected: 0 (Int32)"+ NL + "  But was:  0 (IntPtr)"+ NL);568        }569        class Dummy570        {571            internal readonly int value;572            public Dummy(int value)573            {574                this.value = value;575            }576            public override string ToString()577            {578                return "Dummy " + value;579            }580        }581        class Dummy1582        {583            internal readonly int value;584            public Dummy1(int value)585            {586                this.value = value;587            }588            public override string ToString()589            {590                return "Dummy " + value;591            }592        }593        class DummyGenericClass<T>594        {595            private object _obj;596            public DummyGenericClass(object obj)597            {598                _obj = obj;599            }600            public override string ToString()601            {602                return _obj.ToString();603            }604        }605        [Test]606        public void TestSameValueDifferentTypeUsingGenericTypes()607        {608            var d1 = new Dummy(12);609            var d2 = new Dummy1(12);610            var dc1 = new DummyGenericClass<Dummy>(d1);611            var dc2 = new DummyGenericClass<Dummy1>(d2);612            var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(dc1, dc2));613            var expectedMsg =614                "  Expected: <Dummy 12> (EqualConstraintTests+DummyGenericClass`1[EqualConstraintTests+Dummy])" + Environment.NewLine +615                "  But was:  <Dummy 12> (EqualConstraintTests+DummyGenericClass`1[EqualConstraintTests+Dummy1])" + Environment.NewLine;616            Assert.AreEqual(expectedMsg, ex.Message);617        }618        [Test]619        public void SameValueAndTypeButDifferentReferenceShowNotShowTypeDifference()620        {621            var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(Is.Zero, Is.Zero));622            Assert.AreEqual(ex.Message, "  Expected: <<equal 0>>"+ NL + "  But was:  <<equal 0>>"+ NL);623        }624        [Test, TestCaseSource("DifferentTypeSameValueTestData")]625        public void SameValueDifferentTypeRegexMatch(object expected, object actual)626        {627            var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(expected, actual));628            Assert.That(ex.Message, Does.Match(@"\s*Expected\s*:\s*.*\s*\(.+\)\r?\n\s*But\s*was\s*:\s*.*\s*\(.+\)"));629        }...

Full Screen

Full Screen

EntryPoints.cs

Source:EntryPoints.cs Github

copy

Full Screen

...6	public static class EntryPoints7	{8		[PortableEntryPoint("Stop all tests", -3000)]9		public static void StopAllTests() => ScriptingToolbox.PostLateTasks.StopByTag(RemoteScripting.ScriptsTasksTag);10		[PortableEntryPoint("Dummy test", -2000)]11		public static void DummyTest() => RunTest(new DummyTest());12		[PortableEntryPoint("Bounding Boxes Tool", -1000)]13		public static void BoundingBoxesTool() => RunTest(new BoundingBoxesTool());14		[PortableEntryPoint("Example Test")]15		public static void ExampleTest() => RunTest(new ExampleTest());16		private static void RunTest(Test test) => test.Run(RemoteScripting.ScriptsTasksTag);17	}18}...

Full Screen

Full Screen

ExampleTest.cs

Source:ExampleTest.cs Github

copy

Full Screen

1using NUnit.Framework;2namespace Test.Library3{4    public class ExampleTest5    {6        [Test]7        public void dummyTest()8        {9            Assert.True(true);10        }11    }12}...

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using ExampleTest;2{3    static void Main(string[] args)4    {5        Dummy d = new Dummy();6        d.Display();7    }8}9using ExampleTest;10{11    static void Main(string[] args)12    {13        Dummy d = new Dummy();14        d.Display();15    }16}17using ExampleTest;18{19    static void Main(string[] args)20    {21        Dummy d = new Dummy();22        d.Display();23    }24}25using ExampleTest;26{27    static void Main(string[] args)28    {29        Dummy d = new Dummy();30        d.Display();31    }32}33using ExampleTest;34{35    static void Main(string[] args)36    {37        Dummy d = new Dummy();38        d.Display();39    }40}41using ExampleTest;42{43    static void Main(string[] args)44    {45        Dummy d = new Dummy();46        d.Display();47    }48}49using ExampleTest;50{51    static void Main(string[] args)52    {53        Dummy d = new Dummy();54        d.Display();55    }56}57using ExampleTest;58{59    static void Main(string[] args)60    {61        Dummy d = new Dummy();62        d.Display();63    }64}65using ExampleTest;66{67    static void Main(string[] args)68    {69        Dummy d = new Dummy();70        d.Display();71    }72}73using ExampleTest;74{75    static void Main(string[] args)76    {77        Dummy d = new Dummy();78        d.Display();79    }80}

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using ExampleTest;2{3    {4        public static void Main(string[] args)5        {6            Dummy d = new Dummy();7            d.Print();8        }9    }10}11using ExampleTest;12{13    {14        public static void Main(string[] args)15        {16            Dummy d = new Dummy();17            d.Print();18        }19    }20}21{22    {23        public void Print()24        {25            System.Console.WriteLine("Dummy class of ExampleTest");26        }27    }28}29{30    {31        public static void Main(string[] args)32        {33            Dummy d = new Dummy();34            d.Print();35        }36    }37}38{39    {40        public static void Main(string[] args)41        {42            Dummy d = new Dummy();43            d.Print();44        }45    }46}

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using System;2using ExampleTest;3{4    {5        public static void Main(string[] args)6        {7            Console.WriteLine("Hello World!");8        }9    }10}

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using ExampleTest;2{3    public static void Main()4    {5        Dummy d = new Dummy();6        d.Print();7    }8}

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using ExampleTest;2{3    {4        static void Main(string[] args)5        {6            Dummy d = new Dummy();7            d.print();8        }9    }10}

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using ExampleTest;2{3    static void Main()4    {5        Dummy d = new Dummy();6        d.Show();7    }8}

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using ExampleTest;2using System;3{4    static void Main()5    {6        Dummy d = new Dummy();7        d.Print();8    }9}

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using ExampleTest;2{3    static void Main()4    {5        Dummy d = new Dummy();6        d.Display();7    }8}9using alias = namespace;10using ExampleTest = ExampleTest;11{12    static void Main()13    {14        ExampleTest.Dummy d = new ExampleTest.Dummy();15        d.Display();16    }17}18using static namespace;19using static ExampleTest.Dummy;20{21    static void Main()22    {23        Display();24    }25}

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using ExampleTest;2{3  static void Main()4  {5    Dummy d = new Dummy();6    d.Print();7  }8}9{10  {11    public void Print()12    {13      System.Console.WriteLine("Hello World");14    }15  }16}17using ExampleTest;18using D = ExampleTest.Dummy;19{20  static void Main()21  {22    D d = new D();23    d.Print();24  }25}26{27  {28    public void Print()29    {30      System.Console.WriteLine("Hello World");31    }32  }33}34using ExampleTest;35using D = ExampleTest.Dummy;36{37  static void Main()38  {39    D d = new D();40    d.Print();41  }42}43{44  {45    public void Print()46    {47      System.Console.WriteLine("Hello World");48    }49  }50}51using ExampleTest;52using D = ExampleTest.Dummy;53{54  static void Main()55  {56    D d = new D();57    d.Print();58  }59}60{61  {62    public void Print()63    {64      System.Console.WriteLine("Hello World");65    }66  }67}68using ExampleTest;69using D = ExampleTest.Dummy;70{71  static void Main()72  {73    D d = new D();74    d.Print();75  }76}

Full Screen

Full Screen

Nunit tutorial

Nunit is a well-known open-source unit testing framework for C#. This framework is easy to work with and user-friendly. LambdaTest’s NUnit Testing Tutorial provides a structured and detailed learning environment to help you leverage knowledge about the NUnit framework. The NUnit tutorial covers chapters from basics such as environment setup to annotations, assertions, Selenium WebDriver commands, and parallel execution using the NUnit framework.

Chapters

  1. NUnit Environment Setup - All the prerequisites and setup environments are provided to help you begin with NUnit testing.
  2. NUnit With Selenium - Learn how to use the NUnit framework with Selenium for automation testing and its installation.
  3. Selenium WebDriver Commands in NUnit - Leverage your knowledge about the top 28 Selenium WebDriver Commands in NUnit For Test Automation. It covers web browser commands, web element commands, and drop-down commands.
  4. NUnit Parameterized Unit Tests - Tests on varied combinations may lead to code duplication or redundancy. This chapter discusses how NUnit Parameterized Unit Tests and their methods can help avoid code duplication.
  5. NUnit Asserts - Learn about the usage of assertions in NUnit using Selenium
  6. NUnit Annotations - Learn how to use and execute NUnit annotations for Selenium Automation Testing
  7. Generating Test Reports In NUnit - Understand how to use extent reports and generate reports with NUnit and Selenium WebDriver. Also, look into how to capture screenshots in NUnit extent reports.
  8. Parallel Execution In NUnit - Parallel testing helps to reduce time consumption while executing a test. Deep dive into the concept of Specflow Parallel Execution in NUnit.

NUnit certification -

You can also check out the LambdaTest Certification to enhance your learning in Selenium Automation Testing using the NUnit framework.

YouTube

Watch this tutorial on the LambdaTest Channel to learn how to set up the NUnit framework, run tests and also execute parallel testing.

Run Nunit automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful