Esempio n. 1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldUseAlreadyOpenedFileChannel() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldUseAlreadyOpenedFileChannel()
        {
            StoreChannel channel = Mockito.mock(typeof(StoreChannel));
            CustomChannelFileSystemAbstraction fileSystemAbstraction = new CustomChannelFileSystemAbstraction(this, FileSystemRule.get(), channel);
            int numberOfCallesToOpen = 0;

            try
            {
                using (StoreLocker storeLocker = new StoreLocker(fileSystemAbstraction, Target.storeLayout()))
                {
                    try
                    {
                        storeLocker.CheckLock();
                        fail();
                    }
                    catch (StoreLockException)
                    {
                        numberOfCallesToOpen = fileSystemAbstraction.NumberOfCallsToOpen;

                        // Try to grab lock a second time
                        storeLocker.CheckLock();
                    }
                }
            }
            catch (StoreLockException)
            {
                // expected
            }

            assertEquals("Expect that number of open channels will remain the same for ", numberOfCallesToOpen, fileSystemAbstraction.NumberOfCallsToOpen);
        }
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 something() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void Something()
        {
            object acceptorValue = new object();
            object bookedValue   = new object();

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

            PaxosInstanceStore paxosInstanceStore = new PaxosInstanceStore();

            ProposerContext context = Mockito.mock(typeof(ProposerContext));

            when(context.GetPaxosInstance(instanceId)).thenReturn(paxosInstanceStore.GetPaxosInstance(instanceId));
            when(context.GetMinimumQuorumSize(Mockito.anyList())).thenReturn(2);

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

            paxosInstance.Propose(2001, Iterables.asList(Iterables.iterable(create("http://something1"), create("http://something2"), create("http://something3"))));

            Message message = Message.to(ProposerMessage.Promise, create("http://something1"), new ProposerMessage.PromiseState(2001, acceptorValue));

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

            MessageHolder mockHolder = mock(typeof(MessageHolder));

            ProposerState.Proposer.handle(context, message, mockHolder);
        }
Esempio n. 3
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. 4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") @Before public void setUp()
        public virtual void setUp()
        {
            batchConfiguration  = Mockito.mock(typeof(BatchConfiguration));
            engineConfiguration = Mockito.mock(typeof(ProcessEngineConfigurationImpl));
            ids = Mockito.mock(typeof(System.Collections.IList));
            when(batchConfiguration.Ids).thenReturn(ids);
        }
Esempio n. 5
0
            internal virtual ProgressMonitorFactory Mock(Indicator indicatorMock, int indicatorSteps)
            {
                when(indicatorMock.ReportResolution()).thenReturn(indicatorSteps);
                ProgressMonitorFactory factory = Mockito.mock(typeof(ProgressMonitorFactory));

                when(factory.NewIndicator(any(typeof(string)))).thenReturn(indicatorMock);
                FactoryMocks[factory] = false;
                return(factory);
            }
Esempio n. 6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNotAllowAddingMultiplePartsWithSameIdentifier()
        public virtual void ShouldNotAllowAddingMultiplePartsWithSameIdentifier()
        {
            ProgressMonitorFactory.MultiPartBuilder builder = Mockito.mock(typeof(ProgressMonitorFactory)).multipleParts(TestName.MethodName);
            builder.ProgressForPart("first", 10);

            Expected.expect(typeof(System.ArgumentException));
            Expected.expectMessage("Part 'first' has already been defined.");
            builder.ProgressForPart("first", 10);
        }
        private Config MockConfig(IDictionary <string, string> rawConfig)
        {
            Config config = Mockito.mock(typeof(Config));

            when(config.Raw).thenReturn(rawConfig);
            when(config.Get(strict_config_validation)).thenReturn(Convert.ToBoolean(rawConfig[strict_config_validation.name()]));

            return(config);
        }
Esempio n. 8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void init()
        public virtual void init()
        {
            mockedQuery = Mockito.mock(typeof(SchemaLogQuery));

            mockedSchemaLogEntries = createMockedSchemaLogEntries();
            when(mockedQuery.list()).thenReturn(mockedSchemaLogEntries);

            when(processEngine.ManagementService.createSchemaLogQuery()).thenReturn(mockedQuery);
        }
Esempio n. 9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void closeResource()
        public virtual void CloseResource()
        {
            Resource resource = Mockito.mock(typeof(Resource));
            PrimitiveLongResourceIterator source = resourceIterator(ImmutableEmptyLongIterator.INSTANCE, resource);

            PrimitiveLongResourceIterator iterator = DiffApplyingPrimitiveLongIterator.Augment(source, LongSets.immutable.empty(), LongSets.immutable.empty());

            iterator.Close();

            Mockito.verify(resource).close();
        }
