Exemple #1
0
        internal void ShouldInvalidateServer_should_return_expected_result_for_MongoCommandException(ServerErrorCode?code, string message, bool expectedResult)
        {
            _subject.Initialize();
            var clusterId     = new ClusterId(1);
            var serverId      = new ServerId(clusterId, new DnsEndPoint("localhost", 27017));
            var connectionId  = new ConnectionId(serverId);
            var command       = new BsonDocument("command", 1);
            var commandResult = new BsonDocument
            {
                { "ok", 0 },
                { "code", () => (int)code.Value, code.HasValue },
                { "errmsg", message, message != null }
            };
            var exception =
                ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(connectionId, command, commandResult, "errmsg") ??
                new MongoCommandException(connectionId, "message", command, commandResult); // this needs for cases when we have just a random exception

            var result = _subject.ShouldInvalidateServer(Mock.Of <IConnection>(), exception, new ServerDescription(_subject.ServerId, _subject.EndPoint), out _);

            result.Should().Be(expectedResult);
        }
Exemple #2
0
        // constructors
        public Server(ClusterId clusterId, IClusterClock clusterClock, ClusterConnectionMode clusterConnectionMode, ServerSettings settings, EndPoint endPoint, IConnectionPoolFactory connectionPoolFactory, IServerMonitorFactory serverMonitorFactory, IEventSubscriber eventSubscriber)
        {
            Ensure.IsNotNull(clusterId, nameof(clusterId));
            _clusterClock          = Ensure.IsNotNull(clusterClock, nameof(clusterClock));
            _clusterConnectionMode = clusterConnectionMode;
            _settings = Ensure.IsNotNull(settings, nameof(settings));
            _endPoint = Ensure.IsNotNull(endPoint, nameof(endPoint));
            Ensure.IsNotNull(connectionPoolFactory, nameof(connectionPoolFactory));
            Ensure.IsNotNull(serverMonitorFactory, nameof(serverMonitorFactory));
            Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));

            _serverId       = new ServerId(clusterId, endPoint);
            _connectionPool = connectionPoolFactory.CreateConnectionPool(_serverId, endPoint);
            _state          = new InterlockedInt32(State.Initial);
            _monitor        = serverMonitorFactory.Create(_serverId, _endPoint);

            eventSubscriber.TryGetEventHandler(out _openingEventHandler);
            eventSubscriber.TryGetEventHandler(out _openedEventHandler);
            eventSubscriber.TryGetEventHandler(out _closingEventHandler);
            eventSubscriber.TryGetEventHandler(out _closedEventHandler);
            eventSubscriber.TryGetEventHandler(out _descriptionChangedEventHandler);
        }
 public ServerMonitor(
     ServerId serverId,
     EndPoint endPoint,
     IConnectionFactory connectionFactory,
     ServerMonitorSettings serverMonitorSettings,
     IEventSubscriber eventSubscriber,
     ServerApi serverApi)
     : this(
         serverId,
         endPoint,
         connectionFactory,
         serverMonitorSettings,
         eventSubscriber,
         roundTripTimeMonitor : new RoundTripTimeMonitor(
             connectionFactory,
             serverId,
             endPoint,
             Ensure.IsNotNull(serverMonitorSettings, nameof(serverMonitorSettings)).HeartbeatInterval,
             serverApi),
         serverApi)
 {
 }
Exemple #4
0
 public ServerDescription(
     ServerId serverId,
     EndPoint endPoint,
     ServerState state,
     ServerType type,
     TimeSpan averageRoundTripTime,
     ReplicaSetConfig replicaSetConfig,
     TagSet tags,
     SemanticVersion version,
     Range <int> wireVersionRange)
     : this(
         averageRoundTripTime,
         endPoint,
         replicaSetConfig,
         serverId,
         state,
         tags,
         type,
         version,
         wireVersionRange)
 {
 }
