예제 #1
0
        public void Execute_should_throw_when_a_write_concern_error_occurs(
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.CommandsThatWriteAcceptWriteConcern).ClusterType(ClusterType.ReplicaSet);
            var actualVersion = CoreTestConfiguration.ServerVersion;

            if (actualVersion.Major == 3 && actualVersion.Minor == 5 && actualVersion.Patch == 2)
            {
                // skip test on any version of 3.5.2
                return; // TODO: remove later
            }
            EnsureCollectionExists();
            var subject = new ReIndexOperation(_collectionNamespace, _messageEncoderSettings)
            {
                WriteConcern = new WriteConcern(9)
            };

            var exception = Record.Exception(() => ExecuteOperation(subject, async));

            exception.Should().BeOfType <MongoWriteConcernException>();
        }
        // private methods
        private void CheckClusterTopology(BsonArray allowedTopologies)
        {
            var allowedClusterTypes = allowedTopologies.Select(MapToplogyToClusterType).ToArray();

            RequireServer.Check().ClusterTypes(allowedClusterTypes);

            var clusterType = CoreTestConfiguration.Cluster.Description.Type;

            switch (clusterType)
            {
            case ClusterType.Sharded:
                RequireServer.Check().Supports(Feature.ShardedTransactions);
                break;

            case ClusterType.ReplicaSet:
                RequireServer.Check().Supports(Feature.Transactions);
                break;

            default:
                throw new Exception("Topology type for transactions must be replicaset or sharded.");
            }
        }
        public void Execute_should_work_when_expireAfter_has_value(
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check();
            DropCollection();
            var expireAfter = TimeSpan.FromSeconds(1);
            var requests    = new[] { new CreateIndexRequest(new BsonDocument("x", 1))
                                      {
                                          ExpireAfter = expireAfter
                                      } };
            var subject = new CreateIndexesOperation(_collectionNamespace, requests, _messageEncoderSettings);

            var result = ExecuteOperation(subject, async);

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

            var indexes = ListIndexes();
            var index   = indexes.Single(i => i["name"].AsString == "x_1");

            index["expireAfterSeconds"].ToDouble().Should().Be(expireAfter.TotalSeconds);
        }