Esempio n. 10
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") private org.neo4j.storageengine.api.StorageReader prepareStorageReaderMock(java.util.List<org.neo4j.internal.kernel.api.schema.constraints.ConstraintDescriptor> descriptors)
        private StorageReader PrepareStorageReaderMock(IList <ConstraintDescriptor> descriptors)
        {
            StorageReader storageReader = Mockito.mock(typeof(StorageReader));

            when(storageReader.ConstraintsGetAll()).thenReturn(descriptors.GetEnumerator());
            when(storageReader.GetOrCreateSchemaDependantState(eq(typeof(PropertyExistenceEnforcer)), any(typeof(System.Func)))).thenAnswer(invocation =>
            {
                Function <StorageReader, PropertyExistenceEnforcer> function = invocation.getArgument(1);
                return(function.apply(storageReader));
            });
            return(storageReader);
        }
Esempio n. 11
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldSeekOnAnEmptyTxState()
            internal virtual void ShouldSeekOnAnEmptyTxState()
            {
                // GIVEN
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.storageengine.api.txstate.ReadableTransactionState state = org.mockito.Mockito.mock(org.neo4j.storageengine.api.txstate.ReadableTransactionState.class);
                ReadableTransactionState state = Mockito.mock(typeof(ReadableTransactionState));

                // WHEN
                AddedAndRemoved changes = indexUpdatesForSeek(state, CompositeIndexConflict, ValueTuple.of("43value1", "43value2"));

                // THEN
                assertTrue(changes.Empty);
            }
Esempio n. 12
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldComputeIndexUpdatesForScanOnAnEmptyTxState()
        internal virtual void ShouldComputeIndexUpdatesForScanOnAnEmptyTxState()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.storageengine.api.txstate.ReadableTransactionState state = org.mockito.Mockito.mock(org.neo4j.storageengine.api.txstate.ReadableTransactionState.class);
            ReadableTransactionState state = Mockito.mock(typeof(ReadableTransactionState));

            // WHEN
            AddedAndRemoved           changes           = indexUpdatesForScan(state, _index, IndexOrder.NONE);
            AddedWithValuesAndRemoved changesWithValues = indexUpdatesWithValuesForScan(state, _index, IndexOrder.NONE);

            // THEN
            assertTrue(changes.Empty);
            assertTrue(changesWithValues.Empty);
        }
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 testPluginInitialization()
        public virtual void TestPluginInitialization()
        {
            Config    config    = Config.defaults(ServerSettings.transaction_idle_timeout, "600");
            NeoServer neoServer = Mockito.mock(typeof(NeoServer), Mockito.RETURNS_DEEP_STUBS);

            Mockito.when(neoServer.Config).thenReturn(config);
            ExtensionInitializer extensionInitializer = new ExtensionInitializer(neoServer);

//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Collection<org.neo4j.server.plugins.Injectable<?>> injectableProperties = extensionInitializer.initializePackages(java.util.Collections.singletonList("org.neo4j.server.modules"));
            ICollection <Injectable <object> > injectableProperties = extensionInitializer.InitializePackages(Collections.singletonList("org.neo4j.server.modules"));

            assertTrue(injectableProperties.Any(i => ServerSettings.transaction_idle_timeout.name().Equals(i.Value)));
        }
Esempio n. 14
0
            internal virtual ReadableTransactionState Build()
            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.storageengine.api.txstate.ReadableTransactionState mock = org.mockito.Mockito.mock(org.neo4j.storageengine.api.txstate.ReadableTransactionState.class);
                ReadableTransactionState mock = Mockito.mock(typeof(ReadableTransactionState));

                doReturn(new UnmodifiableMap <>(Updates)).when(mock).getIndexUpdates(any(typeof(SchemaDescriptor)));
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.TreeMap<org.neo4j.values.storable.ValueTuple, org.neo4j.kernel.impl.util.diffsets.MutableLongDiffSetsImpl> sortedMap = new java.util.TreeMap<>(org.neo4j.values.storable.ValueTuple.COMPARATOR);
                SortedDictionary <ValueTuple, MutableLongDiffSetsImpl> sortedMap = new SortedDictionary <ValueTuple, MutableLongDiffSetsImpl>(ValueTuple.COMPARATOR);

