Exemplo n.º 1
0
        public void Execute_should_not_wait_for_response_when_CommandResponseHandling_is_NoResponseExpected()
        {
            var messageEncoderSettings = new MessageEncoderSettings();
            var subject = new CommandWireProtocol <BsonDocument>(
                NoCoreSession.Instance,
                ReadPreference.Primary,
                new DatabaseNamespace("test"),
                new BsonDocument("cmd", 1),
                null, // commandPayloads
                NoOpElementNameValidator.Instance,
                null, // additionalOptions
                null, // postWriteAction
                CommandResponseHandling.NoResponseExpected,
                BsonDocumentSerializer.Instance,
                messageEncoderSettings);

            var mockConnection = new Mock <IConnection>();

            var result = subject.Execute(mockConnection.Object, CancellationToken.None);

            result.Should().BeNull();

            mockConnection.Verify(
                c => c.ReceiveMessageAsync(It.IsAny <int>(), It.IsAny <IMessageEncoderSelector>(), messageEncoderSettings, CancellationToken.None),
                Times.Once);
        }
Exemplo n.º 2
0
        public void Execute_should_wait_for_response_when_CommandResponseHandling_is_Return()
        {
            var messageEncoderSettings = new MessageEncoderSettings();
            var subject = new CommandWireProtocol <BsonDocument>(
                NoCoreSession.Instance,
                ReadPreference.Primary,
                new DatabaseNamespace("test"),
                new BsonDocument("cmd", 1),
                null, // commandPayloads
                NoOpElementNameValidator.Instance,
                null, // additionalOptions
                null, // postWriteAction
                CommandResponseHandling.Return,
                BsonDocumentSerializer.Instance,
                messageEncoderSettings);

            var mockConnection = new Mock <IConnection>();

            var commandResponse = MessageHelper.BuildReply(CreateRawBsonDocument(new BsonDocument("ok", 1)));

            mockConnection
            .Setup(c => c.ReceiveMessage(It.IsAny <int>(), It.IsAny <IMessageEncoderSelector>(), messageEncoderSettings, CancellationToken.None))
            .Returns(commandResponse);

            var result = subject.Execute(mockConnection.Object, CancellationToken.None);

            result.Should().Be("{ok: 1}");
        }
Exemplo n.º 3
0
        public void Execute_should_use_serverApi_in_transaction(
            [Values(false, true)] bool useServerApi,
            [Values(false, true)] bool async)
        {
            var serverApi = useServerApi ? new ServerApi(ServerApiVersion.V1, true, true) : null;

            var connection = new MockConnection();

            connection.Description = __connectionDescription;
            var commandResponse = MessageHelper.BuildCommandResponse(CreateRawBsonDocument(new BsonDocument("ok", 1)));

            connection.EnqueueCommandResponseMessage(commandResponse);
            var subject = new CommandWireProtocol <BsonDocument>(
                CreateMockSessionInTransaction(),
                ReadPreference.Primary,
                new DatabaseNamespace("test"),
                new BsonDocument("moreGet", 1),
                commandPayloads: null,
                NoOpElementNameValidator.Instance,
                additionalOptions: null,
                postWriteAction: null,
                CommandResponseHandling.Return,
                BsonDocumentSerializer.Instance,
                new MessageEncoderSettings(),
                serverApi);

            if (async)
            {
                subject.ExecuteAsync(connection, CancellationToken.None).GetAwaiter().GetResult();
            }
            else
            {
                subject.Execute(connection, CancellationToken.None);
            }

            SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 1, TimeSpan.FromSeconds(4)).Should().BeTrue();

            var sentMessages = MessageHelper.TranslateMessagesToBsonDocuments(connection.GetSentMessages());

            sentMessages.Count.Should().Be(1);
            var actualRequestId         = sentMessages[0]["requestId"].AsInt32;
            var expectedServerApiString = useServerApi ? ", apiVersion : \"1\", apiStrict : true, apiDeprecationErrors : true" : "";

            sentMessages[0].Should().Be($"{{ opcode : \"opmsg\", requestId : {actualRequestId}, responseTo : 0, sections : [ {{ payloadType : 0, document : {{ moreGet : 1, $db : \"test\", txnNumber : NumberLong(1), autocommit : false{expectedServerApiString} }} }} ] }}");

            ICoreSession CreateMockSessionInTransaction()
            {
                var transaction = new CoreTransaction(1, new TransactionOptions());

                transaction.SetState(CoreTransactionState.InProgress);

                var mockSession = new Mock <ICoreSession>();

                mockSession.SetupGet(m => m.CurrentTransaction).Returns(transaction);
                mockSession.SetupGet(m => m.IsInTransaction).Returns(true);

                return(mockSession.Object);
            }
        }
        public void Execute_should_not_wait_for_response_when_CommandResponseHandling_is_Ignore()
        {
            var subject = new CommandWireProtocol <BsonDocument>(
                new DatabaseNamespace("test"),
                new BsonDocument("cmd", 1),
                NoOpElementNameValidator.Instance,
                () => CommandResponseHandling.Ignore,
                true,
                BsonDocumentSerializer.Instance,
                new MessageEncoderSettings());

            var connection = Substitute.For <IConnection>();

            var result = subject.Execute(connection, CancellationToken.None);

            result.Should().BeNull();

            connection.ReceivedWithAnyArgs().ReceiveMessageAsync(0, null, null, CancellationToken.None);
        }
        public void Execute_should_wait_for_response_when_CommandResponseHandling_is_Return()
        {
            var subject = new CommandWireProtocol <BsonDocument>(
                new DatabaseNamespace("test"),
                new BsonDocument("cmd", 1),
                NoOpElementNameValidator.Instance,
                () => CommandResponseHandling.Return,
                true,
                BsonDocumentSerializer.Instance,
                new MessageEncoderSettings());

            var connection = Substitute.For <IConnection>();

            var cmdResponse = MessageHelper.BuildReply(CreateRawBsonDocument(new BsonDocument("ok", 1)));

            connection.ReceiveMessage(0, null, null, CancellationToken.None).ReturnsForAnyArgs(cmdResponse);

            var result = subject.Execute(connection, CancellationToken.None);

            result.Should().Be("{ok: 1}");
        }
        public void Execute_should_not_wait_for_response_when_CommandResponseHandling_is_Ignore()
        {
            var messageEncoderSettings = new MessageEncoderSettings();
            var subject = new CommandWireProtocol <BsonDocument>(
                new DatabaseNamespace("test"),
                new BsonDocument("cmd", 1),
                NoOpElementNameValidator.Instance,
                () => CommandResponseHandling.Ignore,
                true,
                BsonDocumentSerializer.Instance,
                messageEncoderSettings);

            var mockConnection = new Mock <IConnection>();

            var result = subject.Execute(mockConnection.Object, CancellationToken.None);

            result.Should().BeNull();

            mockConnection.Verify(
                c => c.ReceiveMessageAsync(It.IsAny <int>(), It.IsAny <IMessageEncoderSelector>(), messageEncoderSettings, CancellationToken.None),
                Times.Once);
        }