예제 #4
0
        public void AfterClusterTime_should_not_be_sent_when_the_session_is_not_causally_consistent()
        {
            RequireServer.Check().SupportsCausalConsistency();

            var events = new EventCapturer()
                         .Capture <CommandStartedEvent>(x => x.CommandName == "count");

            using (var client = GetClient(events))
                using (var session = client.StartSession(new ClientSessionOptions {
                    CausalConsistency = false
                }))
                {
#pragma warning disable 618
                    client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName)
                    .GetCollection <BsonDocument>(DriverTestConfiguration.CollectionNamespace.CollectionName)
                    .Count(session, FilterDefinition <BsonDocument> .Empty);
#pragma warning restore

                    var commandStartedEvent = (CommandStartedEvent)events.Next();
                    commandStartedEvent.Command.Contains("readConcern").Should().BeFalse();
                }
        }
        public void KillCursors_should_return_expected_result()
        {
            RequireEnvironment.Check().EnvironmentVariable("ATLAS_DATA_LAKE_TESTS_ENABLED");
            RequireServer.Check();

            var databaseName   = "test";
            var collectionName = "driverdata";

            var eventCapturer = new EventCapturer()
                                .Capture <CommandStartedEvent>(x => "killCursors" == x.CommandName)
                                .Capture <CommandSucceededEvent>(x => new[] { "killCursors", "find" }.Contains(x.CommandName));

            using (var client = DriverTestConfiguration.CreateDisposableClient(eventCapturer))
            {
                var cursor = client
                             .GetDatabase(databaseName)
                             .GetCollection <BsonDocument>(collectionName)
                             .Find(new BsonDocument(), new FindOptions {
                    BatchSize = 2
                })
                             .ToCursor();

                var findCommandSucceededEvent = eventCapturer.Events.OfType <CommandSucceededEvent>().First(x => x.CommandName == "find");
                var findCommandResult         = findCommandSucceededEvent.Reply;
                var cursorId        = findCommandResult["cursor"]["id"].AsInt64;
                var cursorNamespace = CollectionNamespace.FromFullName(findCommandResult["cursor"]["ns"].AsString);

                cursor.Dispose();

                var killCursorsCommandStartedEvent   = eventCapturer.Events.OfType <CommandStartedEvent>().First(x => x.CommandName == "killCursors");
                var killCursorsCommandSucceededEvent = eventCapturer.Events.OfType <CommandSucceededEvent>().First(x => x.CommandName == "killCursors");
                var killCursorsStartedCommand        = killCursorsCommandStartedEvent.Command;

                cursorNamespace.DatabaseNamespace.DatabaseName.Should().Be(killCursorsCommandStartedEvent.DatabaseNamespace.DatabaseName);
                cursorNamespace.CollectionName.Should().Be(killCursorsStartedCommand["killCursors"].AsString);
                cursorId.Should().Be(killCursorsStartedCommand["cursors"][0].AsInt64);
                cursorId.Should().Be(killCursorsCommandSucceededEvent.Reply["cursorsKilled"][0].AsInt64);
            }
        }
        public void Test()
        {
            RequireServer.Check().StorageEngine("mmapv1");
            if (_server.Primary.InstanceType != MongoServerInstanceType.ShardRouter)
            {
                _collection.Drop();
                // make sure collection and database exist
                _collection.Insert(new BsonDocument());

                var result = _database.GetStats();
                Assert.True(result.Ok);
                Assert.True(result.AverageObjectSize > 0);
                Assert.True(result.CollectionCount > 0);
                Assert.True(result.DataSize > 0);
                Assert.True(result.ExtentCount > 0);
                Assert.True(result.FileSize > 0);
                Assert.True(result.IndexCount > 0);
                Assert.True(result.IndexSize > 0);
                Assert.True(result.ObjectCount > 0);
                Assert.True(result.StorageSize > 0);
            }
        }
        public void TestCreateCollectionSetIndexOptionDefaults()
        {
            RequireServer.Check().Supports(Feature.IndexOptionsDefaults).ClusterTypes(ClusterType.Standalone, ClusterType.ReplicaSet);
            var collection = _database.GetCollection("testindexoptiondefaults");

            collection.Drop();
            Assert.False(collection.Exists());
            var storageEngine        = CoreTestConfiguration.GetStorageEngine();
            var storageEngineOptions = new BsonDocument(storageEngine, new BsonDocument());
            var indexOptionDefaults  = new IndexOptionDefaults {
                StorageEngine = storageEngineOptions
            };
            var expectedIndexOptionDefaultsDocument = new BsonDocument("storageEngine", storageEngineOptions);
            var options = CollectionOptions.SetIndexOptionDefaults(indexOptionDefaults);

            _database.CreateCollection(collection.Name, options);

            var commandResult  = _database.RunCommand("listCollections");
            var collectionInfo = commandResult.Response["cursor"]["firstBatch"].AsBsonArray.Where(doc => doc["name"] == collection.Name).Single().AsBsonDocument;

            Assert.Equal(expectedIndexOptionDefaultsDocument, collectionInfo["options"]["indexOptionDefaults"]);
        }
        public void TestEvalWithMaxTime()
        {
            RequireServer.Check().Supports(Feature.Eval);
#pragma warning disable 618
            if (!DriverTestConfiguration.Client.Settings.Credentials.Any())
            {
                using (var failpoint = new FailPoint(FailPointName.MaxTimeAlwaysTimeout, _server, _primary))
                {
                    if (failpoint.IsSupported())
                    {
                        failpoint.SetAlwaysOn();
                        var args = new EvalArgs
                        {
                            Code    = "return 0;",
                            MaxTime = TimeSpan.FromMilliseconds(1)
                        };
                        Assert.Throws <MongoExecutionTimeoutException>(() => _adminDatabase.Eval(args));
                    }
                }
            }
#pragma warning restore
        }