Exemple #5
0
        // constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="ServerDescription"/> class.
        /// </summary>
        /// <param name="serverId">The server identifier.</param>
        /// <param name="endPoint">The end point.</param>
        /// <param name="averageRoundTripTime">The average round trip time.</param>
        /// <param name="heartbeatException">The heartbeat exception.</param>
        /// <param name="maxBatchCount">The maximum batch count.</param>
        /// <param name="maxDocumentSize">The maximum size of a document.</param>
        /// <param name="maxMessageSize">The maximum size of a message.</param>
        /// <param name="maxWireDocumentSize">The maximum size of a wire document.</param>
        /// <param name="replicaSetConfig">The replica set configuration.</param>
        /// <param name="state">The server state.</param>
        /// <param name="tags">The replica set tags.</param>
        /// <param name="type">The server type.</param>
        /// <param name="version">The server version.</param>
        /// <param name="wireVersionRange">The wire version range.</param>
        public ServerDescription(
            ServerId serverId,
            EndPoint endPoint,
            Optional <TimeSpan> averageRoundTripTime     = default(Optional <TimeSpan>),
            Optional <Exception> heartbeatException      = default(Optional <Exception>),
            Optional <int> maxBatchCount                 = default(Optional <int>),
            Optional <int> maxDocumentSize               = default(Optional <int>),
            Optional <int> maxMessageSize                = default(Optional <int>),
            Optional <int> maxWireDocumentSize           = default(Optional <int>),
            Optional <ReplicaSetConfig> replicaSetConfig = default(Optional <ReplicaSetConfig>),
            Optional <ServerState> state                 = default(Optional <ServerState>),
            Optional <TagSet> tags                   = default(Optional <TagSet>),
            Optional <ServerType> type               = default(Optional <ServerType>),
            Optional <SemanticVersion> version       = default(Optional <SemanticVersion>),
            Optional <Range <int> > wireVersionRange = default(Optional <Range <int> >))
        {
            Ensure.IsNotNull(endPoint, "endPoint");
            Ensure.IsNotNull(serverId, "serverId");
            if (!EndPointHelper.Equals(endPoint, serverId.EndPoint))
            {
                throw new ArgumentException("EndPoint and ServerId.EndPoint must match.");
            }

            _averageRoundTripTime = averageRoundTripTime.WithDefault(TimeSpan.Zero);
            _endPoint             = endPoint;
            _heartbeatException   = heartbeatException.WithDefault(null);
            _maxBatchCount        = maxBatchCount.WithDefault(1000);
            _maxDocumentSize      = maxDocumentSize.WithDefault(4 * 1024 * 1024);
            _maxMessageSize       = maxMessageSize.WithDefault(Math.Max(_maxDocumentSize + 1024, 16000000));
            _maxWireDocumentSize  = maxWireDocumentSize.WithDefault(_maxDocumentSize + 16 * 1024);
            _replicaSetConfig     = replicaSetConfig.WithDefault(null);
            _serverId             = serverId;
            _state            = state.WithDefault(ServerState.Disconnected);
            _tags             = tags.WithDefault(null);
            _type             = type.WithDefault(ServerType.Unknown);
            _version          = version.WithDefault(null);
            _wireVersionRange = wireVersionRange.WithDefault(null);
        }
