Exemple #1
0
        public virtual void TestStorageReportHasStorageTypeAndState()
        {
            // Make sure we are not testing with the default type, that would not
            // be a very good test.
            NUnit.Framework.Assert.AreNotSame(storageType, StorageType.Default);
            NameNode nn = cluster.GetNameNode();
            DataNode dn = cluster.GetDataNodes()[0];
            // Insert a spy object for the NN RPC.
            DatanodeProtocolClientSideTranslatorPB nnSpy = DataNodeTestUtils.SpyOnBposToNN(dn
                                                                                           , nn);

            // Trigger a heartbeat so there is an interaction with the spy
            // object.
            DataNodeTestUtils.TriggerHeartbeat(dn);
            // Verify that the callback passed in the expected parameters.
            ArgumentCaptor <StorageReport[]> captor = ArgumentCaptor.ForClass <StorageReport[]>
                                                          ();

            Org.Mockito.Mockito.Verify(nnSpy).SendHeartbeat(Matchers.Any <DatanodeRegistration
                                                                          >(), captor.Capture(), Matchers.AnyLong(), Matchers.AnyLong(), Matchers.AnyInt()
                                                            , Matchers.AnyInt(), Matchers.AnyInt(), Org.Mockito.Mockito.Any <VolumeFailureSummary
                                                                                                                             >());
            StorageReport[] reports = captor.GetValue();
            foreach (StorageReport report in reports)
            {
                Assert.AssertThat(report.GetStorage().GetStorageType(), IS.Is(storageType));
                Assert.AssertThat(report.GetStorage().GetState(), IS.Is(DatanodeStorage.State.Normal
                                                                        ));
            }
        }
Exemple #2
0
        private Callable <Void> SharedClientStarter(CoreTopologyService topologyService, ISet <MemberId> expectedTargetSet)
        {
            return(() =>
            {
                try
                {
                    RaftMachine raftMock = mock(typeof(RaftMachine));
                    RaftCoreTopologyConnector tc = new RaftCoreTopologyConnector(topologyService, raftMock, CausalClusteringSettings.database.DefaultValue);
                    topologyService.init();
                    topologyService.start();
                    tc.start();

                    assertEventually("should discover complete target set", () =>
                    {
                        ArgumentCaptor <ISet <MemberId> > targetMembers = ArgumentCaptor.forClass((Type <ISet <MemberId> >)expectedTargetSet.GetType());
                        verify(raftMock, atLeastOnce()).TargetMembershipSet = targetMembers.capture();
                        return targetMembers.Value;
                    }, equalTo(expectedTargetSet), TIMEOUT_MS, MILLISECONDS);
                }
                catch (Exception throwable)
                {
                    fail(throwable.Message);
                }
                return null;
            });
        }
Exemple #3
0
        public void SendGetRequestAsync_Error()
        {
            var response = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.NotFound,
                Content    = new StringContent("Error")
            };

            var handler = new Mock <HttpMessageHandler>(MockBehavior.Strict);

            handler.Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(response);

            var httpClientFactory = new Mock <IHttpClientFactory>();

            httpClientFactory.Setup(h => h.CreateClient(SoundCloudClient.HttpClientName)).Returns(new HttpClient(handler.Object));

            // Act
            var uri       = new Uri("http://localhost:5000");
            var exception = Assert.ThrowsAsync <SoundCloudApiException>(async() =>
                                                                        await new SoundCloudApiGateway(httpClientFactory.Object).SendGetRequestAsync <Comment>(uri));

            // Assert
            Assert.That(exception.HttpStatusCode, Is.EqualTo(response.StatusCode));
            Assert.That(exception.HttpContent, Is.EqualTo(response.Content));

            var captor = new ArgumentCaptor <HttpRequestMessage>();

            handler.Protected().Verify("SendAsync", Times.Once(), captor.CaptureExpr(), ItExpr.IsAny <CancellationToken>());
            Assert.That(captor.Value.RequestUri, Is.EqualTo(uri));
            Assert.That(captor.Value.Method, Is.EqualTo(HttpMethod.Get));
        }