예제 #9
0
        public void Execute_should_return_expected_results_when_Sort_is_set(
            [Values(1, -1)]
            int direction,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check();
            EnsureTestData();
            var sort = new BsonDocument("_id", direction);

#pragma warning disable CS0618 // Type or member is obsolete
            var subject = new MapReduceOperation <BsonDocument>(_collectionNamespace, _mapFunction, _reduceFunction, _resultSerializer, _messageEncoderSettings)
#pragma warning restore CS0618 // Type or member is obsolete
            {
                Limit = 2,
                Sort  = sort
            };

            var cursor  = ExecuteOperation(subject, async);
            var results = ReadCursorToEnd(cursor, async);

            BsonDocument[] expectedResults;
            if (direction == 1)
            {
                expectedResults = new[]
                {
                    BsonDocument.Parse("{ _id : 1, value : 3 }")
                };
            }
            else
            {
                expectedResults = new[]
                {
                    BsonDocument.Parse("{ _id : 1, value : 2 }"),
                    BsonDocument.Parse("{ _id : 2, value : 4 }")
                };
            }
            results.Should().BeEquivalentTo(expectedResults);
        }
예제 #10
0
        public void Execute_should_return_expected_results_when_FinalizeFunction_is_set(
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check();
            EnsureTestData();
            var finalizeFunction = new BsonJavaScript("function(key, reduced) { return -reduced; }");

#pragma warning disable CS0618 // Type or member is obsolete
            var subject = new MapReduceOperation <BsonDocument>(_collectionNamespace, _mapFunction, _reduceFunction, _resultSerializer, _messageEncoderSettings)
#pragma warning restore CS0618 // Type or member is obsolete
            {
                FinalizeFunction = finalizeFunction
            };

            var cursor  = ExecuteOperation(subject, async);
            var results = ReadCursorToEnd(cursor, async);

            results.Should().BeEquivalentTo(
                BsonDocument.Parse("{ _id : 1, value : -3 }"),
                BsonDocument.Parse("{ _id : 2, value : -4 }"));
        }
        public void Session_OperationTime_should_get_updated_after_an_operation()
        {
            RequireServer.Check().SupportsCausalConsistency();

            var events = new EventCapturer()
                         .Capture <CommandStartedEvent>(x => x.CommandName == "count")
                         .Capture <CommandSucceededEvent>(x => x.CommandName == "count");

            using (var client = GetClient(events))
                using (var session = client.StartSession())
                {
                    client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName)
                    .GetCollection <BsonDocument>(DriverTestConfiguration.CollectionNamespace.CollectionName)
                    .Count(session, FilterDefinition <BsonDocument> .Empty);

                    var commandStartedEvent = (CommandStartedEvent)events.Next();
                    commandStartedEvent.Command.GetValue("readConcern", null).Should().BeNull();

                    var commandSucceededEvent = (CommandSucceededEvent)events.Next();
                    session.OperationTime.Should().Be(commandSucceededEvent.Reply.GetValue("operationTime"));
                }
        }
        public void Execute_should_work_when_Collation_has_value(
            [Values("en_US", "fr_CA")]
            string locale,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.CreateIndexesCommand, Feature.Collation);
            DropCollection();
            var collation = new Collation(locale);
            var requests  = new[] { new CreateIndexRequest(new BsonDocument("x", 1))
                                    {
                                        Collation = collation
                                    } };
            var subject = new CreateIndexesUsingCommandOperation(_collectionNamespace, requests, _messageEncoderSettings);

            ExecuteOperation(subject, async);

            var indexes = ListIndexes();
            var index   = indexes.Single(i => i["name"].AsString == "x_1");

            index["collation"]["locale"].AsString.Should().Be(locale);
        }
        [InlineData("IX", "IX", "\u2168", "\u2163", "I\u00ADV", true)]  // "IX", "IX", Roman numeral nine, Roman numeral four, I-V
        public void Authentication_succeeds_with_Unicode_username_and_nonSaslPrepped_password_when_SaslPrep_equivalent_username_exists(
            string asciiUsername,
            string asciiPassword,
            string unicodeUsername,
            string unicodePassword,
            string nonSaslPreppedPassword,
            bool async)
        {
            RequireServer.Check().Supports(Feature.ScramSha256Authentication).Authentication(true);
            var client = DriverTestConfiguration.Client;
            var uniqueAsciiUserName   = $"{asciiUsername}{Guid.NewGuid()}";
            var uniqueUnicodeUserName = $"{unicodeUsername}{Guid.NewGuid()}";

            CreateAdminDatabaseUser(client, uniqueAsciiUserName, asciiPassword, "root", "SCRAM-SHA-256");
            CreateAdminDatabaseUser(client, uniqueUnicodeUserName, unicodePassword, "root", "SCRAM-SHA-256");
            var settings = client.Settings.Clone();

            settings.Credential = MongoCredential.FromComponents(
                mechanism: "SCRAM-SHA-256", source: null, username: uniqueUnicodeUserName, password: nonSaslPreppedPassword);

            AssertAuthenticationSucceeds(settings, async);
        }
        public void Connection_pool_should_be_cleared_when_Shutdown_exceptions(
            [Values(
                 ServerErrorCode.ShutdownInProgress,     // 91
                 ServerErrorCode.InterruptedAtShutdown)] // 11600
            int errorCode)
        {
            RequireServer.Check().Supports(Feature.FailPointsFailCommand).ClusterType(ClusterType.ReplicaSet);

            var eventCapturer = new EventCapturer()
                                .Capture <ConnectionPoolClearedEvent>()
                                .Capture <ConnectionCreatedEvent>();

            using (var client = CreateDisposableClient(eventCapturer))
            {
                var database = client.GetDatabase(_databaseName, new MongoDatabaseSettings {
                    WriteConcern = WriteConcern.WMajority
                });
                database.DropCollection(_databaseName);
                var collection = database.GetCollection <BsonDocument>(_collectionName, new MongoCollectionSettings {
                    WriteConcern = WriteConcern.WMajority
                });
                eventCapturer.Clear();

                using (ConfigureFailPoint(client, errorCode))
                {
                    var exception = Record.Exception(() => { collection.InsertOne(new BsonDocument("test", 1)); });

                    var e = exception.Should().BeOfType <MongoNodeIsRecoveringException>().Subject;
                    e.Code.Should().Be(errorCode);

                    eventCapturer.Next().Should().BeOfType <ConnectionPoolClearedEvent>();
                    eventCapturer.Events.Should().BeEmpty();

                    collection.InsertOne(new BsonDocument("test", 1));
                    eventCapturer.Next().Should().BeOfType <ConnectionCreatedEvent>();
                    eventCapturer.Events.Should().BeEmpty();
                }
            }
        }