//JAVA TO C# CONVERTER TODO TASK: There is no .NET Dictionary equivalent to the Java 'putAll' method:
                sortedMap.putAll(Updates);
                doReturn(sortedMap).when(mock).getSortedIndexUpdates(any(typeof(SchemaDescriptor)));
                return(mock);
            }
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 shouldContinueMovingFilesIfUpgradeCancelledWhileMoving() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldContinueMovingFilesIfUpgradeCancelledWhileMoving()
        {
            PageCache          pageCache          = _pageCacheRule.getPageCache(_fileSystem);
            UpgradableDatabase upgradableDatabase = GetUpgradableDatabase(pageCache);

            string versionToMigrateTo   = upgradableDatabase.CurrentVersion();
            string versionToMigrateFrom = upgradableDatabase.CheckUpgradable(_databaseLayout).storeVersion();

            {
                // GIVEN
                StoreUpgrader upgrader       = NewUpgrader(upgradableDatabase, _allowMigrateConfig, pageCache);
                string        failureMessage = "Just failing";
                upgrader.AddParticipant(ParticipantThatWillFailWhenMoving(failureMessage));

                // WHEN
                try
                {
                    upgrader.MigrateIfNeeded(_databaseLayout);
                    fail("should have thrown");
                }
                catch (UnableToUpgradeException e)
                {                         // THEN
                    assertTrue(e.InnerException is IOException);
                    assertEquals(failureMessage, e.InnerException.Message);
                }
            }

            {
                // AND WHEN

                StoreUpgrader             upgrader             = NewUpgrader(upgradableDatabase, pageCache);
                StoreMigrationParticipant observingParticipant = Mockito.mock(typeof(StoreMigrationParticipant));
                upgrader.AddParticipant(observingParticipant);
                upgrader.MigrateIfNeeded(_databaseLayout);

                // THEN
                verify(observingParticipant, Mockito.never()).migrate(any(typeof(DatabaseLayout)), any(typeof(DatabaseLayout)), any(typeof(ProgressReporter)), eq(versionToMigrateFrom), eq(versionToMigrateTo));
                verify(observingParticipant, Mockito.times(1)).moveMigratedFiles(any(typeof(DatabaseLayout)), any(typeof(DatabaseLayout)), eq(versionToMigrateFrom), eq(versionToMigrateTo));

                verify(observingParticipant, Mockito.times(1)).cleanup(any(typeof(DatabaseLayout)));
            }
        }
Esempio n. 16
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") private org.neo4j.cypher.internal.javacompat.ExecutionResult result(String column, Object value)
        private ExecutionResult Result(string column, object value)
        {
            ExecutionResult result = Mockito.mock(typeof(ExecutionResult));

            Mockito.when(result.Columns()).thenReturn(asList(column));
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.Iterator<java.util.Map<String, Object>> inner = asList(singletonMap(column, value)).iterator();
            IEnumerator <IDictionary <string, object> > inner = asList(singletonMap(column, value)).GetEnumerator();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.graphdb.ResourceIterator<java.util.Map<String, Object>> iterator = new org.neo4j.graphdb.ResourceIterator<java.util.Map<String, Object>>()
            ResourceIterator <IDictionary <string, object> > iterator = new ResourceIteratorAnonymousInnerClass(this, inner);

            Mockito.when(result.GetEnumerator()).thenReturn(iterator);
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            Mockito.when(result.HasNext()).thenAnswer(invocation => iterator.hasNext());
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            Mockito.when(result.Next()).thenAnswer(invocation => iterator.next());
            return(result);
        }
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 updateForHigherNodeIgnoredWhenUsingFullNodeStoreScan() throws org.neo4j.kernel.api.exceptions.index.IndexPopulationFailedKernelException, java.io.IOException, org.neo4j.kernel.api.exceptions.index.IndexEntryConflictException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void UpdateForHigherNodeIgnoredWhenUsingFullNodeStoreScan()
        {
            NeoStores neoStores = Mockito.mock(typeof(NeoStores));
            NodeStore nodeStore = mock(typeof(NodeStore));

            when(neoStores.NodeStore).thenReturn(nodeStore);

            ProcessListenableNeoStoreIndexView storeView      = new ProcessListenableNeoStoreIndexView(this, LockService.NO_LOCK_SERVICE, neoStores);
            MultipleIndexPopulator             indexPopulator = new MultipleIndexPopulator(storeView, _logProvider, EntityType.NODE, mock(typeof(SchemaState)));

            storeView.ProcessListener = new NodeUpdateProcessListener(indexPopulator);

            IndexPopulator populator    = CreateIndexPopulator();
            IndexUpdater   indexUpdater = mock(typeof(IndexUpdater));

            AddPopulator(indexPopulator, populator, 1, TestIndexDescriptorFactory.forLabel(1, 1));

            indexPopulator.Create();
            StoreScan <IndexPopulationFailedKernelException> storeScan = indexPopulator.IndexAllEntities();

            storeScan.Run();

            Mockito.verify(indexUpdater, never()).process(any(typeof(IndexEntryUpdate)));
        }
