Exemplo n.º 1
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);
        }
Exemplo n.º 2
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);
        }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
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);
        }
Exemplo n.º 6
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());
        }
Exemplo n.º 7
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)));
        }
Exemplo n.º 8
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()));
        }
Exemplo n.º 9
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);
        }
Exemplo n.º 10
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());
        }
Exemplo n.º 11
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)
                {
Exemplo n.º 12
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);
                }
            }
        }
Exemplo n.º 13
0
 private OngoingStubbing <Response <LockResult> > WhenMasterAcquireExclusive()
 {
     return(when(_master.acquireExclusiveLock(Null, any(typeof(ResourceType)), ArgumentMatchers.any <long[]>())));
 }
Exemplo n.º 14
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());
        }