예제 #15
0
        public async Task ExecuteAsync_should_find_documents_matching_options()
        {
            RequireServer.Check().Supports(Feature.LegacyWireProtocol);

            EnsureTestData();
            var subject = new FindOpcodeOperation <BsonDocument>(_collectionNamespace, BsonDocumentSerializer.Instance, _messageEncoderSettings)
            {
                Comment    = "funny",
                Filter     = BsonDocument.Parse("{ y : 1 }"),
                Limit      = 4,
                MaxTime    = TimeSpan.FromSeconds(20),
                Projection = BsonDocument.Parse("{ y : 1 }"),
                Skip       = 1,
                Sort       = BsonDocument.Parse("{ _id : -1 }")
            };

            var cursor = await ExecuteOperationAsync(subject);

            var result = await ReadCursorToEndAsync(cursor);

            result.Should().HaveCount(1);
        }
예제 #16
0
        public void SelectServer_loadbalancing_prose_test([Values(false, true)] bool async)
        {
            RequireServer.Check()
            .Supports(Feature.ShardedTransactions, Feature.FailPointsBlockConnection)
            .ClusterType(ClusterType.Sharded)
            .MultipleMongoses(true);

            // temporary disable the test on Auth envs due to operations timings irregularities
            RequireServer.Check().Authentication(false);

            const string applicationName = "loadBalancingTest";
            const int    threadsCount    = 10;
            const int    commandsFailPointPerThreadCount = 10;
            const int    commandsPerThreadCount          = 100;
            const double maxCommandsOnSlowServerRatio    = 0.3; // temporary set slow server load to 30% from 25% until find timings are investigated
            const double operationsCountTolerance        = 0.10;

            var failCommand = BsonDocument.Parse($"{{ configureFailPoint: 'failCommand', mode : {{ times : 10000 }}, data : {{ failCommands : [\"find\"], blockConnection: true, blockTimeMS: 500, appName: '{applicationName}' }} }}");

            DropCollection();
            var eventCapturer = CreateEventCapturer();

            using (var client = CreateDisposableClient(eventCapturer, applicationName))
            {
                var slowServer = client.Cluster.SelectServer(WritableServerSelector.Instance, default);
                var fastServer = client.Cluster.SelectServer(new DelegateServerSelector((_, servers) => servers.Where(s => s.ServerId != slowServer.ServerId)), default);

                using var failPoint = FailPoint.Configure(slowServer, NoCoreSession.NewHandle(), failCommand);

                var database = client.GetDatabase(_databaseName);
                CreateCollection();
                var collection = database.GetCollection <BsonDocument>(_collectionName);

                // warm up connections
                var channels = new ConcurrentBag <IChannelHandle>();
                ThreadingUtilities.ExecuteOnNewThreads(threadsCount, i =>
                {
                    channels.Add(slowServer.GetChannel(default));
                    channels.Add(fastServer.GetChannel(default));
        public void Execute_should_return_expected_results_when_MaxTime_is_set(
            [Values(null, 1000)]
            int?seconds,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.MaxTime);
            EnsureTestData();
            var maxTime = seconds.HasValue ? TimeSpan.FromSeconds(seconds.Value) : (TimeSpan?)null;
            var subject = new MapReduceOperation <BsonDocument>(_collectionNamespace, _mapFunction, _reduceFunction, _resultSerializer, _messageEncoderSettings)
            {
                MaxTime = maxTime
            };

            var cursor  = ExecuteOperation(subject, async);
            var results = ReadCursorToEnd(cursor, async);

            // results should be the same whether MaxTime was used or not
            results.Should().Equal(
                BsonDocument.Parse("{ _id : 1, value : 3 }"),
                BsonDocument.Parse("{ _id : 2, value : 4 }"));
        }
        public void Execute_should_return_expected_results_when_ReadConcern_is_set(
            [Values(null, ReadConcernLevel.Local)] // only use values that are valid on StandAlone servers
            ReadConcernLevel?readConcernLevel,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.ReadConcern);
            EnsureTestData();
            var readConcern = new ReadConcern(readConcernLevel);
            var subject     = new MapReduceOperation <BsonDocument>(_collectionNamespace, _mapFunction, _reduceFunction, _resultSerializer, _messageEncoderSettings)
            {
                ReadConcern = readConcern
            };

            // results should be the same whether ReadConcern was used or not
            var cursor  = ExecuteOperation(subject, async);
            var results = ReadCursorToEnd(cursor, async);

            results.Should().Equal(
                BsonDocument.Parse("{ _id : 1, value : 3 }"),
                BsonDocument.Parse("{ _id : 2, value : 4 }"));
        }
예제 #19
0
        public void Execute_should_find_documents_matching_options(
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.FindCommand);
            EnsureTestData();
            var subject = new FindCommandOperation <BsonDocument>(_collectionNamespace, BsonDocumentSerializer.Instance, _messageEncoderSettings)
            {
                Comment    = "funny",
                Filter     = BsonDocument.Parse("{ y : 1 }"),
                Limit      = 4,
                MaxTime    = TimeSpan.FromSeconds(20),
                Projection = BsonDocument.Parse("{ y : 1 }"),
                Skip       = 1,
                Sort       = BsonDocument.Parse("{ _id : -1 }")
            };

            var cursor = ExecuteOperation(subject, async);
            var result = ReadCursorToEnd(cursor);

            result.Should().HaveCount(1);
        }
        public void Execute_should_return_expected_result_when_MaxTime_is_used(
            [Values(null, 1000)]
            int?seconds,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check();
            EnsureTestData();
            var maxTime = seconds.HasValue ? TimeSpan.FromSeconds(seconds.Value) : (TimeSpan?)null;
            var subject = new GroupOperation <BsonDocument>(_collectionNamespace, _key, _initial, _reduceFunction, null, _messageEncoderSettings)
            {
                MaxTime = maxTime
            };

            // TODO: force a timeout on the server? for now we're just smoke testing
            var result = ExecuteOperation(subject, async);

            result.Should().Equal(
                BsonDocument.Parse("{ x : 1, count : 2 }"),
                BsonDocument.Parse("{ x : 2, count : 1 }"),
                BsonDocument.Parse("{ x : 3, count : 3 }"));
        }
        public void CreateStream_should_call_the_socketConfigurator(
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check();
            var             socketConfiguratorWasCalled = false;
            Action <Socket> socketConfigurator          = s => socketConfiguratorWasCalled = true;
            var             settings = new TcpStreamSettings(socketConfigurator: socketConfigurator);
            var             subject  = new TcpStreamFactory(settings);
            var             endPoint = CoreTestConfiguration.ConnectionString.Hosts[0];

            if (async)
            {
                subject.CreateStreamAsync(endPoint, CancellationToken.None).GetAwaiter().GetResult();
            }
            else
            {
                subject.CreateStream(endPoint, CancellationToken.None);
            }

            socketConfiguratorWasCalled.Should().BeTrue();
        }
        public void Execute_should_return_expected_result_when_MaxAwaitTime_is_set(
            [Values(null, 1000)]
            int?milliseconds,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.ChangeStreamStage);
            EnsureTestData();
            var maxAwaitTime = milliseconds == null ? (TimeSpan?)null : TimeSpan.FromMilliseconds(milliseconds.Value);
            var subject      = new AggregateOperation <BsonDocument>(_collectionNamespace, __pipeline, __resultSerializer, _messageEncoderSettings)
            {
                MaxAwaitTime = maxAwaitTime
            };

            var cursor = ExecuteOperation(subject, async);

            cursor.Should().BeOfType <AsyncCursor <BsonDocument> >();
            var cursorMaxTimeInfo = typeof(AsyncCursor <BsonDocument>).GetField("_maxTime", BindingFlags.NonPublic | BindingFlags.Instance);
            var cursorMaxTime     = (TimeSpan?)cursorMaxTimeInfo.GetValue(cursor);

            cursorMaxTime.Should().Be(maxAwaitTime);
        }