Exemple #4
0
        public virtual void TestPutMetrics2()
        {
            GraphiteSink       sink = new GraphiteSink();
            IList <MetricsTag> tags = new AList <MetricsTag>();

            tags.AddItem(new MetricsTag(MsInfo.Context, "all"));
            tags.AddItem(new MetricsTag(MsInfo.Hostname, null));
            ICollection <AbstractMetric> metrics = new HashSet <AbstractMetric>();

            metrics.AddItem(MakeMetric("foo1", 1));
            metrics.AddItem(MakeMetric("foo2", 2));
            MetricsRecord record = new MetricsRecordImpl(MsInfo.Context, (long)10000, tags, metrics
                                                         );
            ArgumentCaptor <string> argument = ArgumentCaptor.ForClass <string>();

            GraphiteSink.Graphite mockGraphite = MakeGraphite();
            Whitebox.SetInternalState(sink, "graphite", mockGraphite);
            sink.PutMetrics(record);
            try
            {
                Org.Mockito.Mockito.Verify(mockGraphite).Write(argument.Capture());
            }
            catch (IOException e)
            {
                Runtime.PrintStackTrace(e);
            }
            string result = argument.GetValue();

            Assert.Equal(true, result.Equals("null.all.Context.Context=all.foo1 1 10\n"
                                             + "null.all.Context.Context=all.foo2 2 10\n") || result.Equals("null.all.Context.Context=all.foo2 2 10\n"
                                                                                                            + "null.all.Context.Context=all.foo1 1 10\n"));
        }
