Esempio n. 1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void ifProposingWithClosedInstanceThenRetryWithNextInstance() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void IfProposingWithClosedInstanceThenRetryWithNextInstance()
        {
            ProposerContext context = Mockito.mock(typeof(ProposerContext));

            when(context.GetLog(any(typeof(Type)))).thenReturn(NullLog.Instance);

            Org.Neo4j.cluster.protocol.atomicbroadcast.multipaxos.InstanceId instanceId = new Org.Neo4j.cluster.protocol.atomicbroadcast.multipaxos.InstanceId(42);
            PaxosInstanceStore paxosInstanceStore = new PaxosInstanceStore();

            // The instance is closed
            PaxosInstance paxosInstance = new PaxosInstance(paxosInstanceStore, instanceId); // the instance

            paxosInstance.Closed(instanceId, "1/15#");                                       // is closed for that conversation, not really important
            when(context.UnbookInstance(instanceId)).thenReturn(Message.@internal(ProposerMessage.Accepted, "the closed payload"));

            when(context.GetPaxosInstance(instanceId)).thenReturn(paxosInstance);                     // required for

            // But in the meantime it was reused and has now (of course) timed out
            string  theTimedoutPayload = "the timed out payload";
            Message message            = Message.@internal(ProposerMessage.Phase1Timeout, theTimedoutPayload);

            message.setHeader(Org.Neo4j.cluster.protocol.atomicbroadcast.multipaxos.InstanceId.INSTANCE, instanceId.ToString());

            // Handle it
            MessageHolder mockHolder = mock(typeof(MessageHolder));

            ProposerState.Proposer.handle(context, message, mockHolder);

            // Verify it was resent as a propose with the same value
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: verify(mockHolder, times(1)).offer(org.mockito.ArgumentMatchers.argThat<org.neo4j.cluster.com.message.Message<? extends org.neo4j.cluster.com.message.MessageType>>(new org.neo4j.cluster.protocol.MessageArgumentMatcher().onMessageType(ProposerMessage.propose).withPayload(theTimedoutPayload)));
            verify(mockHolder, times(1)).offer(ArgumentMatchers.argThat <Message <MessageType> >((new MessageArgumentMatcher()).onMessageType(ProposerMessage.Propose).withPayload(theTimedoutPayload)));
            verify(context, times(1)).unbookInstance(instanceId);
        }
Esempio n. 2
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldCorrectlySetTheInstanceIdHeaderInTheGeneratedHeartbeat()
        public virtual void ShouldCorrectlySetTheInstanceIdHeaderInTheGeneratedHeartbeat()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.List<org.neo4j.cluster.com.message.Message> sentOut = new java.util.LinkedList<>();
            IList <Message> sentOut = new LinkedList <Message>();

            // Given
            MessageHolder holder = mock(typeof(MessageHolder));

            // The sender, which adds messages outgoing to the list above.
            doAnswer(invocation =>
            {
                sentOut.Add(invocation.getArgument(0));
                return(null);
            }).when(holder).offer(ArgumentMatchers.any <Message <MessageType> >());

            ClusterContext       mockContext       = mock(typeof(ClusterContext));
            ClusterConfiguration mockConfiguration = mock(typeof(ClusterConfiguration));

            when(mockConfiguration.Members).thenReturn(new HashMapAnonymousInnerClass5(this));
            when(mockContext.Configuration).thenReturn(mockConfiguration);

            HeartbeatIAmAliveProcessor processor = new HeartbeatIAmAliveProcessor(holder, mockContext);

            Message incoming = Message.to(mock(typeof(MessageType)), URI.create("ha://someAwesomeInstanceInJapan")).setHeader(Message.HEADER_INSTANCE_ID, "2").setHeader(Message.HEADER_FROM, "ha://2");

            // WHEN
            processor.Process(incoming);

            // THEN
            assertEquals(1, sentOut.Count);
            assertEquals(HeartbeatMessage.IAmAlive, sentOut[0].MessageType);
            assertEquals(new InstanceId(2), ((HeartbeatMessage.IAmAliveState)sentOut[0].Payload).Server);
        }