예제 #23
0
        public void Execute_should_work_when_commitQuorum_is_specified(
            [Values(1, "majority", "votingMembers")] object commitQuorumCase,
            [Values(false, true)] bool async)
        {
            RequireServer.Check().ClusterTypes(ClusterType.ReplicaSet, ClusterType.Sharded).Supports(Feature.CreateIndexCommitQuorum);
            DropCollection();
            var requests = new[] { new CreateIndexRequest(new BsonDocument("x", 1)) };
            CreateIndexCommitQuorum commitQuorum;

            if (commitQuorumCase is int w)
            {
                commitQuorum = CreateIndexCommitQuorum.Create(w);
            }
            else if (commitQuorumCase is string mode)
            {
                switch (mode)
                {
                case "majority": commitQuorum = CreateIndexCommitQuorum.Majority; break;

                case "votingMembers": commitQuorum = CreateIndexCommitQuorum.VotingMembers; break;

                default: commitQuorum = CreateIndexCommitQuorum.Create(mode); break;
                }
            }
            else
            {
                throw new ArgumentException($"Invalid commitQuorumCase: {commitQuorumCase}.", nameof(commitQuorumCase));
            }
            var subject = new CreateIndexesUsingCommandOperation(_collectionNamespace, requests, _messageEncoderSettings)
            {
                CommitQuorum = commitQuorum
            };

            ExecuteOperation(subject, async);

            var indexes = ListIndexes();

            indexes.Select(index => index["name"].AsString).Should().BeEquivalentTo(new[] { "_id_", "x_1" });
        }
        public void Execute_should_return_expected_result_when_Let_is_set_with_match_expression(
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.AggregateOptionsLet);
            EnsureTestData();
            var pipeline = new[] { BsonDocument.Parse("{ $match : { $expr : { $eq : [ '$x', '$$y'] } } }") };
            var subject  = new AggregateOperation <BsonDocument>(_collectionNamespace, pipeline, __resultSerializer, _messageEncoderSettings)
            {
                Let = new BsonDocument("y", "x")
            };

            var cursor = ExecuteOperation(subject, async);
            var result = ReadCursorToEnd(cursor, async);

            result.Should().BeEquivalentTo(new[]
            {
                new BsonDocument {
                    { "_id", 1 }, { "x", "x" }
                }
            });
        }