Exemplo n.º 7
0
        public void Execute_should_use_cached_IWireProtocol_if_available([Values(false, true)] bool withSameConnection)
        {
            var session          = NoCoreSession.Instance;
            var responseHandling = CommandResponseHandling.Return;

            var messageEncoderSettings = new MessageEncoderSettings();
            var subject = new CommandWireProtocol <BsonDocument>(
                session,
                ReadPreference.Primary,
                new DatabaseNamespace("test"),
                new BsonDocument("cmd", 1),
                null, // commandPayloads
                NoOpElementNameValidator.Instance,
                null, // additionalOptions
                null, // postWriteAction
                responseHandling,
                BsonDocumentSerializer.Instance,
                messageEncoderSettings);

            var mockConnection  = new Mock <IConnection>();
            var commandResponse = MessageHelper.BuildCommandResponse(CreateRawBsonDocument(new BsonDocument("ok", 1)));
            var connectionId    = SetupConnection(mockConnection);

            var result = subject.Execute(mockConnection.Object, CancellationToken.None);

            var cachedWireProtocol = subject._cachedWireProtocol();

            cachedWireProtocol.Should().NotBeNull();
            var cachedConnectionId = subject._cachedConnectionId();

            cachedConnectionId.Should().NotBeNull();
            subject._cachedConnectionId().Should().BeSameAs(connectionId);
            result.Should().Be("{ ok : 1 }");

            commandResponse = MessageHelper.BuildCommandResponse(CreateRawBsonDocument(new BsonDocument("ok", 1)));
            _ = SetupConnection(mockConnection, connectionId);
            subject._responseHandling(CommandResponseHandling.Ignore); // will trigger the exception if the CommandUsingCommandMessageWireProtocol ctor will be called

            result = null;
            var exception = Record.Exception(() => { result = subject.Execute(mockConnection.Object, CancellationToken.None); });

            if (withSameConnection)
            {
                exception.Should().BeNull();
                subject._cachedWireProtocol().Should().BeSameAs(cachedWireProtocol);
                subject._cachedConnectionId().Should().BeSameAs(connectionId);
                result.Should().Be("{ ok : 1 }");
            }
            else
            {
                var e = exception.Should().BeOfType <ArgumentException>().Subject;
                e.Message.Should().Be("CommandResponseHandling must be Return, NoneExpected or ExhaustAllowed.\r\nParameter name: responseHandling");
                subject._cachedConnectionId().Should().NotBeSameAs(cachedWireProtocol);
                subject._cachedConnectionId().Should().NotBeSameAs(connectionId);
                result.Should().BeNull();
            }

            ConnectionId SetupConnection(Mock <IConnection> connection, ConnectionId id = null)
            {
                if (id == null || !withSameConnection)
                {
                    id = new ConnectionId(new ServerId(new ClusterId(IdGenerator <ClusterId> .GetNextId()), new DnsEndPoint("localhost", 27017)));
                }

                connection
                .Setup(c => c.ReceiveMessage(It.IsAny <int>(), It.IsAny <IMessageEncoderSelector>(), messageEncoderSettings, CancellationToken.None))
                .Returns(commandResponse);
                connection.SetupGet(c => c.ConnectionId).Returns(id);
                connection
                .SetupGet(c => c.Description)
                .Returns(
                    new ConnectionDescription(
                        id,
                        new IsMasterResult(new BsonDocument("ok", 1)),
                        new BuildInfoResult(new BsonDocument("version", "4.4"))));
                return(id);
            }
        }