Exemple #6
0
        internal void ShouldInvalidateServer_should_return_expected_result_for_MongoWriteConcernException(ServerErrorCode?code, string message, bool expectedResult)
        {
            _subject.Initialize();
            var clusterId     = new ClusterId(1);
            var serverId      = new ServerId(clusterId, new DnsEndPoint("localhost", 27017));
            var connectionId  = new ConnectionId(serverId);
            var command       = new BsonDocument("command", 1);
            var commandResult = new BsonDocument
            {
                { "ok", 1 },
                { "writeConcernError", new BsonDocument
                  {
                      { "code", () => (int)code.Value, code.HasValue },
                      { "errmsg", message, message != null }
                  } }
            };
            var writeConcernResult = new WriteConcernResult(commandResult);
            var exception          = new MongoWriteConcernException(connectionId, "message", writeConcernResult);

            var result = _subject.ShouldInvalidateServer(Mock.Of <IConnection>(), exception, new ServerDescription(_subject.ServerId, _subject.EndPoint), out _);

            result.Should().Be(expectedResult);
        }
        internal void ShouldInvalidateServer_should_return_expected_result_for_exceptionType(string exceptionTypeName, bool expectedResult)
        {
            _subject.Initialize();
            Exception exception;
            var       clusterId     = new ClusterId(1);
            var       serverId      = new ServerId(clusterId, new DnsEndPoint("localhost", 27017));
            var       connectionId  = new ConnectionId(serverId);
            var       command       = new BsonDocument("command", 1);
            var       commandResult = new BsonDocument("ok", 1);

            switch (exceptionTypeName)
            {
            case nameof(EndOfStreamException): exception = new EndOfStreamException(); break;

            case nameof(Exception): exception = new Exception(); break;

            case nameof(IOException): exception = new IOException(); break;

            case nameof(MongoConnectionException): exception = new MongoConnectionException(connectionId, "message"); break;

            case nameof(MongoNodeIsRecoveringException): exception = new MongoNodeIsRecoveringException(connectionId, command, commandResult); break;

            case nameof(MongoNotPrimaryException): exception = new MongoNotPrimaryException(connectionId, command, commandResult); break;

            case nameof(SocketException): exception = new SocketException(); break;

            case nameof(TimeoutException): exception = new TimeoutException(); break;

            case nameof(MongoExecutionTimeoutException): exception = new MongoExecutionTimeoutException(connectionId, "message"); break;

            default: throw new Exception($"Invalid exceptionTypeName: {exceptionTypeName}.");
            }

            var result = _subject.ShouldInvalidateServer(exception);

            result.Should().Be(expectedResult);
        }
        // constructors
        public ClusterableServer(ClusterId clusterId, ClusterConnectionMode clusterConnectionMode, ServerSettings settings, EndPoint endPoint, IConnectionPoolFactory connectionPoolFactory, IConnectionFactory heartbeatConnectionFactory, IEventSubscriber eventSubscriber)
        {
            Ensure.IsNotNull(clusterId, nameof(clusterId));
            _clusterConnectionMode = clusterConnectionMode;
            _settings = Ensure.IsNotNull(settings, nameof(settings));;
            _endPoint = Ensure.IsNotNull(endPoint, nameof(endPoint));
            Ensure.IsNotNull(connectionPoolFactory, nameof(connectionPoolFactory));
            _heartbeatConnectionFactory = Ensure.IsNotNull(heartbeatConnectionFactory, nameof(heartbeatConnectionFactory));
            Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));

            _serverId        = new ServerId(clusterId, endPoint);
            _baseDescription = _currentDescription = new ServerDescription(_serverId, endPoint);
            _connectionPool  = connectionPoolFactory.CreateConnectionPool(_serverId, endPoint);
            _state           = new InterlockedInt32(State.Initial);

            eventSubscriber.TryGetEventHandler(out _openingEventHandler);
            eventSubscriber.TryGetEventHandler(out _openedEventHandler);
            eventSubscriber.TryGetEventHandler(out _closingEventHandler);
            eventSubscriber.TryGetEventHandler(out _closedEventHandler);
            eventSubscriber.TryGetEventHandler(out _heartbeatStartedEventHandler);
            eventSubscriber.TryGetEventHandler(out _heartbeatSucceededEventHandler);
            eventSubscriber.TryGetEventHandler(out _heartbeatFailedEventHandler);
            eventSubscriber.TryGetEventHandler(out _descriptionChangedEventHandler);
        }
        // constructors
        public Server(
            ClusterId clusterId,
            IClusterClock clusterClock,
#pragma warning disable CS0618 // Type or member is obsolete
            ClusterConnectionMode clusterConnectionMode,
            ConnectionModeSwitch connectionModeSwitch,
#pragma warning restore CS0618 // Type or member is obsolete
            bool?directConnection,
            ServerSettings settings,
            EndPoint endPoint,
            IConnectionPoolFactory connectionPoolFactory,
            IEventSubscriber eventSubscriber,
            ServerApi serverApi)
        {
            ClusterConnectionModeHelper.EnsureConnectionModeValuesAreValid(clusterConnectionMode, connectionModeSwitch, directConnection);

            _clusterClock          = Ensure.IsNotNull(clusterClock, nameof(clusterClock));
            _clusterConnectionMode = clusterConnectionMode;
            _connectionModeSwitch  = connectionModeSwitch;
            _directConnection      = directConnection;
            _settings = Ensure.IsNotNull(settings, nameof(settings));
            _endPoint = Ensure.IsNotNull(endPoint, nameof(endPoint));
            Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));

            _serverId                   = new ServerId(clusterId, endPoint);
            _connectionPool             = Ensure.IsNotNull(connectionPoolFactory, nameof(connectionPoolFactory)).CreateConnectionPool(_serverId, endPoint);
            _state                      = new InterlockedInt32(State.Initial);
            _serverApi                  = serverApi;
            _outstandingOperationsCount = 0;

            eventSubscriber.TryGetEventHandler(out _openingEventHandler);
            eventSubscriber.TryGetEventHandler(out _openedEventHandler);
            eventSubscriber.TryGetEventHandler(out _closingEventHandler);
            eventSubscriber.TryGetEventHandler(out _closedEventHandler);
            eventSubscriber.TryGetEventHandler(out _descriptionChangedEventHandler);
        }
