Example #1
0
        public void Execute_should_create_collection_when_Validator_is_set(
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.DocumentValidation);
            DropCollection();
            var validator = new BsonDocument("_id", new BsonDocument("$exists", true));
            var subject   = new CreateCollectionOperation(_collectionNamespace, _messageEncoderSettings)
            {
                Validator        = validator,
                ValidationLevel  = DocumentValidationLevel.Strict,
                ValidationAction = DocumentValidationAction.Error
            };

            BsonDocument info;

            using (var binding = CoreTestConfiguration.GetReadWriteBinding(_session.Fork()))
            {
                ExecuteOperation(subject, binding, async);
                info = GetCollectionInfo(binding);
            }

            info["options"]["validator"].Should().Be(validator);
            info["options"]["validationLevel"].AsString.Should().Be("strict");
            info["options"]["validationAction"].AsString.Should().Be("error");
        }
        public void Execute_should_create_collection_when_AutoIndexId_is_set(
            [Values(false, true)]
            bool autoIndexId,
            [Values(false, true)]
            bool async)
        {
            var subject = new CreateCollectionOperation(_collectionNamespace, _messageEncoderSettings)
            {
                AutoIndexId = autoIndexId
            };

            using (var binding = CoreTestConfiguration.GetReadWriteBinding())
            {
                var result = ExecuteOperation(subject, binding, async);

                result["ok"].ToBoolean().Should().BeTrue();

                var listIndexesOperation = new ListIndexesOperation(_collectionNamespace, _messageEncoderSettings);
                List <BsonDocument> indexes;
                if (async)
                {
                    var cursor = listIndexesOperation.ExecuteAsync(binding, CancellationToken.None).GetAwaiter().GetResult();
                    indexes = cursor.ToListAsync().GetAwaiter().GetResult();
                }
                else
                {
                    var cursor = listIndexesOperation.Execute(binding, CancellationToken.None);
                    indexes = cursor.ToList();
                }

                indexes.Count.Should().Be(autoIndexId ? 1 : 0);
            }
        }
Example #3
0
        public void Execute_should_create_collection_when_MaxDocuments_is_set(
            [Values(1L, 2L)]
            long maxDocuments,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check();
            DropCollection();
            var subject = new CreateCollectionOperation(_collectionNamespace, _messageEncoderSettings)
            {
                Capped       = true,
                MaxSize      = 10000L,
                MaxDocuments = maxDocuments
            };

            BsonDocument info;

            using (var binding = CoreTestConfiguration.GetReadWriteBinding(_session.Fork()))
            {
                ExecuteOperation(subject, binding, async);
                info = GetCollectionInfo(binding);
            }

            info["options"]["max"].ToInt64().Should().Be(maxDocuments);
        }
Example #4
0
        public void Execute_should_create_collection_when_StorageEngine_is_set(
            [Values("abc", "def")]
            string metadata,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().StorageEngine("wiredTiger");
            DropCollection();
            var storageEngine = new BsonDocument
            {
                { "wiredTiger", new BsonDocument("configString", "app_metadata=" + metadata) }
            };
            var subject = new CreateCollectionOperation(_collectionNamespace, _messageEncoderSettings)
            {
                StorageEngine = storageEngine
            };

            BsonDocument info;

            using (var binding = CoreTestConfiguration.GetReadWriteBinding(_session.Fork()))
            {
                ExecuteOperation(subject, binding, async);
                info = GetCollectionInfo(binding);
            }

            info["options"]["storageEngine"].Should().Be(storageEngine);
        }
Example #5
0
        public void Execute_should_create_collection_when_Capped_is_set(
            [Values(false, true)]
            bool capped,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check();
            DropCollection();
            var maxSize = capped ? 10000L : (long?)null;
            var subject = new CreateCollectionOperation(_collectionNamespace, _messageEncoderSettings)
            {
                Capped  = capped,
                MaxSize = maxSize
            };

            BsonDocument info;

            using (var binding = CoreTestConfiguration.GetReadWriteBinding(_session.Fork()))
            {
                ExecuteOperation(subject, binding, async);
                info = GetCollectionInfo(binding);
            }

            // in older versions of the server options might not be present if capped is false
            if (capped || info.Contains("options"))
            {
                info["options"].AsBsonDocument.GetValue("capped", false).ToBoolean().Should().Be(capped);
            }
        }