Exemple #5
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldClearSlavesWhenNewMasterElected()
        public virtual void ShouldClearSlavesWhenNewMasterElected()
        {
            // given
            Cluster        cluster        = mock(typeof(Cluster));
            ClusterMembers clusterMembers = mock(typeof(ClusterMembers));

            when(clusterMembers.AliveMembers).thenReturn(Iterables.option((new ClusterMember(_instanceId)).availableAs(SLAVE, _haUri, StoreId.DEFAULT)));

            SlaveFactory slaveFactory = mock(typeof(SlaveFactory));
            Slave        slave1       = mock(typeof(Slave));
            Slave        slave2       = mock(typeof(Slave));

            when(slaveFactory.NewSlave(any(typeof(LifeSupport)), any(typeof(ClusterMember)), any(typeof(string)), any(typeof(Integer)))).thenReturn(slave1, slave2);

            HighAvailabilitySlaves slaves = new HighAvailabilitySlaves(clusterMembers, cluster, slaveFactory, new HostnamePort("localhost", 0));

            slaves.Init();

            ArgumentCaptor <ClusterListener> listener = ArgumentCaptor.forClass(typeof(ClusterListener));

            verify(cluster).addClusterListener(listener.capture());

            // when
            Slave actualSlave1 = slaves.Slaves.GetEnumerator().next();

            listener.Value.elected(ClusterConfiguration.COORDINATOR, _instanceId, _clusterUri);

            Slave actualSlave2 = slaves.Slaves.GetEnumerator().next();

            // then
            assertThat(actualSlave2, not(sameInstance(actualSlave1)));
        }
        public async Task NewBrandCommandHandler_Works()
        {
            var repository = new Mock <IRepository>();

            var brand = new Brand {
                Id = 1, Name = "a", ImageUri = "uri"
            };

            var captor = new ArgumentCaptor <Brand>();

            repository.Setup(x => x.InsertAsync(captor.Capture()))
            .ReturnsAsync(brand);

            var handler = new NewBrandCommandHandler(repository.Object);

            var result = await handler
                         .Handle(new NewBrandCommand(brand.Name, brand.ImageUri), It.IsAny <CancellationToken>())
                         .ConfigureAwait(false);

            result.Should().BeOfType <BrandDto>();
            result.Id.Should().Equals(brand.Id);
            result.ImageUri.Should().Equals(brand.ImageUri);
            result.Name.Should().Equals(brand.Name);

            captor.Value.Name.Should().Be(brand.Name);
            captor.Value.ImageUri.Should().Be(brand.ImageUri);

            repository.Verify(x => x.InsertAsync(captor.Value), Times.Once);
            repository.VerifyNoOtherCalls();
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldResumeWhenWritabilityChanged() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldResumeWhenWritabilityChanged()
        {
            TestThrottleLock lockOverride = new TestThrottleLock();

            // given
            TransportThrottle throttle = NewThrottleAndInstall(_channel, lockOverride);

            when(_channel.Writable).thenReturn(false);

            Future <Void> completionFuture = OtherThread.execute(state =>
            {
                throttle.Acquire(_channel);
                return(null);
            });

            OtherThread.get().waitUntilWaiting();

            // when
            when(_channel.Writable).thenReturn(true);
            ArgumentCaptor <ChannelInboundHandler> captor = ArgumentCaptor.forClass(typeof(ChannelInboundHandler));

            verify(_channel.pipeline()).addLast(captor.capture());
            captor.Value.channelWritabilityChanged(_context);

            OtherThread.get().awaitFuture(completionFuture);

            assertThat(lockOverride.LockCallCount(), greaterThan(0));
            assertThat(lockOverride.UnlockCallCount(), @is(1));
        }
Exemple #8
0
        public async Task SendDeleteRequestAsync()
        {
            var response = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(JsonConvert.SerializeObject(new Comment {
                    Body = "My Comment"
                }))
            };

            var handler = new Mock <HttpMessageHandler>(MockBehavior.Strict);

            handler.Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(response);

            var httpClientFactory = new Mock <IHttpClientFactory>();

            httpClientFactory.Setup(h => h.CreateClient(SoundCloudClient.HttpClientName)).Returns(new HttpClient(handler.Object));

            // Act
            var uri    = new Uri("http://localhost:5000");
            var result = await new SoundCloudApiGateway(httpClientFactory.Object).SendDeleteRequestAsync <Comment>(uri);

            // Assert
            Assert.That(result.Body, Is.EqualTo("My Comment"));

            var captor = new ArgumentCaptor <HttpRequestMessage>();

            handler.Protected().Verify("SendAsync", Times.Once(), captor.CaptureExpr(), ItExpr.IsAny <CancellationToken>());
            Assert.That(captor.Value.RequestUri, Is.EqualTo(uri));
            Assert.That(captor.Value.Method, Is.EqualTo(HttpMethod.Delete));
        }
 public _Supplier_457(DatanodeProtocolClientSideTranslatorPB mockNN, string fakeBlockPoolId
                      , ArgumentCaptor <StorageReceivedDeletedBlocks[]> captor)
 {
     this.mockNN          = mockNN;
     this.fakeBlockPoolId = fakeBlockPoolId;
     this.captor          = captor;
 }