Exemple #10
0
        public void HandleChannelException_should_update_topology_as_expected_on_network_error_or_timeout(
            string errorType, bool shouldUpdateTopology)
        {
            var       serverId     = new ServerId(_clusterId, _endPoint);
            var       connectionId = new ConnectionId(serverId);
            Exception innerMostException;

            switch (errorType)
            {
            case "MongoConnectionExceptionWithSocketTimeout":
                innerMostException = new SocketException((int)SocketError.TimedOut);
                break;

            case nameof(MongoConnectionException):
                innerMostException = new SocketException((int)SocketError.NetworkUnreachable);
                break;

            default: throw new ArgumentException("Unknown error type.");
            }

            var operationUsingChannelException = new MongoConnectionException(connectionId, "Oops", new IOException("Cry", innerMostException));
            var mockConnection = new Mock <IConnectionHandle>();
            var isMasterResult = new IsMasterResult(new BsonDocument {
                { "compressors", new BsonArray() }
            });
            // the server version doesn't matter when we're not testing MongoNotPrimaryExceptions, but is needed when
            // Server calls ShouldClearConnectionPoolForException
            var buildInfoResult = new BuildInfoResult(new BsonDocument {
                { "version", "4.4.0" }
            });

            mockConnection.SetupGet(c => c.Description)
            .Returns(new ConnectionDescription(new ConnectionId(serverId, 0), isMasterResult, buildInfoResult));
            var mockConnectionPool = new Mock <IConnectionPool>();

            mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny <CancellationToken>())).Returns(mockConnection.Object);
            mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny <CancellationToken>())).ReturnsAsync(mockConnection.Object);
            var mockConnectionPoolFactory = new Mock <IConnectionPoolFactory>();

            mockConnectionPoolFactory
            .Setup(f => f.CreateConnectionPool(It.IsAny <ServerId>(), _endPoint))
            .Returns(mockConnectionPool.Object);
            var mockMonitorServerInitialDescription = new ServerDescription(serverId, _endPoint).With(reasonChanged: "Initial D", type: ServerType.Unknown);
            var mockServerMonitor = new Mock <IServerMonitor>();

            mockServerMonitor.SetupGet(m => m.Description).Returns(mockMonitorServerInitialDescription);
            mockServerMonitor.SetupGet(m => m.Lock).Returns(new object());
            var mockServerMonitorFactory = new Mock <IServerMonitorFactory>();

            mockServerMonitorFactory.Setup(f => f.Create(It.IsAny <ServerId>(), _endPoint)).Returns(mockServerMonitor.Object);
            var subject = new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, mockConnectionPoolFactory.Object, mockServerMonitorFactory.Object, _capturedEvents, _serverApi);

            subject.Initialize();
            var heartbeatDescription = mockMonitorServerInitialDescription.With(reasonChanged: "Heartbeat", type: ServerType.Standalone);

            mockServerMonitor.Setup(m => m.Description).Returns(heartbeatDescription);
            mockServerMonitor.Raise(
                m => m.DescriptionChanged += null,
                new ServerDescriptionChangedEventArgs(mockMonitorServerInitialDescription, heartbeatDescription));
            subject.Description.Should().Be(heartbeatDescription);

            subject.HandleChannelException(mockConnection.Object, operationUsingChannelException);

            if (shouldUpdateTopology)
            {
                subject.Description.Type.Should().Be(ServerType.Unknown);
                subject.Description.ReasonChanged.Should().Contain("ChannelException");
            }
            else
            {
                subject.Description.Should().Be(heartbeatDescription);
            }
        }