Example #6
0
        public void Execute_should_create_collection_when_IndexOptionDefaults_is_set(
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.IndexOptionsDefaults);
            DropCollection();
            var indexOptionDefaults = new BsonDocument
            {
                { "storageEngine", new BsonDocument("mmapv1", new BsonDocument()) }
            };
            var subject = new CreateCollectionOperation(_collectionNamespace, _messageEncoderSettings)
            {
                IndexOptionDefaults = indexOptionDefaults
            };

            BsonDocument info;

            using (var binding = CoreTestConfiguration.GetReadWriteBinding(_session.Fork()))
            {
                ExecuteOperation(subject, binding, async);
                info = GetCollectionInfo(binding);
            }

            info["options"]["indexOptionDefaults"].Should().Be(indexOptionDefaults);
        }
Example #7
0
        public bool OneTimeSetup()
        {
            __capturedEvents = new EventCapturer()
                               .Capture <CommandStartedEvent>(e => __commandsToCapture.Contains(e.CommandName))
                               .Capture <CommandSucceededEvent>(e => __commandsToCapture.Contains(e.CommandName))
                               .Capture <CommandFailedEvent>(e => __commandsToCapture.Contains(e.CommandName));

            var settings = new MongoClientSettings
            {
                ClusterConfigurator = cb =>
                {
                    cb = CoreTestConfiguration.ConfigureCluster(cb);
                    cb.Subscribe(__capturedEvents);

                    // never heartbeat...
                    cb.ConfigureServer(ss => ss.With(heartbeatInterval: Timeout.InfiniteTimeSpan));
                }
            };

            settings.RetryWrites = false;

            __client = new MongoClient(settings);

            return(true);
        }
        private bool IsRequirementSatisfied(BsonElement requirement)
        {
            switch (requirement.Name)
            {
            case "authEnabled":
            case "auth":
                return(IsAuthenticated() == requirement.Value.ToBoolean());

            case "minServerVersion":
            {
                var actualVersion    = CoreTestConfiguration.ServerVersion;
                var minServerVersion = SemanticVersion.Parse(requirement.Value.AsString);
                return(SemanticVersionCompareToAsReleased(actualVersion, minServerVersion) >= 0);
            }

            case "maxServerVersion":
            {
                var actualVersion    = CoreTestConfiguration.ServerVersion;
                var maxServerVersion = SemanticVersion.Parse(requirement.Value.AsString);
                return(SemanticVersionCompareToAsReleased(actualVersion, maxServerVersion) <= 0);
            }

            case "serverless":
                var serverlessValue = requirement.Value.AsString;
                switch (serverlessValue)
                {
                case "allow":
                    return(true);

                case "forbid":
                    return(CoreTestConfiguration.Serverless == false);

                case "require":
                    return(CoreTestConfiguration.Serverless == true);

                default:
                    throw new FormatException($"Invalid runOn requirement serverless field value: '{requirement.Value}'.");
                }

            case "serverParameters":
                var serverParameters = CoreTestConfiguration.GetServerParameters();
                foreach (var parameter in requirement.Value.AsBsonDocument)
                {
                    if (serverParameters[parameter.Name] != parameter.Value)
                    {
                        return(false);
                    }
                }
                return(true);

            case "topologies":
            case "topology":
                var actualClusterType = CoreTestConfiguration.Cluster.Description.Type;
                var runOnClusterTypes = requirement.Value.AsBsonArray.Select(topology => MapTopologyToClusterType(topology.AsString)).ToList();
                return(runOnClusterTypes.Contains(actualClusterType));

            default:
                throw new FormatException($"Unrecognized requirement field: '{requirement.Name}'.");
            }
        }