Exemple #10
0
        private static void AssertMessageHexDumpLogged(Log logMock, sbyte[] messageBytes)
        {
            ArgumentCaptor <string> captor = ArgumentCaptor.forClass(typeof(string));

            verify(logMock).error(captor.capture());
            assertThat(captor.Value, containsString(hexDump(messageBytes)));
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test @SuppressWarnings("unchecked") public void shouldOnlySummarizeStatisticsWhenAllReferencesAreChecked()
            public virtual void ShouldOnlySummarizeStatisticsWhenAllReferencesAreChecked()
            {
                // given
                ConsistencySummaryStatistics summary = mock(typeof(ConsistencySummaryStatistics));
                RecordAccess records = mock(typeof(RecordAccess));

                ConsistencyReporter.ReportHandler handler = new ConsistencyReporter.ReportHandler(new InconsistencyReport(mock(typeof(InconsistencyLogger)), summary), mock(typeof(ConsistencyReporter.ProxyFactory)), RecordType.PROPERTY, records, new PropertyRecord(0), NO_MONITOR);

                RecordReference <PropertyRecord> reference = mock(typeof(RecordReference));
                ComparativeRecordChecker <PropertyRecord, PropertyRecord, ConsistencyReport_PropertyConsistencyReport> checker = mock(typeof(ComparativeRecordChecker));

                handler.comparativeCheck(reference, checker);
                ArgumentCaptor <PendingReferenceCheck <PropertyRecord> > captor = ( ArgumentCaptor )ArgumentCaptor.forClass(typeof(PendingReferenceCheck));

                verify(reference).dispatch(captor.capture());
                PendingReferenceCheck pendingRefCheck = captor.Value;

                // when
                handler.updateSummary();

                // then
                verifyZeroInteractions(summary);

                // when
                pendingRefCheck.skip();

                // then
                verify(summary).update(RecordType.PROPERTY, 0, 0);
                verifyNoMoreInteractions(summary);
            }
Exemple #12
0
        public static float GetFloatGauge(string name, MetricsRecordBuilder rb)
        {
            ArgumentCaptor <float> captor = ArgumentCaptor.ForClass <float>();

            Org.Mockito.Mockito.Verify(rb, Org.Mockito.Mockito.AtLeast(0)).AddGauge(EqName(Interns.Info
                                                                                               (name, string.Empty)), captor.Capture());
            CheckCaptured(captor, name);
            return(captor.GetValue());
        }
Exemple #13
0
        public static long GetLongCounter(string name, MetricsRecordBuilder rb)
        {
            ArgumentCaptor <long> captor = ArgumentCaptor.ForClass <long>();

            Org.Mockito.Mockito.Verify(rb, Org.Mockito.Mockito.AtLeast(0)).AddCounter(EqName(
                                                                                          Interns.Info(name, string.Empty)), captor.Capture());
            CheckCaptured(captor, name);
            return(captor.GetValue());
        }
Exemple #14
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void verifyVerifyUniqueness(org.neo4j.kernel.api.impl.schema.SchemaIndex index, org.neo4j.internal.kernel.api.schema.SchemaDescriptor descriptor, Object... values) throws java.io.IOException, org.neo4j.kernel.api.exceptions.index.IndexEntryConflictException
        private void VerifyVerifyUniqueness(SchemaIndex index, SchemaDescriptor descriptor, params object[] values)
        {
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") org.mockito.ArgumentCaptor<java.util.List<org.neo4j.values.storable.Value[]>> captor = org.mockito.ArgumentCaptor.forClass(java.util.List.class);
            ArgumentCaptor <IList <Value[]> > captor = ArgumentCaptor.forClass(typeof(System.Collections.IList));

            verify(index).verifyUniqueness(any(), eq(descriptor.PropertyIds), captor.capture());

            assertThat(captor.Value, containsInAnyOrder(valueTupleList(values).toArray()));
        }
Exemple #15
0
        public void TestAssignSlotOffsetLength()
        {
            var placedArrayCaptor = new ArgumentCaptor <byte[]>();
            var random            = new Random(0);
            var data = new byte[100].With(random.NextBytes);

            testObj.AssignSlot(SLOT_INDEX, data, 10, 80);
            Verify(slotDestination).SetSlot(Eq(SLOT_INDEX), placedArrayCaptor.GetParameter(), Eq(10), Eq(80));
            VerifyNoMoreInteractions();
            AssertTrue(placedArrayCaptor.Value == data);
        }
        /// <exception cref="System.Exception"/>
        private ReceivedDeletedBlockInfo[] WaitForBlockReceived(ExtendedBlock fakeBlock,
                                                                DatanodeProtocolClientSideTranslatorPB mockNN)
        {
            string fakeBlockPoolId = fakeBlock.GetBlockPoolId();
            ArgumentCaptor <StorageReceivedDeletedBlocks[]> captor = ArgumentCaptor.ForClass <StorageReceivedDeletedBlocks
                                                                                              []>();

            GenericTestUtils.WaitFor(new _Supplier_457(mockNN, fakeBlockPoolId, captor), 100,
                                     10000);
            return(captor.GetValue()[0].GetBlocks());
        }
Exemple #17
0
        public void TestWriteBytesOffsetLength()
        {
            var placedArrayCaptor = new ArgumentCaptor <byte[]>();
            var random            = new Random(0);
            var data = new byte[100].With(random.NextBytes);

            testObj.WriteBytes(SLOT_INDEX, data, 10, 80);
            Verify(slotDestination).SetSlot(Eq(SLOT_INDEX), placedArrayCaptor.GetParameter());
            VerifyNoMoreInteractions();
            AssertTrue(placedArrayCaptor.Value != data);
            AssertTrue(placedArrayCaptor.Value.SequenceEqual(data.Skip(10).Take(80)));
        }
        public async Task NewRecordCommandHandler_Verify_Dependencies()
        {
            var repository = new Mock <IRepository>();

            var record = GetRecord();

            var flavors = new string[] { "a", "b", "c" };

            var flavorPredicateCaptor = new ExpressionCaptor <Flavor, bool>();

            repository.Setup(x => x.ListAsync(flavorPredicateCaptor.Capture()))
            .ReturnsAsync(new List <Flavor> {
                new Flavor {
                    Id = 1, Name = "a",
                }
            });

            var recordCaptor = new ArgumentCaptor <Record>();

            repository.Setup(x => x.InsertAsync(recordCaptor.Capture()))
            .ReturnsAsync(record);

            var flavorCaptor = new ArgumentCaptor <List <Flavor> >();

            repository.Setup(x => x.InsertRangeAsync(flavorCaptor.Capture()))
            .ReturnsAsync(
                new List <Flavor> {
                new Flavor {
                    Id = 2, Name = "b",
                },
                new Flavor {
                    Id = 3, Name = "c",
                }
            });

            var recordFlavorCaptor = new ArgumentCaptor <List <RecordFlavor> >();

            repository.Setup(x => x.InsertRangeAsync(recordFlavorCaptor.Capture()));

            var handler = new NewRecordCommandHandler(repository.Object);

            var result = await handler
                         .Handle(new NewRecordCommand(record.CoffeeId, record.DoseIn, record.DoseOut, record.Time, flavors, record.Rating),
                                 It.IsAny <CancellationToken>())
                         .ConfigureAwait(false);

            repository.Verify(x => x.InsertAsync(recordCaptor.Value), Times.Once);
            repository.Verify(x => x.InsertRangeAsync(flavorCaptor.Value), Times.Once);
            repository.Verify(x => x.InsertRangeAsync(recordFlavorCaptor.Value), Times.Once);
            repository.Verify(x => x.ListAsync(flavorPredicateCaptor.Value), Times.Once);
            repository.VerifyNoOtherCalls();
        }
Exemple #19
0
		private void VerifyFailedStatus(MRAppMasterTest appMaster, string expectedJobState
			)
		{
			ArgumentCaptor<JobHistoryEvent> captor = ArgumentCaptor.ForClass<JobHistoryEvent>
				();
			// handle two events: AMStartedEvent and JobUnsuccessfulCompletionEvent
			Org.Mockito.Mockito.Verify(appMaster.spyHistoryService, Org.Mockito.Mockito.Times
				(2)).HandleEvent(captor.Capture());
			HistoryEvent @event = captor.GetValue().GetHistoryEvent();
			NUnit.Framework.Assert.IsTrue(@event is JobUnsuccessfulCompletionEvent);
			NUnit.Framework.Assert.AreEqual(((JobUnsuccessfulCompletionEvent)@event).GetStatus
				(), expectedJobState);
		}
Exemple #20
0
        public void ReadTypeTest()
        {
            var int32TypeId           = (int)ReservedTypeId.TYPE_S32;
            var typeDescriptionCaptor = new ArgumentCaptor <PofTypeDescription>();

            When(context.GetTypeOrNull(int32TypeId)).ThenReturn(typeof(int));
            When(context.GetTypeFromDescription(typeDescriptionCaptor.GetParameter())).ThenReturn(typeof(int));
            When(slotSource[kSlotIndex]).ThenReturn(BitConverter.GetBytes(int32TypeId));
            AssertEquals(typeof(int), testObj.ReadType(kSlotIndex));
            var typeDescription = typeDescriptionCaptor.Value;

            AssertEquals(1, typeDescription.All().Length);
            AssertEquals(typeof(int), typeDescription.All()[0]);
        }
Exemple #21
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldResumeAsyncResponseDueToTooManyRequests()
        public virtual void shouldResumeAsyncResponseDueToTooManyRequests()
        {
            // given

            // when
            AsyncResponse asyncResponse = mock(typeof(AsyncResponse));

            handler.errorTooManyRequests(asyncResponse);

            // then
            ArgumentCaptor <InvalidRequestException> argumentCaptor = ArgumentCaptor.forClass(typeof(InvalidRequestException));

            verify(asyncResponse).resume(argumentCaptor.capture());
            assertThat(argumentCaptor.Value.Message, @is("At the moment the server has to handle too " + "many requests at the same time. Please try again later."));
        }
Exemple #22
0
        public void TestType()
        {
            var type        = typeof(int);
            var int32TypeId = (int)ReservedTypeId.TYPE_S32;

            When(context.GetTypeIdByType(typeof(int))).ThenReturn(int32TypeId);
            testObj.WriteType(SLOT_INDEX, type);
            var streamCaptor = new ArgumentCaptor <MemoryStream>();

            Verify(context).GetTypeIdByType(typeof(int));
            Verify(slotDestination).SetSlot(Eq(SLOT_INDEX), streamCaptor.GetParameter());
            VerifyNoMoreInteractions();
            var slotStream = streamCaptor.Value;

            AssertEquals(slotStream.ToArray(), BitConverter.GetBytes(int32TypeId));
        }
Exemple #23
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Ignore @Test public void shouldSetAuthenticationProperly()
        public virtual void shouldSetAuthenticationProperly()
        {
            when(identityServiceMock.CurrentAuthentication).thenReturn(new Authentication(MockProvider.EXAMPLE_USER_ID, groupIds, tenantIds));

            FetchExternalTasksExtendedDto fetchExternalTasksDto = createDto(500L);

            given().contentType(ContentType.JSON).body(fetchExternalTasksDto).pathParam("name", "default").when().post(FETCH_EXTERNAL_TASK_URL_NAMED_ENGINE);

            ArgumentCaptor <Authentication> argumentCaptor = ArgumentCaptor.forClass(typeof(Authentication));

            verify(identityServiceMock, atLeastOnce()).Authentication = argumentCaptor.capture();

            assertThat(argumentCaptor.Value.UserId, @is(MockProvider.EXAMPLE_USER_ID));
            assertThat(argumentCaptor.Value.GroupIds, @is(groupIds));
            assertThat(argumentCaptor.Value.TenantIds, @is(tenantIds));
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void databasePanicIsRaisedWhenTxApplicationFails() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void DatabasePanicIsRaisedWhenTxApplicationFails()
        {
            RecordStorageEngine        engine           = BuildRecordStorageEngine();
            Exception                  applicationError = ExecuteFailingTransaction(engine);
            ArgumentCaptor <Exception> captor           = ArgumentCaptor.forClass(typeof(Exception));

            verify(_databaseHealth).panic(captor.capture());
            Exception exception = captor.Value;

            if (exception is KernelException)
            {
                assertThat((( KernelException )exception).status(), @is(Org.Neo4j.Kernel.Api.Exceptions.Status_General.UnknownError));
                exception = exception.InnerException;
            }
            assertThat(exception, @is(applicationError));
        }
Exemple #25
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void appliesDefaultTuningConfigurationForConsistencyChecker() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void AppliesDefaultTuningConfigurationForConsistencyChecker()
        {
            // given
            string[] args = new string[] { "-host", "localhost", "-to", "my_backup" };
            BackupProtocolService service   = mock(typeof(BackupProtocolService));
            PrintStream           systemOut = mock(typeof(PrintStream));

            // when
            (new BackupTool(service, systemOut)).Run(args);

            // then
            ArgumentCaptor <Config> config = ArgumentCaptor.forClass(typeof(Config));

            verify(service).doIncrementalBackupOrFallbackToFull(anyString(), anyInt(), eq(DatabaseLayout.of(Paths.get("my_backup").toFile())), any(typeof(ConsistencyCheck)), config.capture(), eq(BackupClient.BIG_READ_TIMEOUT), eq(false));
            assertFalse(config.Value.get(ConsistencyCheckSettings.consistency_check_property_owners));
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldSetWriteBufferWatermarkOnChannelConfigWhenInstalled()
        public virtual void ShouldSetWriteBufferWatermarkOnChannelConfigWhenInstalled()
        {
            // given
            TransportThrottle throttle = NewThrottle();

            // when
            throttle.Install(_channel);

            // expect
            ArgumentCaptor <WriteBufferWaterMark> argument = ArgumentCaptor.forClass(typeof(WriteBufferWaterMark));

            verify(_config, times(1)).WriteBufferWaterMark = argument.capture();

            assertEquals(64, argument.Value.low());
            assertEquals(256, argument.Value.high());
        }
        private void VerifyCapturedArguments(ArgumentCaptor <StorageBlockReport[]> captor,
                                             int expectedReportsPerCall, int expectedTotalBlockCount)
        {
            IList <StorageBlockReport[]> listOfReports = captor.GetAllValues();
            int numBlocksReported = 0;

            foreach (StorageBlockReport[] reports in listOfReports)
            {
                Assert.AssertThat(reports.Length, IS.Is(expectedReportsPerCall));
                foreach (StorageBlockReport report in reports)
                {
                    BlockListAsLongs blockList = report.GetBlocks();
                    numBlocksReported += blockList.GetNumberOfBlocks();
                }
            }
            System.Diagnostics.Debug.Assert((numBlocksReported >= expectedTotalBlockCount));
        }
Exemple #28
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void appliesDefaultTuningConfigurationForConsistencyChecker() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void AppliesDefaultTuningConfigurationForConsistencyChecker()
        {
            // given
            DatabaseLayout databaseLayout = _testDirectory.databaseLayout();

            string[] args = new string[] { databaseLayout.DatabaseDirectory().AbsolutePath };
            ConsistencyCheckService service = mock(typeof(ConsistencyCheckService));

            // when
            RunConsistencyCheckToolWith(service, args);

            // then
            ArgumentCaptor <Config> config = ArgumentCaptor.forClass(typeof(Config));

            verify(service).runFullConsistencyCheck(eq(databaseLayout), config.capture(), any(typeof(ProgressMonitorFactory)), any(typeof(LogProvider)), any(typeof(FileSystemAbstraction)), anyBoolean(), any(typeof(ConsistencyFlags)));
            assertFalse(config.Value.get(ConsistencyCheckSettings.ConsistencyCheckPropertyOwners));
        }
Exemple #29
0
        public void RegisterHandler_Generic_Test()
        {
            object parameterObject = new object();
            bool   handlerExecuted = false;
            var    handler         = new Action <object>(o => { handlerExecuted = o == parameterObject; });

            testObj.RegisterHandler(handler);

            var captor = new ArgumentCaptor <Action <object> >();

            Verify(handlersByType).TryAdd(Eq(typeof(object)), captor.GetParameter());
            VerifyNoMoreInteractions();

            AssertFalse(handlerExecuted);
            captor.Value(parameterObject);
            AssertTrue(handlerExecuted);
        }
Exemple #30
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void lockResultMustHaveMessageWhenAcquiringSharedLockWithoutConversation() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void LockResultMustHaveMessageWhenAcquiringSharedLockWithoutConversation()
        {
            MasterImpl.SPI      spi = MockedSpi();
            ConversationManager conversationManager = mock(typeof(ConversationManager));
            Config     config = config();
            MasterImpl master = new MasterImpl(spi, conversationManager, null, config);

            RequestContext context = CreateRequestContext(master);

            when(conversationManager.Acquire(context)).thenThrow(new NoSuchEntryException(""));
            master.AcquireSharedLock(context, ResourceTypes.NODE, 1);

            ArgumentCaptor <LockResult> captor = ArgumentCaptor.forClass(typeof(LockResult));

            verify(spi).packTransactionObligationResponse(MockitoHamcrest.argThat(@is(context)), captor.capture());
            assertThat(captor.Value.Message, @is(not(nullValue())));
        }