Exemple #11
0
        public void ToString_should_return_string_representation()
        {
            var subject = new ServerId(__clusterId, __endPoint);

            subject.ToString().Should().Be("{ ClusterId : 1, EndPoint : \"Unspecified/localhost:27017\" }");
        }
 /// <inheritdoc/>
 public IServerMonitor Create(ServerId serverId, EndPoint endPoint)
 {
     return(new ServerMonitor(serverId, endPoint, _connectionFactory, _serverMonitorSettings, _eventSubscriber, _serverApi));
 }
        public void Equals_should_return_false_when_any_field_is_not_equal(string notEqualField)
        {
            var averageRoundTripTime = TimeSpan.FromSeconds(1);
            var canonicalEndPoint    = new DnsEndPoint("localhost", 27017);
            var electionId           = new ElectionId(ObjectId.GenerateNewId());
            var endPoint             = new DnsEndPoint("localhost", 27017);
            var helloOk               = false;
            var lastUpdateTimestamp   = DateTime.UtcNow;
            var logicalSessionTimeout = TimeSpan.FromMinutes(1);
            var replicaSetConfig      = new ReplicaSetConfig(
                new[] { new DnsEndPoint("localhost", 27017), new DnsEndPoint("localhost", 27018) },
                "name",
                new DnsEndPoint("localhost", 27017),
                1);
            var serverId         = new ServerId(__clusterId, endPoint);
            var state            = ServerState.Connected;
            var tags             = new TagSet(new[] { new Tag("x", "a") });
            var type             = ServerType.ReplicaSetPrimary;
            var version          = new SemanticVersion(3, 6, 0);
            var wireVersionRange = new Range <int>(6, 14);

            var subject = new ServerDescription(
                serverId,
                endPoint,
                state: state,
                type: type,
                averageRoundTripTime: averageRoundTripTime,
                canonicalEndPoint: canonicalEndPoint,
                electionId: electionId,
                helloOk: helloOk,
                lastUpdateTimestamp: lastUpdateTimestamp,
                logicalSessionTimeout: logicalSessionTimeout,
                replicaSetConfig: replicaSetConfig,
                tags: tags,
                version: version,
                wireVersionRange: wireVersionRange);

            switch (notEqualField)
            {
            case "AverageRoundTripTime": averageRoundTripTime = averageRoundTripTime.Add(TimeSpan.FromSeconds(1)); break;

            case "CanonicalEndPoint": canonicalEndPoint = new DnsEndPoint("localhost", 27018); break;

            case "ElectionId": electionId = new ElectionId(ObjectId.Empty); break;

            case "EndPoint": endPoint = new DnsEndPoint(endPoint.Host, endPoint.Port + 1); serverId = new ServerId(__clusterId, endPoint); break;

            case "HelloOk": helloOk = !helloOk; break;

            case "LogicalSessionTimeout": logicalSessionTimeout = TimeSpan.FromMinutes(2); break;

            case "ReplicaSetConfig": replicaSetConfig = new ReplicaSetConfig(replicaSetConfig.Members, "newname", replicaSetConfig.Primary, replicaSetConfig.Version); break;

            case "State": state = ServerState.Disconnected; break;

            case "ServerId": serverId = new ServerId(new ClusterId(), endPoint); break;

            case "Tags": tags = new TagSet(new[] { new Tag("x", "b") }); break;

            case "Type": type = ServerType.ReplicaSetSecondary; break;

            case "Version": version = new SemanticVersion(version.Major, version.Minor, version.Patch + 1); break;

            case "WireVersionRange": wireVersionRange = new Range <int>(0, 0); break;
            }

            var serverDescription2 = new ServerDescription(
                serverId,
                endPoint,
                state: state,
                type: type,
                averageRoundTripTime: averageRoundTripTime,
                canonicalEndPoint: canonicalEndPoint,
                electionId: electionId,
                helloOk: helloOk,
                lastUpdateTimestamp: lastUpdateTimestamp,
                logicalSessionTimeout: logicalSessionTimeout,
                replicaSetConfig: replicaSetConfig,
                tags: tags,
                version: version,
                wireVersionRange: wireVersionRange);

            subject.Equals(serverDescription2).Should().BeFalse();
            subject.Equals((object)serverDescription2).Should().BeFalse();
            subject.GetHashCode().Should().NotBe(serverDescription2.GetHashCode());
        }