Example #9
0
        public void Execute_should_create_view_when_Collation_is_set(
            [Values(null, "en_US")]
            string locale,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.Views).VersionGreaterThanOrEqualTo("3.3.13");
            DropView(_viewName);
            var collation = locale == null ? null : new Collation(locale);
            var subject   = new CreateViewOperation(_databaseNamespace, _viewName, _collectionNamespace.CollectionName, _pipeline, _messageEncoderSettings)
            {
                Collation = collation
            };

            BsonDocument info;

            using (var binding = CoreTestConfiguration.GetReadWriteBinding(_session.Fork()))
            {
                ExecuteOperation(subject, binding, async);
                info = GetViewInfo(binding, _viewName);
            }

            var options = info["options"].AsBsonDocument;

            options["viewOn"].AsString.Should().Be(_collectionNamespace.CollectionName);
            options["pipeline"].AsBsonArray.Cast <BsonDocument>().Should().Equal(_pipeline);
            if (collation == null)
            {
                options.Contains("collation").Should().BeFalse();
            }
            else
            {
                options["collation"].AsBsonDocument.Should().Equals(collation.ToBsonDocument());
            }
        }
Example #10
0
        public void Execute_should_create_view_when_WriteConcern_is_set(
            [Values("a", "b")]
            string viewName,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.Views);
            DropView(viewName);
            var subject = new CreateViewOperation(_databaseNamespace, viewName, _collectionNamespace.CollectionName, _pipeline, _messageEncoderSettings)
            {
                WriteConcern = new WriteConcern(1)
            };

            BsonDocument info;

            using (var binding = CoreTestConfiguration.GetReadWriteBinding(_session.Fork()))
            {
                ExecuteOperation(subject, binding, async);
                info = GetViewInfo(binding, viewName);
            }

            var options = info["options"].AsBsonDocument;

            options["viewOn"].AsString.Should().Be(_collectionNamespace.CollectionName);
            options["pipeline"].AsBsonArray.Cast <BsonDocument>().Should().Equal(_pipeline);
        }
        public void InsertOne_to_oftype_collection_should_generate_id()
        {
            var collectionNamespace = CoreTestConfiguration.GetCollectionNamespaceForTestClass(typeof(CSharp2622Tests));
            var databaseName        = collectionNamespace.DatabaseNamespace.DatabaseName;
            var collectionName      = collectionNamespace.CollectionName;
            var client           = DriverTestConfiguration.Client;
            var database         = client.GetDatabase(databaseName);
            var collection       = database.GetCollection <C>(collectionName);
            var ofTypeCollection = collection.OfType <D>();

            database.DropCollection(collectionName);
            var document = new D {
                X = 1
            };

            ofTypeCollection.InsertOne(document);

            var insertedDocuments = collection.FindSync("{}").ToList();

            insertedDocuments.Count.Should().Be(1);
            insertedDocuments[0].Should().BeOfType <D>();
            var insertedDocument = (D)insertedDocuments[0];

            insertedDocument.Id.Should().NotBe(ObjectId.Empty);
            insertedDocument.X.Should().Be(1);
        }
        // private methods
        private bool CanRunOn(ICluster cluster, BsonDocument requirement)
        {
            foreach (var item in requirement)
            {
                switch (item.Name)
                {
                case "minServerVersion":
                {
                    var actualVersion    = CoreTestConfiguration.ServerVersion;
                    var minServerVersion = SemanticVersion.Parse(item.Value.AsString);
                    if (SemanticVersionCompareToAsReleased(actualVersion, minServerVersion) < 0)
                    {
                        return(false);
                    }
                }
                break;

                case "maxServerVersion":
                {
                    var actualVersion    = CoreTestConfiguration.ServerVersion;
                    var maxServerVersion = SemanticVersion.Parse(item.Value.AsString);
                    if (SemanticVersionCompareToAsReleased(actualVersion, maxServerVersion) > 0)
                    {
                        return(false);
                    }
                }
                break;

                case "serverParameters":
                {
                    var serverParameters = CoreTestConfiguration.GetServerParameters();
                    foreach (var parameter in item.Value.AsBsonDocument)
                    {
                        if (serverParameters[parameter.Name] != parameter.Value)
                        {
                            return(false);
                        }
                    }
                }
                break;

                case "topologies":
                case "topology":
                {
                    var actualClusterType = CoreTestConfiguration.Cluster.Description.Type;
                    var runOnClusterTypes = item.Value.AsBsonArray.Select(topology => MapTopologyToClusterType(topology.AsString)).ToList();
                    if (!runOnClusterTypes.Contains(actualClusterType))
                    {
                        return(false);
                    }
                }
                break;

                default:
                    throw new FormatException($"Unrecognized requirement field: '{item.Name}'");
                }
            }

            return(true);
        }
        public void Execute_should_create_collection_when_MaxSize_is_set(
            [Values(false, true)]
            bool async)
        {
            RequireServer.Any();
            DropCollection();
            var maxSize = 10000L;
            var subject = new CreateCollectionOperation(_collectionNamespace, _messageEncoderSettings)
            {
                Capped  = true,
                MaxSize = maxSize
            };

            using (var binding = CoreTestConfiguration.GetReadWriteBinding())
            {
                var result = ExecuteOperation(subject, binding, async);

                result["ok"].ToBoolean().Should().BeTrue();

                var stats = GetCollectionStats(binding, async);
                stats["ns"].ToString().Should().Be(_collectionNamespace.FullName);
                stats["capped"].ToBoolean().Should().BeTrue();
                // TODO: not sure how to verify that the maxSize took effect
            }
        }
        public void Execute_should_create_collection_when_MaxDocuments_is_set(
            [Values(false, true)]
            bool async)
        {
            RequireServer.Any();
            DropCollection();
            var maxDocuments = 123L;
            var subject      = new CreateCollectionOperation(_collectionNamespace, _messageEncoderSettings)
            {
                Capped       = true,
                MaxSize      = 10000L,
                MaxDocuments = maxDocuments
            };

            using (var binding = CoreTestConfiguration.GetReadWriteBinding())
            {
                var result = ExecuteOperation(subject, binding, async);

                result["ok"].ToBoolean().Should().BeTrue();

                var stats = GetCollectionStats(binding, async);
                stats["ns"].ToString().Should().Be(_collectionNamespace.FullName);
                stats["capped"].ToBoolean().Should().BeTrue();
                stats["max"].ToInt64().Should().Be(maxDocuments);
            }
        }