예제 #25
0
        public void Execute_should_return_expected_result(
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().ClusterTypes(ClusterType.Standalone, ClusterType.ReplicaSet).VersionLessThan("4.8.0");
            EnsureTestData();
            var subject = new GeoSearchOperation <BsonDocument>(
                _collectionNamespace,
                new BsonArray {
                1, 2
            },
                BsonDocumentSerializer.Instance,
                _messageEncoderSettings)
            {
                MaxDistance = 20,
                Search      = new BsonDocument("Type", "restaraunt")
            };

            var result = ExecuteOperation(subject, async);

            result["results"].Should().NotBeNull();
        }
        public void Execute_should_find_all_the_documents_matching_the_query_when_max_staleness_is_used(
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.MaxStaleness);
            EnsureTestData();
            var subject        = new FindOperation <BsonDocument>(_collectionNamespace, BsonDocumentSerializer.Instance, _messageEncoderSettings);
            var readPreference = new ReadPreference(ReadPreferenceMode.SecondaryPreferred, maxStaleness: TimeSpan.FromSeconds(90));

            // the count could be short temporarily until replication catches up
            List <BsonDocument> result = null;

            SpinWait.SpinUntil(() =>
            {
                var cursor = ExecuteOperation(subject, readPreference, async);
                result     = ReadCursorToEnd(cursor, async);
                return(result.Count >= 5);
            },
                               TimeSpan.FromSeconds(10));

            result.Should().HaveCount(5);
        }