Esempio n. 18
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setup()
        public virtual void Setup()
        {
            IDictionary <InstanceId, URI> members = new Dictionary <InstanceId, URI>();

            for (int i = 0; i < _instanceIds.Length; i++)
            {
                members[_instanceIds[i]] = URI.create(_initialHosts[i]);
            }
            ClusterConfiguration config = new ClusterConfiguration("clusterName", NullLogProvider.Instance, _initialHosts);

            config.Members = members;

            _context = mock(typeof(ClusterContext));

            Config configuration = mock(typeof(Config));

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

            when(_context.Configuration).thenReturn(config);
            when(_context.MyId).thenReturn(_instanceIds[0]);

            MultiPaxosContext context = new MultiPaxosContext(_instanceIds[0], Iterables.iterable(new ElectionRole("coordinator")), config, 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)), configuration);

            _toTest = context.HeartbeatContext;
        }
Esempio n. 19
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = TEST_TIMEOUT_MILLIS) public void testThreadRemovedFromWaitingListOnDeadlock() throws InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void TestThreadRemovedFromWaitingListOnDeadlock()
        {
            RagManager   ragManager = Mockito.mock(typeof(RagManager));
            LockResource resource   = new LockResource(ResourceTypes.NODE, 1L);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final RWLock lock = createRWLock(ragManager, resource);
            RWLock @lock = CreateRWLock(ragManager, resource);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final LockTransaction lockTransaction = new LockTransaction();
            LockTransaction lockTransaction = new LockTransaction();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final LockTransaction anotherTransaction = new LockTransaction();
            LockTransaction anotherTransaction = new LockTransaction();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch exceptionLatch = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent exceptionLatch = new System.Threading.CountdownEvent(1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch completionLatch = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent completionLatch = new System.Threading.CountdownEvent(1);

            Mockito.doNothing().doAnswer(invocation =>
            {
                exceptionLatch.Signal();
                throw new DeadlockDetectedException("Deadlock");
            }).when(ragManager).checkWaitOn(@lock, lockTransaction);

            @lock.Mark();
            @lock.Mark();
            @lock.AcquireReadLock(LockTracer.NONE, lockTransaction);
            @lock.AcquireReadLock(LockTracer.NONE, anotherTransaction);

            // writer will be added to a waiting list
            // then spurious wake up will be simulated
            // and deadlock will be detected
            ThreadStart writer = () =>
            {
                try
                {
                    @lock.Mark();
                    @lock.AcquireWriteLock(LockTracer.NONE, lockTransaction);
                }
                catch (DeadlockDetectedException)
                {
                    // ignored
                }
                completionLatch.Signal();
            };

            _executor.execute(writer);

            WaitWaitingThreads(@lock, 1);

            // sending notify for all threads till our writer will not cause deadlock exception
            do
            {
                //noinspection SynchronizationOnLocalVariableOrMethodParameter
                lock ( @lock )
                {
                    Monitor.PulseAll(@lock);
                }
            } while (exceptionLatch.CurrentCount == 1);

            // waiting for writer to finish
            completionLatch.await();

            assertEquals("In case of deadlock caused by spurious wake up " + "thread should be removed from waiting list", 0, @lock.WaitingThreadsCount);
        }
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 shouldIgnoreSuspicionsForOurselves() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldIgnoreSuspicionsForOurselves()
        {
            // 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"));
            configuration.Joined(new InstanceId(2), 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);

            HeartbeatContext heartbeatContext = context.HeartbeatContext;
            Message          received         = Message.@internal(HeartbeatMessage.Suspicions, new HeartbeatMessage.SuspicionsState(asSet(iterable(instanceId))));

            received.setHeader(Message.HEADER_FROM, "cluster://2").SetHeader(Message.HEADER_INSTANCE_ID, "2");

            // When
            heartbeat.handle(heartbeatContext, received, mock(typeof(MessageHolder)));

            // Then
            assertThat(heartbeatContext.GetSuspicionsOf(instanceId).Count, equalTo(0));
        }
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 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. 22
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void whenMessageHandlingCausesNewMessagesThenEnsureCorrectOrder()
        public virtual void WhenMessageHandlingCausesNewMessagesThenEnsureCorrectOrder()
        {
            // Given
            StateMachines stateMachines = new StateMachines(NullLogProvider.Instance, mock(typeof(StateMachines.Monitor)), mock(typeof(MessageSource)), Mockito.mock(typeof(MessageSender)), Mockito.mock(typeof(Timeouts)), Mockito.mock(typeof(DelayedDirectExecutor)), ThreadStart.run, mock(typeof(InstanceId)));

            List <TestMessage> handleOrder  = new List <TestMessage>();
            StateMachine       stateMachine = new StateMachine(handleOrder, typeof(TestMessage), TestState.Test, NullLogProvider.Instance);

            stateMachines.AddStateMachine(stateMachine);

            // When
            stateMachines.Process(@internal(TestMessage.Message1));

            // Then
            assertThat(handleOrder.ToString(), equalTo("[message1, message2, message4, message5, message3]"));
        }