public void Authenticate_should_throw_when_server_provides_invalid_r_value( [Values(false, true)] bool async) { var randomStringGenerator = new ConstantRandomStringGenerator("fyko+d2lbbFgONRv9qkxdawL"); var subject = new ScramSha1Authenticator(__credential, randomStringGenerator); var saslStartReply = MessageHelper.BuildReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{conversationId: 1, payload: BinData(0,\"cj1meWtvLWQybGJiRmdPTlJ2OXFreGRhd0xIbytWZ2s3cXZVT0tVd3VXTElXZzRsLzlTcmFHTUhFRSxzPXJROVpZM01udEJldVAzRTFURFZDNHc9PSxpPTEwMDAw\"), done: false, ok: 1}")); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(saslStartReply); Action act; if (async) { act = () => subject.AuthenticateAsync(connection, __description, CancellationToken.None).GetAwaiter().GetResult(); } else { act = () => subject.Authenticate(connection, __description, CancellationToken.None); } act.ShouldThrow<MongoAuthenticationException>(); }
public void InitializeConnectionA_should_build_the_ConnectionDescription_correctly( [Values(false, true)] bool async) { var isMasterReply = MessageHelper.BuildReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ ok: 1 }")); var buildInfoReply = MessageHelper.BuildReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ ok: 1, version: \"2.6.3\" }")); var gleReply = MessageHelper.BuildReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ ok: 1, connectionId: 10 }")); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(isMasterReply); connection.EnqueueReplyMessage(buildInfoReply); connection.EnqueueReplyMessage(gleReply); ConnectionDescription result; if (async) { result = _subject.InitializeConnectionAsync(connection, CancellationToken.None).GetAwaiter().GetResult(); } else { result = _subject.InitializeConnection(connection, CancellationToken.None); } result.ServerVersion.Should().Be(new SemanticVersion(2, 6, 3)); result.ConnectionId.ServerValue.Should().Be(10); }
public void Authenticate_should_not_throw_when_authentication_succeeds( [Values(false, true)] bool async) { var subject = new PlainAuthenticator(__credential); var saslStartReply = MessageHelper.BuildReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{conversationId: 0, payload: BinData(0,\"\"), done: true, ok: 1}")); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(saslStartReply); var expectedRequestId = RequestMessage.CurrentGlobalRequestId + 1; Action act; if (async) { act = () => subject.AuthenticateAsync(connection, __description, CancellationToken.None).GetAwaiter().GetResult(); } else { act = () => subject.Authenticate(connection, __description, CancellationToken.None); } act.ShouldNotThrow(); SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 1, 100).Should().BeTrue(); var sentMessages = MessageHelper.TranslateMessagesToBsonDocuments(connection.GetSentMessages()); sentMessages.Count.Should().Be(1); var actualRequestId = sentMessages[0]["requestId"].AsInt32; actualRequestId.Should().BeInRange(expectedRequestId, expectedRequestId + 10); sentMessages[0].Should().Be("{opcode: \"query\", requestId: " + actualRequestId + ", database: \"source\", collection: \"$cmd\", batchSize: -1, slaveOk: true, query: {saslStart: 1, mechanism: \"PLAIN\", payload: new BinData(0, \"AHVzZXIAcGVuY2ls\")}}"); }
public void QueryByRange_AnotherSyntax() { var query = new Dictionary <string, string> { { "q", "(id:[123 TO 456])" }, { "rows", DefaultRows() }, }; var conn = new MockConnection(query); Solr.Connection = conn; Solr.Query <TestDocument>().By("id").Between(123).And(456).Run(); }
public void IsPluggedInTest() { MockConnection connection = new MockConnection(); Assert.IsTrue(powerNetwork.PlugIn(connection)); Assert.AreEqual(1, powerGrids.Count); Grid grid; Assert.IsTrue(powerNetwork.IsPluggedIn(connection, out grid)); Assert.IsNotNull(grid); }
public void QueryByRangeExclusive() { var query = new Dictionary <string, string> { { "q", "(id:{123 TO 456})" }, { "rows", DefaultRows() }, }; var conn = new MockConnection(query); Solr.Connection = conn; Solr.Query <TestDocument>().ByRange("id", 123, 456).Exclusive().Run(); }
public void QueryISolrQuery() { const string queryString = "id:123"; var conn = new MockConnection(new Dictionary <string, string> { { "q", queryString }, //{"rows", DefaultRows()}, }); Solr.Connection = conn; Solr.Query <TestDocument>(new SolrQuery(queryString)); }
public void QueryByAnyField() { var query = new Dictionary <string, string> { { "q", "(id:(123456))" }, { "rows", DefaultRows() }, }; var conn = new MockConnection(query); Solr.Connection = conn; Solr.Query <TestDocument>().By("id").Is("123456").Run(); }
public void Initialization() { var ipAddress = "192.168.10.100"; var port = "4040"; var sid = "db12c"; var userName = "******"; var userId = 123; _mockConnection = new MockConnection(ipAddress, port, sid, userName, userId); }
public void UnplugTest() { MockConnection connection = new MockConnection(); Assert.IsTrue(powerNetwork.PlugIn(connection)); Assert.AreEqual(1, powerGrids.Count); powerNetwork.Unplug(connection); Assert.AreEqual(1, powerGrids.Count); powerNetwork.Update(1.0f); Assert.AreEqual(0, powerGrids.Count); }
public void Authenticate_should_send_serverApi_with_command_wire_protocol_if_serverApi_is_provided( [Values(false, true)] bool useServerApi, [Values(false, true)] bool async) { var serverApi = useServerApi ? new ServerApi(ServerApiVersion.V1, true, true) : null; var randomStringGenerator = new ConstantRandomStringGenerator("fyko+d2lbbFgONRv9qkxdawL"); var subject = new ScramSha1Authenticator(__credential, randomStringGenerator, serverApi); var connection = new MockConnection(__serverId); var saslStartReply = RawBsonDocumentHelper.FromJson("{ conversationId : 1, payload : BinData(0,'cj1meWtvK2QybGJiRmdPTlJ2OXFreGRhd0xIbytWZ2s3cXZVT0tVd3VXTElXZzRsLzlTcmFHTUhFRSxzPXJROVpZM01udEJldVAzRTFURFZDNHc9PSxpPTEwMDAw'), done : false, ok : 1 }"); var saslContinueReply = RawBsonDocumentHelper.FromJson("{ conversationId : 1, payload : BinData(0,'dj1VTVdlSTI1SkQxeU5ZWlJNcFo0Vkh2aFo5ZTA9'), done : true, ok : 1}"); if (useServerApi) { connection.EnqueueCommandResponseMessage(MessageHelper.BuildCommandResponse(saslStartReply)); connection.EnqueueCommandResponseMessage(MessageHelper.BuildCommandResponse(saslContinueReply)); } else { connection.EnqueueReplyMessage(MessageHelper.BuildReply(saslStartReply)); connection.EnqueueReplyMessage(MessageHelper.BuildReply(saslContinueReply)); } connection.Description = __descriptionQueryWireProtocol; if (async) { subject.AuthenticateAsync(connection, __descriptionQueryWireProtocol, CancellationToken.None).GetAwaiter().GetResult(); } else { subject.Authenticate(connection, __descriptionQueryWireProtocol, CancellationToken.None); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, TimeSpan.FromSeconds(5)).Should().BeTrue(); var sentMessages = MessageHelper.TranslateMessagesToBsonDocuments(connection.GetSentMessages()); sentMessages.Count.Should().Be(2); var actualRequestId0 = sentMessages[0]["requestId"].AsInt32; var actualRequestId1 = sentMessages[1]["requestId"].AsInt32; if (useServerApi) { sentMessages[0].Should().Be($"{{opcode : \"opmsg\", requestId : {actualRequestId0}, responseTo : 0, sections : [{{ payloadType : 0, document : {{ saslStart : 1, mechanism : \"SCRAM-SHA-1\", payload : new BinData(0, \"biwsbj11c2VyLHI9ZnlrbytkMmxiYkZnT05Sdjlxa3hkYXdM\"), options : {{ skipEmptyExchange : true }}, \"$db\" : \"source\", apiVersion : \"1\", apiStrict : true, apiDeprecationErrors : true }} }}]}}"); sentMessages[1].Should().Be($"{{opcode : \"opmsg\", requestId : {actualRequestId1}, responseTo : 0, sections : [{{ payloadType : 0, document : {{ saslContinue : 1, conversationId : 1, payload : new BinData(0, \"Yz1iaXdzLHI9ZnlrbytkMmxiYkZnT05Sdjlxa3hkYXdMSG8rVmdrN3F2VU9LVXd1V0xJV2c0bC85U3JhR01IRUUscD1NQzJUOEJ2Ym1XUmNrRHc4b1dsNUlWZ2h3Q1k9\"), \"$db\" : \"source\", apiVersion : \"1\", apiStrict : true, apiDeprecationErrors : true }} }}]}}"); } else { sentMessages[0].Should().Be($"{{ opcode : \"query\", requestId : {actualRequestId0}, database : \"source\", collection : \"$cmd\", batchSize : -1, slaveOk : true, query : {{ saslStart : 1, mechanism : \"SCRAM-SHA-1\", payload : new BinData(0, \"biwsbj11c2VyLHI9ZnlrbytkMmxiYkZnT05Sdjlxa3hkYXdM\"), options : {{ \"skipEmptyExchange\" : true }} }} }}"); sentMessages[1].Should().Be($"{{ opcode : \"query\", requestId : {actualRequestId1}, database : \"source\", collection : \"$cmd\", batchSize : -1, slaveOk : true, query : {{ saslContinue : 1, conversationId : 1, payload : new BinData(0, \"Yz1iaXdzLHI9ZnlrbytkMmxiYkZnT05Sdjlxa3hkYXdMSG8rVmdrN3F2VU9LVXd1V0xJV2c0bC85U3JhR01IRUUscD1NQzJUOEJ2Ym1XUmNrRHc4b1dsNUlWZ2h3Q1k9\") }} }}"); } }
public void HighlightingFields() { var conn = new MockConnection(new Dictionary <string, string> { { "q", "(makedesc:(bmw))" }, { "hl", "true" }, { "hl.fl", "make,category" }, { "rows", DefaultRows() }, }); Solr.Connection = conn; var r = Solr.Query <TestDocument>().By("makedesc").Is("bmw").WithHighlightingFields("make", "category").Run(); }
public void UpdatesActiveNetworksOnConnectionRemoved() { ConnectionMonitor monitor = CreateConnectionMonitor(); MockNetworkStatusStrategy strategy = ((TestableNetworkManager)monitor.Networks).MockStatusStrategy; MockConnection connection = new MockConnection("Test", 10); monitor.Connections.Add(connection); strategy.LastIsAliveAddresses.Clear(); monitor.Connections.Remove(connection); Assert.AreEqual(3, strategy.LastIsAliveAddresses.Count); }
public void AuthenticateAsync_should_throw_an_AuthenticationException_when_authentication_fails() { var subject = new MongoDBCRAuthenticator(__credential); var reply = MessageHelper.BuildNoDocumentsReturnedReply<RawBsonDocument>(); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(reply); Action act = () => subject.AuthenticateAsync(connection, __description, CancellationToken.None).Wait(); act.ShouldThrow<MongoAuthenticationException>(); }
public void AuthenticateAsync_should_throw_an_AuthenticationException_when_authentication_fails() { var subject = new MongoDBX509Authenticator("CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US"); var reply = MessageHelper.BuildNoDocumentsReturnedReply<RawBsonDocument>(); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(reply); Action act = () => subject.AuthenticateAsync(connection, __description, CancellationToken.None).Wait(); act.ShouldThrow<MongoAuthenticationException>(); }
public void Authenticate_should_send_serverApi_with_command_wire_protocol_if_serverApi_is_provided( [Values(false, true)] bool useServerApi, [Values(false, true)] bool async) { var serverApi = useServerApi ? new ServerApi(ServerApiVersion.V1, true, true) : null; var subject = new PlainAuthenticator(__credential, serverApi); var connection = new MockConnection(__serverId); var saslStartReply = RawBsonDocumentHelper.FromJson("{ conversationId : 0, payload : BinData(0,\"\"), done : true, ok : 1 }"); if (useServerApi) { connection.EnqueueCommandResponseMessage(MessageHelper.BuildCommandResponse(saslStartReply)); } else { connection.EnqueueReplyMessage(MessageHelper.BuildReply(saslStartReply)); } connection.Description = __descriptionQueryWireProtocol; var expectedRequestId = RequestMessage.CurrentGlobalRequestId + 1; if (async) { subject.AuthenticateAsync(connection, __descriptionQueryWireProtocol, CancellationToken.None).GetAwaiter().GetResult(); } else { subject.Authenticate(connection, __descriptionQueryWireProtocol, CancellationToken.None); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 1, TimeSpan.FromSeconds(5)).Should().BeTrue(); var sentMessages = MessageHelper.TranslateMessagesToBsonDocuments(connection.GetSentMessages()); sentMessages.Count.Should().Be(1); var actualRequestId = sentMessages[0]["requestId"].AsInt32; actualRequestId.Should().BeInRange(expectedRequestId, expectedRequestId + 10); if (useServerApi) { sentMessages[0].Should().Be($"{{ opcode : \"opmsg\", requestId : {actualRequestId}, responseTo : 0, sections : [{{ payloadType : 0, document : {{ saslStart : 1, mechanism : \"PLAIN\", payload : new BinData(0, \"AHVzZXIAcGVuY2ls\"), \"$db\" : \"source\", apiVersion : \"1\", apiStrict : true, apiDeprecationErrors : true }} }}] }}"); } else { sentMessages[0].Should().Be($"{{ opcode : \"query\", requestId : {actualRequestId}, database : \"source\", collection : \"$cmd\", batchSize : -1, slaveOk : true, query : {{ saslStart : 1, mechanism : \"PLAIN\", payload : new BinData(0, \"AHVzZXIAcGVuY2ls\") }} }}"); } }
public void Authenticate_should_send_serverApi_with_command_wire_protocol_if_serverApi_is_provided( [Values(false, true)] bool useServerApi, [Values(false, true)] bool async) { var serverApi = useServerApi ? new ServerApi(ServerApiVersion.V1, true, true) : null; var subject = new MongoDBX509Authenticator("CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US", serverApi); var connection = new MockConnection(__serverId); if (useServerApi) { var reply = MessageHelper.BuildCommandResponse(RawBsonDocumentHelper.FromJson("{ok: 1}")); connection.EnqueueCommandResponseMessage(reply); } else { var reply = MessageHelper.BuildReply(RawBsonDocumentHelper.FromJson("{ok: 1}")); connection.EnqueueReplyMessage(reply); } connection.Description = __descriptionQueryWireProtocol; var expectedRequestId = RequestMessage.CurrentGlobalRequestId + 1; if (async) { subject.AuthenticateAsync(connection, __descriptionQueryWireProtocol, CancellationToken.None).GetAwaiter().GetResult(); } else { subject.Authenticate(connection, __descriptionQueryWireProtocol, CancellationToken.None); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 1, TimeSpan.FromSeconds(5)).Should().BeTrue(); var sentMessages = MessageHelper.TranslateMessagesToBsonDocuments(connection.GetSentMessages()); sentMessages.Count.Should().Be(1); var actualRequestId = sentMessages[0]["requestId"].AsInt32; actualRequestId.Should().BeInRange(expectedRequestId, expectedRequestId + 10); if (useServerApi) { sentMessages[0].Should().Be($"{{ \"opcode\" : \"opmsg\", \"requestId\" : {actualRequestId}, \"responseTo\" : 0, \"sections\" : [{{ \"payloadType\" : 0, \"document\" : {{ \"authenticate\" : 1, \"mechanism\" : \"MONGODB-X509\", \"user\" : \"CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US\", \"$db\" : \"$external\", \"apiVersion\" : \"1\", \"apiStrict\" : true, \"apiDeprecationErrors\" : true }} }}] }}"); } else { sentMessages[0].Should().Be($"{{ opcode : \"query\", requestId : {actualRequestId}, database : \"$external\", collection : \"$cmd\", batchSize : -1, slaveOk : true, query : {{ authenticate : 1, mechanism : \"MONGODB-X509\", user : \"CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US\" }} }}"); } }
public void AuthenticateAsync_should_throw_an_AuthenticationException_when_authentication_fails() { var subject = new MongoDBCRAuthenticator(__credential); var reply = MessageHelper.BuildNoDocumentsReturnedReply <RawBsonDocument>(); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(reply); Action act = () => subject.AuthenticateAsync(connection, __description, CancellationToken.None).Wait(); act.ShouldThrow <MongoAuthenticationException>(); }
public void TestCommitCallsTransactionCommit() { var conn = new MockConnection(); var tran = new MockTransaction(); using (var scope = new DbScope(conn, tran)) { Assert.IsFalse(tran.IsCommited); scope.Commit(); Assert.IsTrue(tran.IsCommited); Assert.IsNull(scope.Transaction); } }
public ServerMonitorTests() { _endPoint = new DnsEndPoint("localhost", 27017); _serverId = new ServerId(new ClusterId(), _endPoint); _connection = new MockConnection(); _mockConnectionFactory = new Mock<IConnectionFactory>(); _mockConnectionFactory .Setup(f => f.CreateConnection(_serverId, _endPoint)) .Returns(_connection); _capturedEvents = new EventCapturer(); _subject = new ServerMonitor(_serverId, _endPoint, _mockConnectionFactory.Object, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan, _capturedEvents); }
public void OpenAsyncWillNotBlockOnConnectionLost() { var wampChannelFactory = new WampChannelFactory <MockRaw>(mFormatter); var mockConnection = new MockConnection <MockRaw>(mFormatter); var mockControlledWampConnection = mockConnection.SideAToSideB; var wampChannel = wampChannelFactory.CreateChannel(mockControlledWampConnection); var openAsync = wampChannel.OpenAsync(); Assert.IsFalse(openAsync.IsCompleted); mockConnection.SideBToSideA.Dispose(); Assert.IsTrue(openAsync.IsCompleted); }
public void TestDiposeCallsTransactionDispose() { var conn = new MockConnection(); var tran = new MockTransaction(); using (var scope = new DbScope(conn, tran)) { Assert.IsFalse(tran.IsCommited); Assert.IsFalse(tran.IsDisposed); } Assert.IsTrue(tran.IsDisposed); }
public void OrderBy2() { const string queryString = "id:123"; var query = new Dictionary <string, string> { { "q", queryString }, { "rows", DefaultRows() }, { "sort", "id asc" }, }; var conn = new MockConnection(query); Solr.Connection = conn; Solr.Query <TestDocument>(new SolrQuery(queryString), new SortOrder("id", Order.ASC)); }
public void QueryISolrQueryWithPagination() { const string queryString = "id:123"; var query = new Dictionary <string, string> { { "q", queryString }, { "start", 10.ToString() }, { "rows", 20.ToString() } }; var conn = new MockConnection(query); Solr.Connection = conn; Solr.Query <TestDocument>(new SolrQuery(queryString), 10, 20); }
public void LoginTest2() { ILogin user2 = new LoginDto() { UserId = 18, Email = "*****@*****.**", Password = "******" }; var result2 = sut.Login(user2); Assert.IsFalse(result2); MockConnection.CloseConnection(); }
public void LoginTest1() { ILogin user = new LoginDto() { UserId = 18, Email = "*****@*****.**", Password = "******" }; var result = sut.Login(user); Assert.IsTrue(result); MockConnection.CloseConnection(); }
public void Setup() { _endPoint = new DnsEndPoint("localhost", 27017); _connection = new MockConnection(); _connectionFactory = Substitute.For<IConnectionFactory>(); _connectionFactory.CreateConnection(null, null) .ReturnsForAnyArgs(_connection); _capturedEvents = new EventCapturer(); _serverId = new ServerId(new ClusterId(), _endPoint); _subject = new ServerMonitor(_serverId, _endPoint, _connectionFactory, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan, _capturedEvents); }
public void Setup() { _endPoint = new DnsEndPoint("localhost", 27017); _connection = new MockConnection(); _connectionFactory = Substitute.For <IConnectionFactory>(); _connectionFactory.CreateConnection(null, null) .ReturnsForAnyArgs(_connection); _capturedEvents = new EventCapturer(); _serverId = new ServerId(new ClusterId(), _endPoint); _subject = new ServerMonitor(_serverId, _endPoint, _connectionFactory, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan, _capturedEvents); }
public ServerMonitorTests() { _endPoint = new DnsEndPoint("localhost", 27017); _serverId = new ServerId(new ClusterId(), _endPoint); _connection = new MockConnection(); _mockConnectionFactory = new Mock <IConnectionFactory>(); _mockConnectionFactory .Setup(f => f.CreateConnection(_serverId, _endPoint)) .Returns(_connection); _capturedEvents = new EventCapturer(); _subject = new ServerMonitor(_serverId, _endPoint, _mockConnectionFactory.Object, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan, _capturedEvents); }
public void AuthenticateAsync_should_throw_an_AuthenticationException_when_authentication_fails() { var subject = new MongoDBX509Authenticator("CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US"); var reply = MessageHelper.BuildNoDocumentsReturnedReply <RawBsonDocument>(); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(reply); Action act = () => subject.AuthenticateAsync(connection, Timeout.InfiniteTimeSpan, CancellationToken.None).Wait(); act.ShouldThrow <MongoAuthenticationException>(); }
public void AddUnactiveConnectionDoesNotAddToActiveConnectionList() { ConnectionCollection manager = new ConnectionCollection(); MockConnection connection1 = new MockConnection("Connection1", 10); MockConnection connection2 = new MockConnection("Connection2", 10); MockConnection connection3 = new MockConnection("Connection3", 10); connection1.Disconnect(); manager.Add(connection1); manager.Add(connection2); manager.Add(connection3); Assert.IsFalse(manager.ActiveConnections.Contains(connection1)); }
public void Highlighting() { var conn = new MockConnection(new Dictionary <string, string> { { "q", "((makedesc:bmw))" }, { "hl", "true" }, { "hl.fl", "make" }, { "rows", DefaultRows() }, }); Solr.Connection = conn; var r = Solr.Query <TestDocument>().By("makedesc").Is("bmw").WithHighlighting(new HighlightingParameters { Fields = new[] { "make" }, }).Run(); }
public void AuthenticateAsync_should_not_throw_when_authentication_succeeds() { var subject = new MongoDBX509Authenticator("CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US"); var reply = MessageHelper.BuildReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ok: 1}")); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(reply); Action act = () => subject.AuthenticateAsync(connection, __description, CancellationToken.None).Wait(); act.ShouldNotThrow(); }
public void InitializeConnectionA_should_build_the_ConnectionDescription_correctly( [Values("noop", "zlib", "snappy", "zstd")] string compressorType, [Values(false, true)] bool async) { var isMasterReply = MessageHelper.BuildReply <RawBsonDocument>( RawBsonDocumentHelper.FromJson($"{{ ok: 1, compression: ['{compressorType}'] }}")); var buildInfoReply = MessageHelper.BuildReply <RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ ok: 1, version: \"2.6.3\" }")); var gleReply = MessageHelper.BuildReply <RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ ok: 1, connectionId: 10 }")); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(isMasterReply); connection.EnqueueReplyMessage(buildInfoReply); connection.EnqueueReplyMessage(gleReply); ConnectionDescription result; if (async) { result = _subject.InitializeConnectionAsync(connection, CancellationToken.None).GetAwaiter().GetResult(); } else { result = _subject.InitializeConnection(connection, CancellationToken.None); } result.ServerVersion.Should().Be(new SemanticVersion(2, 6, 3)); result.ConnectionId.ServerValue.Should().Be(10); result.AvailableCompressors.Count.Should().Be(1); result.AvailableCompressors.Should().Contain(ToCompressorTypeEnum(compressorType)); CompressorType ToCompressorTypeEnum(string ct) { switch (ct) { case "noop": return(CompressorType.Noop); case "zlib": return(CompressorType.Zlib); case "snappy": return(CompressorType.Snappy); case "zstd": return(CompressorType.ZStandard); default: throw new InvalidOperationException($"Unexpected compression {compressorType}."); } } }
public void OrderBy() { var conn = new MockConnection(new Dictionary <string, string> { { "q", "(Id:(123456))" }, { "sort", "id asc" }, { "rows", DefaultRows() }, }); Solr.Connection = conn; Solr.Query <TestDocumentWithId>() .By("Id").Is("123456") .OrderBy("id") .Run(); }
private (IConnectionPool, FailPoint, ICluster) SetupConnectionData(BsonDocument test, IEventSubscriber eventSubscriber, bool isUnit) { ParseSettings(test, out var connectionPoolSettings, out var connectionSettings); IConnectionPool connectionPool; ICluster cluster = null; FailPoint failPoint = null; if (isUnit) { var endPoint = new DnsEndPoint("localhost", 27017); var serverId = new ServerId(new ClusterId(), endPoint); var connectionFactory = new Mock <IConnectionFactory>(); connectionFactory .Setup(c => c.CreateConnection(serverId, endPoint)) .Returns(() => { var connection = new MockConnection(serverId, connectionSettings, eventSubscriber); connection.Open(CancellationToken.None); return(connection); }); connectionPool = new ExclusiveConnectionPool( serverId, endPoint, connectionPoolSettings, connectionFactory.Object, eventSubscriber); connectionPool.Initialize(); } else { failPoint = ConfigureFailPoint(test, CoreTestConfiguration.Cluster); cluster = CoreTestConfiguration.CreateCluster(b => b.ConfigureConnectionPool(c => c.With( maxConnections: connectionPoolSettings.MaxConnections, minConnections: connectionPoolSettings.MinConnections, waitQueueTimeout: connectionPoolSettings.WaitQueueTimeout)) .Subscribe(eventSubscriber)); var server = cluster.SelectServer(WritableServerSelector.Instance, CancellationToken.None); connectionPool = server._connectionPool(); } return(connectionPool, failPoint, cluster); }
public void UpdateEnoughPowerTest() { MockConnection powerProducer = new MockConnection { OutputRate = 50.0f }; MockConnection firstPowerConsumer = new MockConnection { InputRate = 30.0f }; grid.PlugIn(powerProducer); grid.PlugIn(firstPowerConsumer); Assert.AreEqual(2, connections.Count); grid.Tick(); Assert.IsTrue(grid.IsOperating); }
public void AuthenticateAsync_should_not_throw_when_authentication_succeeds() { var subject = new MongoDBX509Authenticator("CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US"); var reply = MessageHelper.BuildSuccessReply <RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ok: 1}")); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(reply); Action act = () => subject.AuthenticateAsync(connection, Timeout.InfiniteTimeSpan, CancellationToken.None).Wait(); act.ShouldNotThrow(); }
public void AuthenticateAsync_should_throw_when_server_provides_invalid_r_value() { var randomStringGenerator = new ConstantRandomStringGenerator("fyko+d2lbbFgONRv9qkxdawL"); var subject = new ScramSha1Authenticator(__credential, randomStringGenerator); var saslStartReply = MessageHelper.BuildSuccessReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{conversationId: 1, payload: BinData(0,\"cj1meWtvLWQybGJiRmdPTlJ2OXFreGRhd0xIbytWZ2s3cXZVT0tVd3VXTElXZzRsLzlTcmFHTUhFRSxzPXJROVpZM01udEJldVAzRTFURFZDNHc9PSxpPTEwMDAw\"), done: false, ok: 1}")); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(saslStartReply); var currentRequestId = RequestMessage.CurrentGlobalRequestId; Action act = () => subject.AuthenticateAsync(connection, Timeout.InfiniteTimeSpan, CancellationToken.None).Wait(); act.ShouldThrow<MongoAuthenticationException>(); }
public void Welcome() { MockConnection<MockRaw> connection = new MockConnection<MockRaw>(); IWampClient client = mBuilder.Create(connection.SideAToSideB); client.Welcome("v59mbCGDXZ7WTyxB", 1, "Autobahn/0.5.1"); WampMessage<MockRaw> serialized = mOutgoingMessageHandler.Message; WampMessage<MockRaw> raw = WampV1Messages.Welcome("v59mbCGDXZ7WTyxB", 1, "Autobahn/0.5.1"); Assert.That(serialized, Is.EqualTo(raw).Using(mComparer)); }
public void CallServer_And_Receive_Call_Result() { MockListener<JToken> mockListener = new MockListener<JToken>(); Mock<IWampServer<JToken>> serverMock = new Mock<IWampServer<JToken>>(); serverMock.Setup(x => x.Call(It.IsAny<IWampClient>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<JToken[]>())) .Callback((IWampClient clientParameter, string callId, string procUrl, JToken[] arguments) => { clientParameter.CallResult(callId, new {stuff = "cool"}); }); WampListener<JToken> listener = GetListener(mockListener, serverMock.Object); Mock<IWampClient<JToken>> clientMock = new Mock<IWampClient<JToken>>(); MockConnection<JToken> connection = new MockConnection<JToken>(); IWampServer client = GetClient(connection.SideAToSideB, clientMock.Object); listener.Start(); mockListener.OnNext(connection.SideBToSideA); clientMock.Verify(x => x.Welcome(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>())); Mock<IWampClient> userClientMock = new Mock<IWampClient>(); client.Call(userClientMock.Object, "a123123", "Test", new { name = "Jack" }); serverMock.Verify(x => x.Call(It.IsAny<IWampClient>(), "a123123", "Test", It.IsAny<JToken[]>())); clientMock.Verify(x => x.CallResult("a123123", It.Is((JToken result) => result.Value<string>("stuff") == "cool"))); }
public void InitializeConnectionAsync_should_build_the_ConnectionDescription_correctly() { var isMasterReply = MessageHelper.BuildSuccessReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ ok: 1 }")); var buildInfoReply = MessageHelper.BuildSuccessReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ ok: 1, version: \"2.6.3\" }")); var gleReply = MessageHelper.BuildSuccessReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ ok: 1, connectionId: 10 }")); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(isMasterReply); connection.EnqueueReplyMessage(buildInfoReply); connection.EnqueueReplyMessage(gleReply); var result = _subject.InitializeConnectionAsync(connection, __connectionId, Timeout.InfiniteTimeSpan, CancellationToken.None).Result; result.ServerVersion.Should().Be(new SemanticVersion(2, 6, 3)); result.ConnectionId.ServerValue.Should().Be(10); }
public void AuthenticateAsync_should_not_throw_when_authentication_succeeds() { var subject = new PlainAuthenticator(__credential); var saslStartReply = MessageHelper.BuildReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{conversationId: 0, payload: BinData(0,\"\"), done: true, ok: 1}")); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(saslStartReply); var currentRequestId = RequestMessage.CurrentGlobalRequestId; Action act = () => subject.AuthenticateAsync(connection, __description, CancellationToken.None).Wait(); act.ShouldNotThrow(); var sentMessages = MessageHelper.TranslateMessagesToBsonDocuments(connection.GetSentMessages()); sentMessages.Count.Should().Be(1); sentMessages[0].Should().Be("{opcode: \"query\", requestId: " + (currentRequestId + 1) + ", database: \"source\", collection: \"$cmd\", batchSize: -1, slaveOk: true, query: {saslStart: 1, mechanism: \"PLAIN\", payload: new BinData(0, \"AHVzZXIAcGVuY2ls\")}}"); }
public void Authenticate_should_not_throw_when_authentication_succeeds( [Values(false, true)] bool async) { var randomStringGenerator = new ConstantRandomStringGenerator("fyko+d2lbbFgONRv9qkxdawL"); var subject = new ScramSha1Authenticator(__credential, randomStringGenerator); var saslStartReply = MessageHelper.BuildReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{conversationId: 1, payload: BinData(0,\"cj1meWtvK2QybGJiRmdPTlJ2OXFreGRhd0xIbytWZ2s3cXZVT0tVd3VXTElXZzRsLzlTcmFHTUhFRSxzPXJROVpZM01udEJldVAzRTFURFZDNHc9PSxpPTEwMDAw\"), done: false, ok: 1}")); var saslContinueReply = MessageHelper.BuildReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{conversationId: 1, payload: BinData(0,\"dj1VTVdlSTI1SkQxeU5ZWlJNcFo0Vkh2aFo5ZTA9\"), done: true, ok: 1}")); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(saslStartReply); connection.EnqueueReplyMessage(saslContinueReply); var expectedRequestId = RequestMessage.CurrentGlobalRequestId + 1; Action act; if (async) { act = () => subject.AuthenticateAsync(connection, __description, CancellationToken.None).GetAwaiter().GetResult(); } else { act = () => subject.Authenticate(connection, __description, CancellationToken.None); } act.ShouldNotThrow(); SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, 100).Should().BeTrue(); var sentMessages = MessageHelper.TranslateMessagesToBsonDocuments(connection.GetSentMessages()); sentMessages.Count.Should().Be(2); var actualRequestId0 = sentMessages[0]["requestId"].AsInt32; var actualRequestId1 = sentMessages[1]["requestId"].AsInt32; actualRequestId0.Should().BeInRange(expectedRequestId, expectedRequestId + 10); actualRequestId1.Should().BeInRange(actualRequestId0 + 1, actualRequestId0 + 11); sentMessages[0].Should().Be("{opcode: \"query\", requestId: " + actualRequestId0 + ", database: \"source\", collection: \"$cmd\", batchSize: -1, slaveOk: true, query: {saslStart: 1, mechanism: \"SCRAM-SHA-1\", payload: new BinData(0, \"biwsbj11c2VyLHI9ZnlrbytkMmxiYkZnT05Sdjlxa3hkYXdM\")}}"); sentMessages[1].Should().Be("{opcode: \"query\", requestId: " + actualRequestId1 + ", database: \"source\", collection: \"$cmd\", batchSize: -1, slaveOk: true, query: {saslContinue: 1, conversationId: 1, payload: new BinData(0, \"Yz1iaXdzLHI9ZnlrbytkMmxiYkZnT05Sdjlxa3hkYXdMSG8rVmdrN3F2VU9LVXd1V0xJV2c0bC85U3JhR01IRUUscD1NQzJUOEJ2Ym1XUmNrRHc4b1dsNUlWZ2h3Q1k9\")}}"); }
public void Setup() { _clusterId = new ClusterId(); _clusterConnectionMode = ClusterConnectionMode.Standalone; _connectionPool = Substitute.For<IConnectionPool>(); _connectionPoolFactory = Substitute.For<IConnectionPoolFactory>(); _connectionPoolFactory.CreateConnectionPool(null, null) .ReturnsForAnyArgs(_connectionPool); _endPoint = new DnsEndPoint("localhost", 27017); _heartbeatConnection = new MockConnection(); _heartbeatConnectionFactory = Substitute.For<IConnectionFactory>(); _heartbeatConnectionFactory.CreateConnection(null, null) .ReturnsForAnyArgs(_heartbeatConnection); _capturedEvents = new EventCapturer(); _settings = new ServerSettings(heartbeatInterval: Timeout.InfiniteTimeSpan); _subject = new ClusterableServer(_clusterId, _clusterConnectionMode, _settings, _endPoint, _connectionPoolFactory, _heartbeatConnectionFactory, _capturedEvents); }
public void Authenticate_should_not_throw_when_authentication_succeeds( [Values(false, true)] bool async) { var subject = new MongoDBCRAuthenticator(__credential); var getNonceReply = MessageHelper.BuildReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{nonce: \"2375531c32080ae8\", ok: 1}")); var authenticateReply = MessageHelper.BuildReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ok: 1}")); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(getNonceReply); connection.EnqueueReplyMessage(authenticateReply); var expectedRequestId = RequestMessage.CurrentGlobalRequestId + 1; Action act; if (async) { act = () => subject.AuthenticateAsync(connection, __description, CancellationToken.None).GetAwaiter().GetResult(); } else { act = () => subject.Authenticate(connection, __description, CancellationToken.None); } act.ShouldNotThrow(); SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, 100).Should().BeTrue(); var sentMessages = MessageHelper.TranslateMessagesToBsonDocuments(connection.GetSentMessages()); sentMessages.Count.Should().Be(2); var actualRequestId0 = sentMessages[0]["requestId"].AsInt32; var actualRequestId1 = sentMessages[1]["requestId"].AsInt32; actualRequestId0.Should().BeInRange(expectedRequestId, expectedRequestId + 10); actualRequestId1.Should().BeInRange(actualRequestId0 + 1, actualRequestId0 + 11); sentMessages[0].Should().Be("{opcode: \"query\", requestId: " + actualRequestId0 + ", database: \"source\", collection: \"$cmd\", batchSize: -1, slaveOk: true, query: {getnonce: 1}}"); sentMessages[1].Should().Be("{opcode: \"query\", requestId: " + actualRequestId1 + ", database: \"source\", collection: \"$cmd\", batchSize: -1, slaveOk: true, query: {authenticate: 1, user: \"user\", nonce: \"2375531c32080ae8\", key: \"21742f26431831d5cfca035a08c5bdf6\"}}"); }
public void Authenticate_should_throw_an_AuthenticationException_when_authentication_fails( [Values(false, true)] bool async) { var subject = new MongoDBCRAuthenticator(__credential); var reply = MessageHelper.BuildNoDocumentsReturnedReply<RawBsonDocument>(); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(reply); Action act; if (async) { act = () => subject.AuthenticateAsync(connection, __description, CancellationToken.None).GetAwaiter().GetResult(); } else { act = () => subject.Authenticate(connection, __description, CancellationToken.None); } act.ShouldThrow<MongoAuthenticationException>(); }
public void Authenticate_should_throw_an_AuthenticationException_when_authentication_fails( [Values(false, true)] bool async) { var subject = new MongoDBX509Authenticator("CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US"); var reply = MessageHelper.BuildNoDocumentsReturnedReply<RawBsonDocument>(); var connection = new MockConnection(__serverId); connection.Description = CreateConnectionDescription(new SemanticVersion(3, 2, 0)); connection.EnqueueReplyMessage(reply); Action act; if (async) { act = () => subject.AuthenticateAsync(connection, __description, CancellationToken.None).GetAwaiter().GetResult(); } else { act = () => subject.Authenticate(connection, __description, CancellationToken.None); } act.ShouldThrow<MongoAuthenticationException>(); }
public void AuthenticateAsync_should_not_throw_when_authentication_succeeds() { var subject = new MongoDBCRAuthenticator(__credential); var getNonceReply = MessageHelper.BuildReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{nonce: \"2375531c32080ae8\", ok: 1}")); var authenticateReply = MessageHelper.BuildReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ok: 1}")); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(getNonceReply); connection.EnqueueReplyMessage(authenticateReply); var currentRequestId = RequestMessage.CurrentGlobalRequestId; Action act = () => subject.AuthenticateAsync(connection, __description, CancellationToken.None).Wait(); act.ShouldNotThrow(); var sentMessages = MessageHelper.TranslateMessagesToBsonDocuments(connection.GetSentMessages()); sentMessages.Count.Should().Be(2); sentMessages[0].Should().Be("{opcode: \"query\", requestId: " + (currentRequestId + 1) + ", database: \"source\", collection: \"$cmd\", batchSize: -1, slaveOk: true, query: {getnonce: 1}}"); sentMessages[1].Should().Be("{opcode: \"query\", requestId: " + (currentRequestId + 2) + ", database: \"source\", collection: \"$cmd\", batchSize: -1, slaveOk: true, query: {authenticate: 1, user: \"user\", nonce: \"2375531c32080ae8\", key: \"21742f26431831d5cfca035a08c5bdf6\"}}"); }
public void AcquiredConnections_should_not_return_connections_to_the_pool_when_disposed_and_expired() { var createdConnections = new List<MockConnection>(); _connectionFactory.CreateConnection(null, null).ReturnsForAnyArgs(c => { var conn = new MockConnection(c.Arg<ServerId>()); createdConnections.Add(conn); return conn; }); InitializeAndWait(); var connection = _subject.AcquireConnectionAsync(CancellationToken.None).Result; _capturedEvents.Clear(); _subject.DormantCount.Should().Be(_settings.MinConnections - 1); createdConnections.ForEach(c => c.IsExpired = true); connection.Dispose(); _subject.DormantCount.Should().Be(_settings.MinConnections - 1); _capturedEvents.Next().Should().BeOfType<ConnectionPoolCheckingInConnectionEvent>(); _capturedEvents.Next().Should().BeOfType<ConnectionPoolRemovingConnectionEvent>(); _capturedEvents.Next().Should().BeOfType<ConnectionPoolRemovedConnectionEvent>(); _capturedEvents.Next().Should().BeOfType<ConnectionPoolCheckedInConnectionEvent>(); _capturedEvents.Any().Should().BeFalse(); }
public void InitializeConnectionAsync_should_invoke_authenticators_when_they_exist() { var isMasterReply = MessageHelper.BuildSuccessReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ ok: 1 }")); var buildInfoReply = MessageHelper.BuildSuccessReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ ok: 1, version: \"2.6.3\" }")); var gleReply = MessageHelper.BuildSuccessReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ ok: 1, connectionId: 10 }")); var connection = new MockConnection(__serverId); connection.EnqueueReplyMessage(isMasterReply); connection.EnqueueReplyMessage(buildInfoReply); connection.EnqueueReplyMessage(gleReply); var authenticator = Substitute.For<IAuthenticator>(); connection.Settings = new ConnectionSettings() .WithAuthenticators(new[] { authenticator }); _subject.InitializeConnectionAsync(connection, __connectionId, Timeout.InfiniteTimeSpan, CancellationToken.None).Wait(); authenticator.ReceivedWithAnyArgs().AuthenticateAsync(null, Timeout.InfiniteTimeSpan, CancellationToken.None); }
public void AcquiredConnection_should_not_return_connections_to_the_pool_when_disposed_and_expired( [Values(false, true)] bool async) { var createdConnections = new List<MockConnection>(); _mockConnectionFactory.Setup(f => f.CreateConnection(_serverId, _endPoint)) .Returns(() => { var conn = new MockConnection(_serverId); createdConnections.Add(conn); return conn; }); InitializeAndWait(); IConnectionHandle connection; if (async) { connection = _subject.AcquireConnectionAsync(CancellationToken.None).GetAwaiter().GetResult(); } else { connection = _subject.AcquireConnection(CancellationToken.None); } _capturedEvents.Clear(); _subject.DormantCount.Should().Be(_settings.MinConnections - 1); createdConnections.ForEach(c => c.IsExpired = true); connection.Dispose(); _subject.DormantCount.Should().Be(_settings.MinConnections - 1); _capturedEvents.Next().Should().BeOfType<ConnectionPoolCheckingInConnectionEvent>(); _capturedEvents.Next().Should().BeOfType<ConnectionPoolRemovingConnectionEvent>(); _capturedEvents.Next().Should().BeOfType<ConnectionPoolRemovedConnectionEvent>(); _capturedEvents.Next().Should().BeOfType<ConnectionPoolCheckedInConnectionEvent>(); _capturedEvents.Any().Should().BeFalse(); }
public void CallServer_And_Receive_Call_Result_ViaRpcClient() { MockListener<JToken> mockListener = new MockListener<JToken>(); Mock<IWampServer<JToken>> serverMock = new Mock<IWampServer<JToken>>(); serverMock.Setup(x => x.Call(It.IsAny<IWampClient>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<JToken[]>())) .Callback((IWampClient clientParameter, string callId, string procUrl, JToken[] arguments) => { clientParameter.CallResult(callId, 12); }); WampListener<JToken> listener = GetListener(mockListener, serverMock.Object); MockConnection<JToken> connection = new MockConnection<JToken>(); WampRpcClientFactory<JToken> factory = new WampRpcClientFactory<JToken>(new WampRpcSerializer(new WampDelegateProcUriMapper(x => x.Name)), new WampRpcClientHandlerBuilder<JToken>(mFormatter, new WampServerProxyFactory<JToken>(new WampServerProxyBuilder<JToken, IWampRpcClient<JToken>, IWampServer>(new WampOutgoingRequestSerializer<JToken>(mFormatter), new WampServerProxyOutgoingMessageHandlerBuilder<JToken, IWampRpcClient<JToken>>(new WampServerProxyIncomingMessageHandlerBuilder<JToken, IWampRpcClient<JToken>>(mFormatter)))))); listener.Start(); ICalculator calculator = factory.GetClient<ICalculator>(connection.SideAToSideB); mockListener.OnNext(connection.SideBToSideA); int four = 4; int sixteen = calculator.Square(four); Assert.That(sixteen, Is.EqualTo(12)); serverMock.Verify(x => x.Call(It.IsAny<IWampClient>(), It.IsAny<string>(), "Square", It.Is((JToken[] parameters) => parameters[0].Value<int>() == four))); }
public MockConnectStrategy(AbstractConnection cxn) { _cxn = (MockConnection)cxn; _dataSource = cxn.DataSource; }
public void AcquiredConnections_should_not_return_connections_to_the_pool_when_disposed_and_expired() { var createdConnections = new List<MockConnection>(); _connectionFactory.CreateConnection(null, null).ReturnsForAnyArgs(c => { var conn = new MockConnection(c.Arg<ServerId>()); createdConnections.Add(conn); return conn; }); InitializeAndWait(); var connection = _subject.AcquireConnectionAsync(Timeout.InfiniteTimeSpan, CancellationToken.None).Result; _subject.DormantCount.Should().Be(_settings.MinConnections - 1); createdConnections.ForEach(c => c.IsExpired = true); connection.Dispose(); _subject.DormantCount.Should().Be(_settings.MinConnections - 1); }
public void Authenticate_should_not_throw_when_username_is_null_and_server_support_null_username( [Values(false, true)] bool async) { var subject = new MongoDBX509Authenticator(null); var reply = MessageHelper.BuildReply<RawBsonDocument>( RawBsonDocumentHelper.FromJson("{ok: 1}")); var connection = new MockConnection(__serverId); connection.Description = CreateConnectionDescription(new SemanticVersion(3, 4, 0)); connection.EnqueueReplyMessage(reply); Exception exception; if (async) { exception = Record.Exception(() => subject.AuthenticateAsync(connection, __description, CancellationToken.None).GetAwaiter().GetResult()); } else { exception = Record.Exception(() => subject.Authenticate(connection, __description, CancellationToken.None)); } exception.Should().BeNull(); }
public void Setup() { _clusterId = new ClusterId(); _connectionPool = Substitute.For<IConnectionPool>(); _connectionPoolFactory = Substitute.For<IConnectionPoolFactory>(); _connectionPoolFactory.CreateConnectionPool(null, null) .ReturnsForAnyArgs(_connectionPool); _endPoint = new DnsEndPoint("localhost", 27017); _heartbeatConnection = new MockConnection(); _heartbeatConnectionFactory = Substitute.For<IConnectionFactory>(); _heartbeatConnectionFactory.CreateConnection(null, null) .ReturnsForAnyArgs(_heartbeatConnection); _listener = Substitute.For<IServerListener>(); _settings = new ServerSettings() .WithHeartbeatInterval(Timeout.InfiniteTimeSpan); _subject = new ClusterableServer(_settings, _clusterId, _endPoint, _connectionPoolFactory, _heartbeatConnectionFactory, _listener); }
public void CallServer_And_Receive_Call_Result_ViaRpcServer() { MockListener<JToken> mockListener = new MockListener<JToken>(); var wampRpcServiceHost = new WampRpcMetadataCatalog(); wampRpcServiceHost.Register(new MethodInfoWampRpcMetadata(new AddCalculator())); WampRpcServer<JToken> rpcServer = new WampRpcServer<JToken>(mFormatter, wampRpcServiceHost); WampListener<JToken> listener = GetListener(mockListener, rpcServer); MockConnection<JToken> connection = new MockConnection<JToken>(); WampRpcClientFactory<JToken> factory = new WampRpcClientFactory<JToken>(new WampRpcSerializer(new WampDelegateProcUriMapper(x => "http://www.yogev.com/pr/" + x.Name)), new WampRpcClientHandlerBuilder<JToken>(mFormatter, new WampServerProxyFactory<JToken>(new WampServerProxyBuilder<JToken, IWampRpcClient<JToken>, IWampServer>(new WampOutgoingRequestSerializer<JToken>(mFormatter), new WampServerProxyOutgoingMessageHandlerBuilder<JToken, IWampRpcClient<JToken>>(new WampServerProxyIncomingMessageHandlerBuilder<JToken, IWampRpcClient<JToken>>(mFormatter)))))); listener.Start(); IAddCalculator calculator = factory.GetClient<IAddCalculator>(connection.SideAToSideB); mockListener.OnNext(connection.SideBToSideA); int sixteen = calculator.Add(10, 6); Assert.That(sixteen, Is.EqualTo(16)); }