Example #15
0
 protected TResult ExecuteOperation <TResult>(IReadOperation <TResult> operation)
 {
     using (var binding = CoreTestConfiguration.GetReadBinding())
     {
         return(operation.Execute(binding, CancellationToken.None));
     }
 }
        public void Execute_should_create_collection_when_Capped_is_set(
            [Values(false, true)]
            bool capped,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Any();
            DropCollection();
            var maxSize = capped ? (long?)10000 : null;
            var subject = new CreateCollectionOperation(_collectionNamespace, _messageEncoderSettings)
            {
                Capped  = capped,
                MaxSize = maxSize
            };

            using (var binding = CoreTestConfiguration.GetReadWriteBinding())
            {
                var result = ExecuteOperation(subject, binding, async);

                result["ok"].ToBoolean().Should().BeTrue();

                var stats = GetCollectionStats(binding, async);
                stats["ns"].ToString().Should().Be(_collectionNamespace.FullName);
                stats.GetValue("capped", false).ToBoolean().Should().Be(capped);
            }
        }
Example #17
0
 protected async Task <TResult> ExecuteOperationAsync <TResult>(IReadOperation <TResult> operation)
 {
     using (var binding = CoreTestConfiguration.GetReadBinding())
     {
         return(await ExecuteOperationAsync(operation, binding));
     }
 }