Exemple #14
0
        public void GetChannel_should_update_topology_and_clear_connection_pool_on_network_error_or_timeout(
            [Values("timedout", "networkunreachable")] string errorType,
            [Values(false, true)] bool async)
        {
            var serverId           = new ServerId(_clusterId, _endPoint);
            var connectionId       = new ConnectionId(serverId);
            var innerMostException = CoreExceptionHelper.CreateSocketException(errorType);

            var openConnectionException = new MongoConnectionException(connectionId, "Oops", new IOException("Cry", innerMostException));
            var mockConnection          = new Mock <IConnectionHandle>();

            mockConnection.Setup(c => c.Open(It.IsAny <CancellationToken>())).Throws(openConnectionException);
            mockConnection.Setup(c => c.OpenAsync(It.IsAny <CancellationToken>())).ThrowsAsync(openConnectionException);
            var mockConnectionPool = new Mock <IConnectionPool>();

            mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny <CancellationToken>())).Returns(mockConnection.Object);
            mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny <CancellationToken>())).ReturnsAsync(mockConnection.Object);
            var mockConnectionPoolFactory = new Mock <IConnectionPoolFactory>();

            mockConnectionPoolFactory
            .Setup(f => f.CreateConnectionPool(It.IsAny <ServerId>(), _endPoint))
            .Returns(mockConnectionPool.Object);
            var mockMonitorServerDescription = new ServerDescription(serverId, _endPoint);
            var mockServerMonitor            = new Mock <IServerMonitor>();

            mockServerMonitor.SetupGet(m => m.Description).Returns(mockMonitorServerDescription);
            mockServerMonitor
            .Setup(m => m.Invalidate(It.IsAny <string>()))
            .Callback((string reason) => MockMonitorInvalidate(reason));
            var mockServerMonitorFactory = new Mock <IServerMonitorFactory>();

            mockServerMonitorFactory.Setup(f => f.Create(It.IsAny <ServerId>(), _endPoint)).Returns(mockServerMonitor.Object);

            var subject = new Server(_clusterId, _clusterClock, _clusterConnectionMode, _settings, _endPoint, mockConnectionPoolFactory.Object, mockServerMonitorFactory.Object, _capturedEvents);

            subject.Initialize();

            IChannelHandle channel = null;
            Exception      exception;

            if (async)
            {
                exception = Record.Exception(() => channel = subject.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult());
            }
            else
            {
                exception = Record.Exception(() => channel = subject.GetChannel(CancellationToken.None));
            }

            channel.Should().BeNull();
            exception.Should().Be(openConnectionException);
            subject.Description.Type.Should().Be(ServerType.Unknown);
            subject.Description.ReasonChanged.Should().Contain("ChannelException during handshake");
            mockServerMonitor.Verify(m => m.Invalidate(It.IsAny <string>()), Times.Once);
            mockConnectionPool.Verify(p => p.Clear(), Times.Once);

            void MockMonitorInvalidate(string reason)
            {
                var currentDescription = mockServerMonitor.Object.Description;

                mockServerMonitor.SetupGet(m => m.Description).Returns(currentDescription.With(reason));
            }
        }