Esempio n. 3
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void delayedVoteFromPreviousElectionMustNotCauseCurrentElectionToComplete() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void DelayedVoteFromPreviousElectionMustNotCauseCurrentElectionToComplete()
        {
            // Given
            ElectionContext context = mock(typeof(ElectionContext));
            MessageHolder   holder  = mock(typeof(MessageHolder));

            when(context.GetLog(Mockito.any())).thenReturn(NullLog.Instance);

            const string role = "master";
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.cluster.InstanceId voter = new org.neo4j.cluster.InstanceId(2);
            InstanceId voter = new InstanceId(2);

            ElectionCredentials       voteCredentialComparable = mock(typeof(ElectionCredentials));
            Message <ElectionMessage> vote = Message.@internal(voted, new ElectionMessage.VersionedVotedData(role, voter, voteCredentialComparable, 4));

            when(context.Voted(role, voter, voteCredentialComparable, 4)).thenReturn(false);

            // When
            election.handle(context, vote, holder);

            verify(context).getLog(ArgumentMatchers.any());
            verify(context).voted(role, voter, voteCredentialComparable, 4);

            // Then
            verifyNoMoreInteractions(context, holder);
        }
Esempio n. 4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void learnerServingOldInstanceShouldNotLogErrorIfItDoesNotHaveIt() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void LearnerServingOldInstanceShouldNotLogErrorIfItDoesNotHaveIt()
        {
            // Given
            LearnerState   state    = LearnerState.Learner;
            LearnerContext ctx      = mock(typeof(LearnerContext));
            MessageHolder  outgoing = mock(typeof(MessageHolder));
            // The instance will be asked for paxos instance 4...
            InstanceId paxosInstanceIdIDontHave          = new InstanceId(4);
            Message <LearnerMessage> messageRequestingId = Message.to(LearnerMessage.LearnRequest, URI.create("c:/1")).setHeader(Message.HEADER_FROM, "c:/2").setHeader(InstanceId.INSTANCE, "4");

            // ...but it does not have it yet
            when(ctx.GetPaxosInstance(paxosInstanceIdIDontHave)).thenReturn(new PaxosInstance(mock(typeof(PaxosInstanceStore)), paxosInstanceIdIDontHave));

            // When
            state.handle(ctx, messageRequestingId, outgoing);

            // Then
            // verify there is no logging of the failure
            verify(ctx, never()).notifyLearnMiss(paxosInstanceIdIDontHave);
            // but the learn failed went out anyway
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: verify(outgoing, times(1)).offer(org.mockito.ArgumentMatchers.argThat<org.neo4j.cluster.com.message.Message<? extends org.neo4j.cluster.com.message.MessageType>>(new org.neo4j.cluster.protocol.MessageArgumentMatcher()
            verify(outgoing, times(1)).offer(ArgumentMatchers.argThat <Message <MessageType> >(new MessageArgumentMatcher()
                                                                                               .onMessageType(LearnerMessage.LearnFailed).to(URI.create("c:/2"))));
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void stopShouldFirstMarkStateMachineForTermination()
        public virtual void StopShouldFirstMarkStateMachineForTermination()
        {
            BoltConnection connection = NewConnection();

            connection.Stop();

            verify(_stateMachine).markForTermination();
            verify(_queueMonitor).enqueued(ArgumentMatchers.eq(connection), any(typeof(Job)));
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void stopShouldCloseStateMachineOnProcessNextBatch()
        public virtual void StopShouldCloseStateMachineOnProcessNextBatch()
        {
            BoltConnection connection = NewConnection();

            connection.Stop();

            connection.ProcessNextBatch();

            verify(_queueMonitor).enqueued(ArgumentMatchers.eq(connection), any(typeof(Job)));
            verify(_stateMachine).markForTermination();
            verify(_stateMachine).close();
        }
Esempio n. 7
0
        internal static ClusterMemberListenerContainer MockAddClusterMemberListener(ClusterMemberEvents events)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final ClusterMemberListenerContainer listenerContainer = new ClusterMemberListenerContainer();
            ClusterMemberListenerContainer listenerContainer = new ClusterMemberListenerContainer();

            doAnswer(invocation =>
            {
                listenerContainer.Set(invocation.getArgument(0));
                return(null);
            }).when(events).addClusterMemberListener(ArgumentMatchers.any());
            return(listenerContainer);
        }
Esempio n. 8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void learnerShouldAskAllAliveInstancesAndTheseOnlyForMissingValue() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void LearnerShouldAskAllAliveInstancesAndTheseOnlyForMissingValue()
        {
            // Given

            IList <URI> allMembers = new List <URI>(3);
            URI         instance1  = URI.create("c:/1");        // this one is failed
            URI         instance2  = URI.create("c:/2");        // this one is ok and will respond
            URI         instance3  = URI.create("c:/3");        // this one is the requesting instance
            URI         instance4  = URI.create("c:/4");        // and this one is ok and will respond too

            allMembers.Add(instance1);
            allMembers.Add(instance2);
            allMembers.Add(instance3);
            allMembers.Add(instance4);

            ISet <Org.Neo4j.cluster.InstanceId> aliveInstanceIds = new HashSet <Org.Neo4j.cluster.InstanceId>();

            Org.Neo4j.cluster.InstanceId id2 = new Org.Neo4j.cluster.InstanceId(2);
            Org.Neo4j.cluster.InstanceId id4 = new Org.Neo4j.cluster.InstanceId(4);
            aliveInstanceIds.Add(id2);
            aliveInstanceIds.Add(id4);

            LearnerState   state    = LearnerState.Learner;
            LearnerContext ctx      = mock(typeof(LearnerContext));
            MessageHolder  outgoing = mock(typeof(MessageHolder));
            InstanceId     paxosInstanceIdIAskedFor = new InstanceId(4);

            when(ctx.LastDeliveredInstanceId).thenReturn(3L);
            when(ctx.LastKnownLearnedInstanceInCluster).thenReturn(5L);
            when(ctx.MemberURIs).thenReturn(allMembers);
            when(ctx.Alive).thenReturn(aliveInstanceIds);
            when(ctx.GetUriForId(id2)).thenReturn(instance2);
            when(ctx.GetUriForId(id4)).thenReturn(instance4);
            when(ctx.GetPaxosInstance(paxosInstanceIdIAskedFor)).thenReturn(new PaxosInstance(mock(typeof(PaxosInstanceStore)), paxosInstanceIdIAskedFor));

            Message <LearnerMessage> theCause = Message.to(LearnerMessage.CatchUp, instance2);                // could be anything, really

            // When
            state.handle(ctx, Message.timeout(LearnerMessage.LearnTimedout, theCause), outgoing);

            // Then
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: verify(outgoing, times(1)).offer(org.mockito.ArgumentMatchers.argThat<org.neo4j.cluster.com.message.Message<? extends org.neo4j.cluster.com.message.MessageType>>(new org.neo4j.cluster.protocol.MessageArgumentMatcher()
            verify(outgoing, times(1)).offer(ArgumentMatchers.argThat <Message <MessageType> >(new MessageArgumentMatcher()
                                                                                               .onMessageType(LearnerMessage.LearnRequest).to(instance2)));
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: verify(outgoing, times(1)).offer(org.mockito.ArgumentMatchers.argThat<org.neo4j.cluster.com.message.Message<? extends org.neo4j.cluster.com.message.MessageType>>(new org.neo4j.cluster.protocol.MessageArgumentMatcher()
            verify(outgoing, times(1)).offer(ArgumentMatchers.argThat <Message <MessageType> >(new MessageArgumentMatcher()
                                                                                               .onMessageType(LearnerMessage.LearnRequest).to(instance4)));
            verifyNoMoreInteractions(outgoing);
        }
Esempio n. 9
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: private javax.ws.rs.core.Response.ResponseBuilder mockResponseBuilder(javax.ws.rs.core.Response response, final java.util.concurrent.atomic.AtomicReference<javax.ws.rs.core.StreamingOutput> ref)
        private Response.ResponseBuilder MockResponseBuilder(Response response, AtomicReference <StreamingOutput> @ref)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final javax.ws.rs.core.Response.ResponseBuilder responseBuilder = mock(javax.ws.rs.core.Response.ResponseBuilder.class);
            Response.ResponseBuilder responseBuilder = mock(typeof(Response.ResponseBuilder));
            when(responseBuilder.entity(ArgumentMatchers.isA(typeof(StreamingOutput)))).thenAnswer(invocationOnMock =>
            {
                @ref.set(invocationOnMock.getArgument(0));
                return(responseBuilder);
            });
            when(responseBuilder.type(ArgumentMatchers.any <MediaType>())).thenReturn(responseBuilder);
            when(responseBuilder.build()).thenReturn(response);
            return(responseBuilder);
        }
Esempio n. 10
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void stopShouldCloseStateMachineIfEnqueueEndsWithRejectedExecutionException()
        public virtual void StopShouldCloseStateMachineIfEnqueueEndsWithRejectedExecutionException()
        {
            BoltConnection connection = NewConnection();

            doAnswer(i =>
            {
                connection.HandleSchedulingError(new RejectedExecutionException());
                return(null);
            }).when(_queueMonitor).enqueued(ArgumentMatchers.eq(connection), any(typeof(Job)));

            connection.Stop();

            verify(_stateMachine).markForTermination();
            verify(_stateMachine).close();
        }
Esempio n. 11
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testElectionFromDemoteIsRejectedIfNoQuorum() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void TestElectionFromDemoteIsRejectedIfNoQuorum()
        {
            ElectionContext context            = mock(typeof(ElectionContext));
            ClusterContext  clusterContextMock = mock(typeof(ClusterContext));

            when(context.ElectionOk()).thenReturn(false);
            when(clusterContextMock.GetLog(ArgumentMatchers.any())).thenReturn(NullLog.Instance);
            when(context.GetLog(ArgumentMatchers.any())).thenReturn(NullLog.Instance);

            MessageHolder holder = mock(typeof(MessageHolder));

            election.handle(context, Message.@internal(demote), holder);

            verifyZeroInteractions(holder);
        }
Esempio n. 12
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void electionShouldRemainLocalIfStartedBySingleInstanceWhichIsTheRoleHolder() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ElectionShouldRemainLocalIfStartedBySingleInstanceWhichIsTheRoleHolder()
        {
            /*
             * Ensures that when an instance is alone in the cluster, elections for roles that it holds do not set
             * timeouts or try to reach other instances.
             */

            // Given
            ElectionContext context            = mock(typeof(ElectionContext));
            ClusterContext  clusterContextMock = mock(typeof(ClusterContext));

            when(clusterContextMock.GetLog(ArgumentMatchers.any())).thenReturn(NullLog.Instance);
            MessageHolder holder = mock(typeof(MessageHolder));

            // These mean the election can proceed normally, by us
            when(context.ElectionOk()).thenReturn(true);
            when(context.InCluster).thenReturn(true);
            when(context.Elector).thenReturn(true);

            // Like it says on the box, we are the only instance
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.cluster.InstanceId myInstanceId = new org.neo4j.cluster.InstanceId(1);
            InstanceId myInstanceId = new InstanceId(1);
            IDictionary <InstanceId, URI> members = new Dictionary <InstanceId, URI>();

            members[myInstanceId] = URI.create("ha://me");
            when(context.Members).thenReturn(members);

            // Any role would do, just make sure we have it
            const string role = "master";
            ElectionContext_VoteRequest voteRequest = new ElectionContext_VoteRequest(role, 13);

            when(context.PossibleRoles).thenReturn(Collections.singletonList(new ElectionRole(role)));
            when(context.GetElected(role)).thenReturn(myInstanceId);
            when(context.VoteRequestForRole(new ElectionRole(role))).thenReturn(voteRequest);

            // Required for logging
            when(context.GetLog(Mockito.any())).thenReturn(NullLog.Instance);

            // When
            election.handle(context, Message.@internal(performRoleElections), holder);

            // Then
            // Make sure that we asked ourselves to vote for that role and that no timer was set
            verify(holder, times(1)).offer(ArgumentMatchers.argThat(new MessageArgumentMatcher <ElectionMessage>()
                                                                    .onMessageType(ElectionMessage.Vote).withPayload(voteRequest)));
            verify(context, never()).setTimeout(ArgumentMatchers.any(), ArgumentMatchers.any());
        }
Esempio n. 13
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldDropMessagesAfterBeingStopped() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldDropMessagesAfterBeingStopped()
        {
            // given
            AssertableLogProvider  logProvider  = new AssertableLogProvider();
            BatchingMessageHandler batchHandler = new BatchingMessageHandler(_downstreamHandler, _inQueueConfig, _batchConfig, _jobSchedulerFactory, logProvider);

            NewEntry.Request message = new NewEntry.Request(null, null);
            batchHandler.Stop();

            // when
            batchHandler.Handle(Wrap(message));
            batchHandler.Run();

            // then
            verify(_downstreamHandler, never()).handle(ArgumentMatchers.any(typeof(RaftMessages_ReceivedInstantClusterIdAwareMessage)));
            logProvider.AssertAtLeastOnce(AssertableLogProvider.inLog(typeof(BatchingMessageHandler)).debug("This handler has been stopped, dropping the message: %s", Wrap(message)));
        }
Esempio n. 14
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void cannotProvideStreamingForOtherMediaTypes() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void CannotProvideStreamingForOtherMediaTypes()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final javax.ws.rs.core.Response.ResponseBuilder responseBuilder = mock(javax.ws.rs.core.Response.ResponseBuilder.class);
            Response.ResponseBuilder responseBuilder = mock(typeof(Response.ResponseBuilder));
            // no streaming
            when(responseBuilder.entity(any(typeof(sbyte[])))).thenReturn(responseBuilder);
            Mockito.verify(responseBuilder, never()).entity(isA(typeof(StreamingOutput)));
            when(responseBuilder.type(ArgumentMatchers.any <MediaType>())).thenReturn(responseBuilder);
            when(responseBuilder.build()).thenReturn(null);
            OutputFormat format = _repository.outputFormat(new IList <MediaType> {
                MediaType.TEXT_HTML_TYPE
            }, new URI("http://some.host"), StreamingHeader());

            assertNotNull(format);
            format.Response(responseBuilder, new ExceptionRepresentation(new Exception()));
        }
Esempio n. 15
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldStopPullingAfterStop() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldStopPullingAfterStop()
        {
            // WHEN
            _updatePuller.pullUpdates();

            // THEN
            verify(_lastUpdateTime, times(1)).LastUpdateTime = anyLong();
            verify(_databaseAvailabilityGuard, times(1)).isAvailable(anyLong());
            verify(_master, times(1)).pullUpdates(ArgumentMatchers.any());
            verify(_monitor, times(1)).pulledUpdates(anyLong());

            // WHEN
            _updatePuller.stop();
            _updatePuller.pullUpdates();

            // THEN
            verifyNoMoreInteractions(_lastUpdateTime, _databaseAvailabilityGuard);
        }
Esempio n. 16
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void keepPullingUpdatesOnConsecutiveCalls() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void KeepPullingUpdatesOnConsecutiveCalls()
        {
            // WHEN
            _updatePuller.pullUpdates();

            // THEN
            verify(_lastUpdateTime, times(1)).LastUpdateTime = anyLong();
            verify(_databaseAvailabilityGuard, times(1)).isAvailable(anyLong());
            verify(_master, times(1)).pullUpdates(ArgumentMatchers.any());
            verify(_monitor, times(1)).pulledUpdates(anyLong());

            // WHEN
            _updatePuller.pullUpdates();

            // THEN
            verify(_lastUpdateTime, times(2)).LastUpdateTime = anyLong();
            verify(_databaseAvailabilityGuard, times(2)).isAvailable(anyLong());
            verify(_master, times(2)).pullUpdates(ArgumentMatchers.any());
            verify(_monitor, times(2)).pulledUpdates(anyLong());
        }
Esempio n. 17
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldAddInstanceIdHeaderInCatchUpMessages() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldAddInstanceIdHeaderInCatchUpMessages()
        {
            // Given
            InstanceId           instanceId    = new InstanceId(1);
            HeartbeatState       heartbeat     = HeartbeatState.Heartbeat;
            ClusterConfiguration configuration = new ClusterConfiguration("whatever", NullLogProvider.Instance, "cluster://1", "cluster://2");

            configuration.Joined(instanceId, URI.create("cluster://1"));
            InstanceId otherInstance = new InstanceId(2);

            configuration.Joined(otherInstance, URI.create("cluster://2"));

            Config config = mock(typeof(Config));

            when(config.Get(ClusterSettings.max_acceptors)).thenReturn(10);

            MultiPaxosContext context = new MultiPaxosContext(instanceId, iterable(new ElectionRole("coordinator")), configuration, Mockito.mock(typeof(Executor)), NullLogProvider.Instance, Mockito.mock(typeof(ObjectInputStreamFactory)), Mockito.mock(typeof(ObjectOutputStreamFactory)), Mockito.mock(typeof(AcceptorInstanceStore)), Mockito.mock(typeof(Timeouts)), mock(typeof(ElectionCredentialsProvider)), config);

            int lastDeliveredInstanceId = 100;

            context.LearnerContext.LastDeliveredInstanceId = lastDeliveredInstanceId;
            // This gap will trigger the catchUp message that we'll test against
            lastDeliveredInstanceId += 20;

            HeartbeatContext heartbeatContext = context.HeartbeatContext;
            Message          received         = Message.@internal(HeartbeatMessage.IAmAlive, new HeartbeatMessage.IAmAliveState(otherInstance));

            received.setHeader(Message.HEADER_FROM, "cluster://2").SetHeader(Message.HEADER_INSTANCE_ID, "2").setHeader("last-learned", Convert.ToString(lastDeliveredInstanceId));

            // When
            MessageHolder holder = mock(typeof(MessageHolder));

            heartbeat.handle(heartbeatContext, received, holder);

            // Then
            verify(holder, times(1)).offer(ArgumentMatchers.argThat(new MessageArgumentMatcher <LearnerMessage>()
                                                                    .onMessageType(LearnerMessage.catchUp).withHeader(Message.HEADER_INSTANCE_ID, "2")));
        }
Esempio n. 18
0
 private static T[] NullSafeAny <T>()
 {
     return(ArgumentMatchers.argThat(argument => true));
 }
Esempio n. 19
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void senderThatStartsAfterReceiverShouldEventuallyConnectSuccessfully() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void SenderThatStartsAfterReceiverShouldEventuallyConnectSuccessfully()
        {
            /*
             * This test verifies that a closed channel from a sender to a receiver is removed from the connections
             * mapping in the sender. It starts a sender, connects it to a receiver and sends a message.
             *
             * We should be testing this without resorting to using a NetworkReceiver. But, as prophets Mick Jagger and
             * Keith Richards mention in their scriptures, you can't always get what you want. In this case,
             * NetworkSender creates on its own the things required to communicate with the outside world, and this
             * means it creates actual sockets. To interact with it then, we need to setup listeners for those sockets
             * and respond properly. Hence, NetworkReceiver. Yes, this means that this test requires to open actual
             * network sockets.
             *
             * Read on for further hacks in place.
             */
            NetworkSender   sender   = null;
            NetworkReceiver receiver = null;

            try
            {
                LogProvider logProviderMock = mock(typeof(LogProvider));
                Log         logMock         = mock(typeof(Log));
                when(logProviderMock.getLog(ArgumentMatchers.any <Type>())).thenReturn(logMock);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.Semaphore sem = new java.util.concurrent.Semaphore(0);
                Semaphore sem = new Semaphore(0);

                /*
                 * A semaphore AND a boolean? Weird, you may think, as the purpose is clearly to step through the
                 * connection setup/teardown process. So, let's discuss what happens here more clearly.
                 *
                 * The sender and receiver are started. Trapped by the semaphore release on listeningAt()
                 * The sender sends through the first message, it is received by the receiver. Trapped by the semaphore
                 *      release on listeningAt() which is triggered on the first message receive on the receiver
                 * The receiver is stopped, trapped by the overridden stop() method of the logging service.
                 * The sender sends a message through, which will trigger the ChannelClosedException. This is where it
                 *      gets tricky. See, normally, since we waited for the semaphore on NetworkReceiver.stop() and an
                 *      happensBefore edge exists and all these good things, it should be certain that the Receiver is
                 *      actually stopped and the message would fail to be sent. That would be too easy though. In reality,
                 *      netty will not wait for all listening threads to stop before returning, so the receiver is not
                 *      guaranteed to not be listening for incoming connections when stop() returns. This happens rarely,
                 *      but the result is that the message "HelloWorld2" should fail with an exception (triggering the warn
                 *      method on the logger) but it doesn't. So we can't block, but we must retry until we know the
                 *      message failed to be sent and the exception happened, which is what this test is all about. We do
                 *      that with a boolean that is tested upon continuously with sent messages until the error happens.
                 *      Then we proceed with...
                 * The receiver is started. Trapped by the listeningAt() callback.
                 * The sender sends a message.
                 * The receiver receives it, trapped by the dummy processor added to the receiver.
                 */
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicBoolean senderChannelClosed = new java.util.concurrent.atomic.AtomicBoolean(false);
                AtomicBoolean senderChannelClosed = new AtomicBoolean(false);

                doAnswer(invocation =>
                {
                    senderChannelClosed.set(true);
                    return(null);
                }).when(logMock).warn(anyString());

                int port = PortAuthority.allocatePort();

                receiver = new NetworkReceiver(mock(typeof(NetworkReceiver.Monitor)), new ConfigurationAnonymousInnerClass(this, port)
                                               , NullLogProvider.Instance)
                {
Esempio n. 20
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldBeAbleToCancelPopulationJob() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldBeAbleToCancelPopulationJob()
        {
            // GIVEN
            CreateNode(map(_name, "Mattias"), _first);
            IndexPopulator      populator = mock(typeof(IndexPopulator));
            FlippableIndexProxy index     = mock(typeof(FlippableIndexProxy));
            IndexStoreView      storeView = mock(typeof(IndexStoreView));
            ControlledStoreScan storeScan = new ControlledStoreScan();

            when(storeView.VisitNodes(any(typeof(int[])), any(typeof(System.Func <int, bool>)), ArgumentMatchers.any(), ArgumentMatchers.any <Visitor <NodeLabelUpdate, Exception> >(), anyBoolean())).thenReturn(storeScan);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final IndexPopulationJob job = newIndexPopulationJob(populator, index, storeView, org.neo4j.logging.NullLogProvider.getInstance(), org.neo4j.storageengine.api.EntityType.NODE, indexDescriptor(FIRST, name, false));
            IndexPopulationJob job = NewIndexPopulationJob(populator, index, storeView, NullLogProvider.Instance, EntityType.NODE, IndexDescriptor(_first, _name, false));

            OtherThreadExecutor <Void> populationJobRunner = Cleanup.add(new OtherThreadExecutor <Void>("Population job test runner", null));
            Future <Void> runFuture = populationJobRunner.ExecuteDontWait(state =>
            {
                job.Run();
                return(null);
            });

            storeScan.Latch.waitForAllToStart();
            job.Cancel().get();
            storeScan.Latch.waitForAllToFinish();

            // WHEN
            runFuture.get();

            // THEN
            verify(populator, times(1)).close(false);
            verify(index, never()).flip(any(), any());
        }
Esempio n. 21
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldFailValueValidationIfAnyPartFail()
        public virtual void ShouldFailValueValidationIfAnyPartFail()
        {
            // given
            System.ArgumentException failure = new System.ArgumentException("failing");
            for (int i = 0; i < _aliveAccessors.Length; i++)
            {
                for (int j = 0; j < _aliveAccessors.Length; j++)
                {
                    if (i == j)
                    {
                        doThrow(failure).when(_aliveAccessors[i]).validateBeforeCommit(ArgumentMatchers.any(typeof(Value[])));
                    }
                    else
                    {
                        doAnswer(invocation => null).when(_aliveAccessors[i]).validateBeforeCommit(any(typeof(Value[])));
                    }
                }

                // when
                try
                {
                    _fusionIndexAccessor.validateBeforeCommit(new Value[] { stringValue("something") });
                }
                catch (System.ArgumentException e)
                {
                    // then
                    assertSame(failure, e);
                }
            }
        }
Esempio n. 22
0
 private OngoingStubbing <Response <LockResult> > WhenMasterAcquireExclusive()
 {
     return(when(_master.acquireExclusiveLock(Null, any(typeof(ResourceType)), ArgumentMatchers.any <long[]>())));
 }