Example #18
0
 protected async Task <TResult> ExecuteOperationAsync <TResult>(IWriteOperation <TResult> operation)
 {
     using (var binding = CoreTestConfiguration.GetReadWriteBinding())
     {
         return(await operation.ExecuteAsync(binding, CancellationToken.None));
     }
 }
        public void Count_should_return_the_expected_result(
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.AggregateCountStage);
            var client              = DriverTestConfiguration.Client;
            var databaseNamespace   = CoreTestConfiguration.DatabaseNamespace;
            var collectionNamespace = CoreTestConfiguration.GetCollectionNamespaceForTestMethod();
            var database            = client.GetDatabase(databaseNamespace.DatabaseName);

            database.DropCollection(collectionNamespace.CollectionName);
            var collection = database.GetCollection <BsonDocument>(collectionNamespace.CollectionName);

            collection.InsertOne(new BsonDocument());
            var subject = collection.Aggregate();

            long result;

            if (async)
            {
                result = subject.Count().SingleAsync().GetAwaiter().GetResult().Count;
            }
            else
            {
                result = subject.Count().Single().Count;
            }

            result.Should().Be(1);
        }
Example #20
0
        public async Task ExecuteAsync_should_find_all_the_documents_matching_the_query_when_limit_is_used(
            [Values(1, 5, 6, 12)] int limit)
        {
            RequireServer.Check().VersionLessThan("3.2.0");
            var collectionNamespace = CoreTestConfiguration.GetCollectionNamespaceForTestMethod(
                className: GetType().Name,
                methodName: nameof(ExecuteAsync_should_find_all_the_documents_matching_the_query_when_limit_is_used));

            for (var id = 1; id <= limit + 1; id++)
            {
                var document = new BsonDocument {
                    { "id", id }, { "filler", new string('x', 1000000) }
                };                                                                                        // about 1MB big
                var requests        = new[] { new InsertRequest(document) };
                var insertOperation = new BulkMixedWriteOperation(collectionNamespace, requests, new MessageEncoderSettings());
                ExecuteOperation(insertOperation);
            }
            var subject = new FindOpcodeOperation <BsonDocument>(collectionNamespace, BsonDocumentSerializer.Instance, _messageEncoderSettings)
            {
                Limit = limit
            };

            using (var cursor = await ExecuteOperationAsync(subject))
            {
                var result = await ReadCursorToEndAsync(cursor);

                result.Should().HaveCount(limit);
            }
        }
Example #21
0
        public void Command_should_update_the_session_and_cluster_cluster_times()
        {
            RequireServer.Check().VersionGreaterThanOrEqualTo("3.6").ClusterTypes(ClusterType.ReplicaSet, ClusterType.Sharded);

            var eventCapturer = new EventCapturer().Capture <CommandSucceededEvent>(e => e.CommandName == "ping");

            using (var cluster = CoreTestConfiguration.CreateCluster(b => b.Subscribe(eventCapturer)))
                using (var session = cluster.StartSession())
                {
                    var cancellationToken = CancellationToken.None;
                    var server            = (Server)cluster.SelectServer(WritableServerSelector.Instance, cancellationToken);
                    using (var channel = server.GetChannel(cancellationToken))
                    {
                        var command = BsonDocument.Parse("{ ping : 1 }");
                        channel.Command <BsonDocument>(
                            session,
                            ReadPreference.Primary,
                            DatabaseNamespace.Admin,
                            command,
                            NoOpElementNameValidator.Instance,
                            null, // additionalOptions
                            () => CommandResponseHandling.Return,
                            BsonDocumentSerializer.Instance,
                            new MessageEncoderSettings(),
                            cancellationToken);
                    }

                    var commandSucceededEvent = eventCapturer.Next().Should().BeOfType <CommandSucceededEvent>().Subject;
                    var actualReply           = commandSucceededEvent.Reply;
                    var actualClusterTime     = actualReply["$clusterTime"].AsBsonDocument;
                    session.ClusterTime.Should().Be(actualClusterTime);
                    server.ClusterClock.ClusterTime.Should().Be(actualClusterTime);
                }
        }