Exemple #15
0
        public void Equals_should_return_false_when_any_field_is_not_equal(string notEqualField)
        {
            var averageRoundTripTime = TimeSpan.FromSeconds(1);
            var endPoint             = new DnsEndPoint("localhost", 27017);
            var replicaSetConfig     = new ReplicaSetConfig(
                new[] { new DnsEndPoint("localhost", 27017), new DnsEndPoint("localhost", 27018) },
                "name",
                new DnsEndPoint("localhost", 27017),
                1);
            var serverId         = new ServerId(__clusterId, endPoint);
            var state            = ServerState.Connected;
            var tags             = new TagSet(new[] { new Tag("x", "a") });
            var type             = ServerType.ReplicaSetPrimary;
            var version          = new SemanticVersion(2, 6, 3);
            var wireVersionRange = new Range <int>(2, 3);

            var subject = new ServerDescription(
                serverId,
                endPoint,
                state: state,
                type: type,
                averageRoundTripTime: averageRoundTripTime,
                replicaSetConfig: replicaSetConfig,
                tags: tags,
                version: version,
                wireVersionRange: wireVersionRange);

            switch (notEqualField)
            {
            case "AverageRoundTripTime": averageRoundTripTime = averageRoundTripTime.Add(TimeSpan.FromSeconds(1)); break;

            case "EndPoint": endPoint = new DnsEndPoint(endPoint.Host, endPoint.Port + 1); serverId = new ServerId(__clusterId, endPoint); break;

            case "ReplicaSetConfig": replicaSetConfig = new ReplicaSetConfig(replicaSetConfig.Members, "newname", replicaSetConfig.Primary, replicaSetConfig.Version); break;

            case "State": state = ServerState.Disconnected; break;

            case "ServerId": serverId = new ServerId(new ClusterId(), endPoint); break;

            case "Tags": tags = new TagSet(new[] { new Tag("x", "b") }); break;

            case "Type": type = ServerType.ReplicaSetSecondary; break;

            case "Version": version = new SemanticVersion(version.Major, version.Minor, version.Patch + 1); break;

            case "WireVersionRange": wireVersionRange = new Range <int>(0, 0); break;
            }

            var serverDescription2 = new ServerDescription(
                serverId,
                endPoint,
                state: state,
                type: type,
                averageRoundTripTime: averageRoundTripTime,
                replicaSetConfig: replicaSetConfig,
                tags: tags,
                version: version,
                wireVersionRange: wireVersionRange);

            subject.Equals(serverDescription2).Should().BeFalse();
            subject.Equals((object)serverDescription2).Should().BeFalse();
            subject.GetHashCode().Should().NotBe(serverDescription2.GetHashCode());
        }
Exemple #16
0
 // static constructor
 static ServerDescriptionTests()
 {
     __clusterId = new ClusterId();
     __endPoint  = new DnsEndPoint("localhost", 27017);
     __serverId  = new ServerId(__clusterId, __endPoint);
 }
Exemple #17
0
 /// <inheritdoc/>
 public IServerMonitor Create(ServerId serverId, EndPoint endPoint)
 {
     return(new ServerMonitor(serverId, endPoint, _connectionFactory, _settings.HeartbeatInterval, _settings.HeartbeatTimeout, _eventSubscriber));
 }