예제 #27
0
        private void SkipIfNotLoadBalancingMode()
        {
#if DEBUG
            RequirePlatform.Check().SkipWhen(SupportedOperatingSystem.Linux);
            RequirePlatform.Check().SkipWhen(SupportedOperatingSystem.MacOS);
            // Make sure that LB is started. "nginx" is a LB we use for windows testing
            RequireEnvironment.Check().ProcessStarted("nginx");
            Environment.SetEnvironmentVariable("MONGODB_URI", "mongodb://localhost:17017?loadBalanced=true");
            Environment.SetEnvironmentVariable("MONGODB_URI_WITH_MULTIPLE_MONGOSES", "mongodb://localhost:17018?loadBalanced=true");
            RequireServer
            .Check()
            .LoadBalancing(enabled: true, ignorePreviousSetup: true)
            .Authentication(authentication: false);                                 // auth server requires credentials in connection string
#else
            RequireEnvironment.Check().EnvironmentVariable("SINGLE_MONGOS_LB_URI"); // these env variables are used only on the scripting side
            RequireEnvironment.Check().EnvironmentVariable("MULTI_MONGOS_LB_URI");
            // EG currently supports LB only for Ubuntu
            RequirePlatform.Check().SkipWhen(SupportedOperatingSystem.Windows);
            RequirePlatform.Check().SkipWhen(SupportedOperatingSystem.MacOS);
            RequireServer.Check().ClusterType(ClusterType.LoadBalanced);
#endif
        }
        public void Execute_should_return_expected_results_when_Sort_is_set(
            [Values(1, -1)]
            int direction,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().ClusterTypes(ClusterType.Standalone, ClusterType.ReplicaSet);
            EnsureTestData();
            var sort = new BsonDocument("_id", direction);

#pragma warning disable CS0618 // Type or member is obsolete
            var subject = new MapReduceOutputToCollectionOperation(_collectionNamespace, _outputCollectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings)
#pragma warning restore CS0618 // Type or member is obsolete
            {
                Limit = 2,
                Sort  = sort
            };

            ExecuteOperation(subject, async);

            BsonDocument[] expectedResults;
            if (direction == 1)
            {
                expectedResults = new[]
                {
                    BsonDocument.Parse("{ _id : 1, value : 3 }")
                };
            }
            else
            {
                expectedResults = new[]
                {
                    BsonDocument.Parse("{ _id : 1, value : 2 }"),
                    BsonDocument.Parse("{ _id : 2, value : 4 }")
                };
            }
            ReadAllFromCollection(_outputCollectionNamespace).Should().BeEquivalentTo(expectedResults);
        }
        public void Execute_should_return_expected_results_when_Collation_is_set(
            [Values(false, true)]
            bool caseSensitive,
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.Collation);
            EnsureTestData();
            var collation = new Collation("en_US", caseLevel: caseSensitive, strength: CollationStrength.Primary);
            var filter    = BsonDocument.Parse("{ y : 'a' }");
            var subject   = new MapReduceOperation <BsonDocument>(_collectionNamespace, _mapFunction, _reduceFunction, _resultSerializer, _messageEncoderSettings)
            {
                Collation = collation,
                Filter    = filter
            };

            var cursor  = ExecuteOperation(subject, async);
            var results = ReadCursorToEnd(cursor, async);

            BsonDocument[] expectedResults;
            if (caseSensitive)
            {
                expectedResults = new[]
                {
                    BsonDocument.Parse("{ _id : 1, value : 1 }"),
                    BsonDocument.Parse("{ _id : 2, value : 4 }")
                };
            }
            else
            {
                expectedResults = new[]
                {
                    BsonDocument.Parse("{ _id : 1, value : 3 }"),
                    BsonDocument.Parse("{ _id : 2, value : 4 }")
                };
            }
            results.Should().Equal(expectedResults);
        }
        public void Densify_the_full_range_of_values_example_using_linq_should_work()
        {
            RequireServer.Check().Supports(Feature.DensifyStage);
            var collection = CreateCoffeeCollection();
            var subject    = collection.AsQueryable();

            var queryable = subject.Densify(
                field: x => x.Altitude,
                range: DensifyRange.Numeric(DensifyBounds.Full, step: 200),
                partitionByFields: x => x.Variety);

            var stages = Translate(collection, queryable);

            AssertStages(stages, "{ $densify : { field : 'Altitude', partitionByFields : ['Variety'], range : { step : 200, bounds : 'full' } } }");

            var results         = queryable.ToList().Select(r => new { Variety = r.Variety, Altitude = r.Altitude }).OrderBy(r => r.Variety).ThenBy(r => r.Altitude).ToList();
            var expectedResults = new[]
            {
                new { Variety = "Arabica Typica", Altitude = 600 },
                new { Variety = "Arabica Typica", Altitude = 750 },
                new { Variety = "Arabica Typica", Altitude = 800 },
                new { Variety = "Arabica Typica", Altitude = 950 },
                new { Variety = "Arabica Typica", Altitude = 1000 },
                new { Variety = "Arabica Typica", Altitude = 1200 },
                new { Variety = "Arabica Typica", Altitude = 1400 },
                new { Variety = "Arabica Typica", Altitude = 1600 },
                new { Variety = "Gesha", Altitude = 600 },
                new { Variety = "Gesha", Altitude = 800 },
                new { Variety = "Gesha", Altitude = 1000 },
                new { Variety = "Gesha", Altitude = 1200 },
                new { Variety = "Gesha", Altitude = 1250 },
                new { Variety = "Gesha", Altitude = 1400 },
                new { Variety = "Gesha", Altitude = 1600 },
                new { Variety = "Gesha", Altitude = 1700 }
            };

            results.Should().Equal(expectedResults);
        }