Example #22
0
        public void TestFixtureSetUp()
        {
            var databaseNamespace = CoreTestConfiguration.GetDatabaseNamespaceForTestFixture();

            _collectionNamespace    = new CollectionNamespace(databaseNamespace, "ListIndexesOperationTests");
            _messageEncoderSettings = CoreTestConfiguration.MessageEncoderSettings;
        }
        protected IReadWriteBinding CreateReadWriteBinding(bool useImplicitSession = false)
        {
            var options = new CoreSessionOptions(isImplicit: useImplicitSession);
            var session = CoreTestConfiguration.StartSession(_cluster, options);

            return(new WritableServerBinding(_cluster, session));
        }
        protected void VerifySessionIdSending <TResult>(
            Func <WritableServerBinding, CancellationToken, Task <TResult> > executeAsync,
            Func <WritableServerBinding, CancellationToken, TResult> execute,
            Action <EventCapturer, ICoreSessionHandle, Exception> assertResults,
            string commandName,
            bool async,
            bool useImplicitSession = false)
        {
            var eventCapturer = new EventCapturer().Capture <CommandStartedEvent>(e => e.CommandName == commandName);

            using (var cluster = CoreTestConfiguration.CreateCluster(b => b.Subscribe(eventCapturer)))
            {
                using (var session = CreateSession(cluster, useImplicitSession))
                    using (var binding = new WritableServerBinding(cluster, session.Fork()))
                    {
                        var       cancellationToken = new CancellationTokenSource().Token;
                        Exception exception;
                        if (async)
                        {
                            exception = Record.Exception(() => executeAsync(binding, cancellationToken).GetAwaiter().GetResult());
                        }
                        else
                        {
                            exception = Record.Exception(() => execute(binding, cancellationToken));
                        }

                        assertResults(eventCapturer, session, exception);
                    }
            }
        }
Example #25
0
 // private methods
 private BsonValue ExecuteOperation(EvalOperation operation, bool async)
 {
     using (var binding = CoreTestConfiguration.GetReadWriteBinding())
     {
         return(ExecuteOperation(operation, binding, async));
     }
 }
 public OperationTestBase()
 {
     _databaseNamespace      = CoreTestConfiguration.DatabaseNamespace;
     _collectionNamespace    = CoreTestConfiguration.GetCollectionNamespaceForTestClass(GetType());
     _messageEncoderSettings = CoreTestConfiguration.MessageEncoderSettings;
     _session = CoreTestConfiguration.StartSession();
 }
Example #27
0
 private ICluster CreateLoadBalancedCluster(EventCapturer eventCapturer, string appName = null) =>
 CoreTestConfiguration.CreateCluster(builder =>
 {
     return(builder
            .ConfigureCluster(cs => cs.With(loadBalanced: true))
            .ConfigureConnection(cc => cc.With(applicationName: appName))
            .Subscribe(eventCapturer));
 });
 protected async Task <TResult> ExecuteOperationAsync <TResult>(IReadOperation <TResult> operation)
 {
     using (var binding = CoreTestConfiguration.GetReadBinding(_session.Fork()))
         using (var bindingHandle = new ReadBindingHandle(binding))
         {
             return(await ExecuteOperationAsync(operation, bindingHandle));
         }
 }
 protected TResult ExecuteOperation <TResult>(IWriteOperation <TResult> operation)
 {
     using (var binding = CoreTestConfiguration.GetReadWriteBinding(_session.Fork()))
         using (var bindingHandle = new ReadWriteBindingHandle(binding))
         {
             return(operation.Execute(bindingHandle, CancellationToken.None));
         }
 }
        // helper methods
        private void DropCollection()
        {
            var operation = new DropCollectionOperation(_collectionNamespace, _messageEncoderSettings);

            using (var binding = CoreTestConfiguration.GetReadWriteBinding())
            {
                operation.ExecuteAsync(binding, CancellationToken.None).GetAwaiter().GetResult();
            }
        }