public async Task ThrowsExceptionWhenPrivateRepositoryQuotaExceeded() { var newRepository = new NewRepository { Name = "aName", Private = true }; var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":" + @"""name can't be private. You are over your quota.""}]}"); var credentials = new Credentials("haacked", "pwd"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Connection.Credentials.Returns(credentials); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await AssertEx.Throws<PrivateRepositoryQuotaExceededException>( async () => await client.Create(newRepository)); Assert.NotNull(exception); }
public void TestCreateRequest() { var twilioRestClient = Substitute.For <ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Preview, "/understand/Assistants/UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Tasks/UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Fields", "" ); request.AddPostParam("FieldType", Serialize("FieldType")); request.AddPostParam("UniqueName", Serialize("UniqueName")); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { FieldResource.Create("UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "FieldType", "UniqueName", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); }
public CreatePaymentTest() { _connectionStringsOptions = Options.Create(new ConnectionStringsSettings { MongoDbChallenge = string.Empty }); _queuesOptionsSettings = Options.Create(new QueuesSettings { PaymentCreatedQueueName = "fila-teste" }); _awsOptionsSettings = Options.Create(new AwsSettings { AccessKey = "XXX", Region = "XXX", SecretKey = "XXX" }); _mapper = Substitute.For <IMapper>(); _queueHandler = new QueueHandler(_awsOptionsSettings); }
public void rebuilds_if_it_does_not_exist_in_the_schema_if_auto_create_is_create_only() { var schema = Substitute.For <IDocumentSchema>(); var dbobjects = Substitute.For <IDbObjects>(); schema.DbObjects.Returns(dbobjects); var func = TransformFunction.ForFile(new StoreOptions { AutoCreateSchemaObjects = AutoCreate.CreateOnly }, "get_fullname.js"); dbobjects.SchemaFunctionNames().Returns(Enumerable.Empty <FunctionName>()); var runner = Substitute.For <IDDLRunner>(); func.GenerateSchemaObjectsIfNecessary(AutoCreate.CreateOnly, schema, runner); var generated = func.GenerateFunction(); runner.Received().Apply(func, generated); }
public void MapToProperty_GetItemByPath_ReturnsItem() { //Assign using (Db database = new Db { new Sitecore.FakeDb.DbItem("Source"), new Sitecore.FakeDb.DbItem("Target") }) { var config = new SitecoreNodeConfiguration(); var mapper = new SitecoreNodeMapper(); var language = LanguageManager.GetLanguage("en"); mapper.Setup(new DataMapperResolverArgs(null, config)); var obj = new Stub(); var source = database.Database.GetItem("/sitecore/content/Source", language); var target = database.Database.GetItem("/sitecore/content/Target", language); var service = Substitute.For <ISitecoreService>(); var expected = new StubMapped(); config.PropertyInfo = typeof(Stub).GetProperty("StubMapped"); config.Path = "/sitecore/content/Target"; service.CreateType( typeof(StubMapped), Arg.Is <Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language), false, false, null).Returns(expected); service.ItemVersionHandler.VersionCountEnabledAndHasVersions(target).Returns(true); var mappingContext = new SitecoreDataMappingContext(obj, source, service); //Act var result = mapper.MapToProperty(mappingContext); //Assert Assert.AreEqual(expected, result); } }
public void WorkItemLink_addNew_succeeds() { var logger = new DebugEventLogger(); var settings = TestHelpers.LoadConfigFromResourceFile("NewObjects.policies", logger); var repository = new WorkItemRepositoryMock(); var context = Substitute.For <IRequestContext>(); context.GetProjectCollectionUri().Returns( new System.Uri("http://*****:*****@"C:\WorkItemLink_addNew_succeeds", settings, context, logger, (c, i, l) => repository); var parent = new WorkItemMock(repository, runtime); parent.Id = 1; parent.TypeName = "Use Case"; parent["Title"] = "UC"; var child = new WorkItemMock(repository, runtime); child.Id = 2; child.TypeName = "Task"; child["Title"] = "TSK"; repository.SetWorkItems(new[] { parent, child }); using (var processor = new EventProcessor(runtime)) { var notification = Substitute.For <INotification>(); notification.WorkItemId.Returns(2); var result = processor.ProcessEvent(context, notification); Assert.AreEqual(0, result.ExceptionProperties.Count); Assert.IsTrue(child.InternalWasSaveCalled); Assert.AreEqual(EventNotificationStatus.ActionPermitted, result.NotificationStatus); } }
public void GetConfiguration_MaxEntriesPerCallIsNotSetForCustomAudienceUsersEndpoint_ThrowsException() { // Arrange var configuration = XDocument.Parse(@"<komfoSharp> <services> <endpoints baseUrl='https://connect.komfo.com'> <customAudienceUsers path='/v1/ads/customaudiences/{audience_id}/users' /> </endpoints> </services> <polling defaultTimeInterval='00:00:10' defaultAttemptsCount='6'/> </komfoSharp>"); var xmlSource = Substitute.For<IXmlSource>(); var configurationFactory = new AppConfigConfigurationProvider(xmlSource); xmlSource.GetXml().Returns(ToXmlDocument(configuration).SelectSingleNode("komfoSharp")); // Act, Assert configurationFactory .Invoking((x) => x.GetConfiguration()) .ShouldThrow<InvalidOperationException>() .WithMessage("There were errors during deserializing the 'komfoSharp/services/endpoints/customAudienceUsers' node into the KomfoSharp.Configuration.Endpoints.CustomAudienceUsersEndpoint type. See inner exception for details."); }
public void TestCreateRequest() { var twilioRestClient = Substitute.For <ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Api, "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/Mobile.json", "" ); request.AddPostParam("PhoneNumber", Serialize(new Twilio.Types.PhoneNumber("+15017122661"))); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { MobileResource.Create(new Twilio.Types.PhoneNumber("+15017122661"), client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); }
public void ShouldMakePassedRuleCheckAllItsPaths() { //GIVEN var pathCache = new PathCache(Any.Instance <IDependencyPathFactory>()); var rule = Substitute.For <IDependencyRule>(); var report = Any.Instance <IAnalysisReportInProgress>(); var path1 = Any.Instance <IProjectDependencyPath>(); var path2 = Any.Instance <IProjectDependencyPath>(); var path3 = Any.Instance <IProjectDependencyPath>(); pathCache.Add(path1); pathCache.Add(path2); pathCache.Add(path3); //WHEN pathCache.Check(rule, report); //THEN rule.Received(1).Check(report, path1); rule.Received(1).Check(report, path2); rule.Received(1).Check(report, path3); }
public async Task Should_Support_Options_Monitor() { var(_, server, configuration) = await InitializeWithConfiguration(ConfigureClient, options => { ConfigureServer(options); options.Services.Configure <BinderSourceUrl>("mysection"); }); var options = server.GetService <IOptionsMonitor <BinderSourceUrl> >(); var sub = Substitute.For <Action <BinderSourceUrl> >(); options.OnChange(sub); configuration.Update("mysection", new Dictionary <string, string> { ["host"] = "localhost", ["port"] = "443" }); configuration.Update("notmysection", new Dictionary <string, string> { ["host"] = "127.0.0.1", ["port"] = "123" }); await options.WaitForChange(CancellationToken); await SettleNext(); // IOptionsMonitor<> is registered as a singleton, so this will update options.CurrentValue.Host.Should().Be("localhost"); options.CurrentValue.Port.Should().Be(443); sub.Received(1).Invoke(Arg.Any <BinderSourceUrl>()); configuration.Update("mysection", new Dictionary <string, string> { ["host"] = "127.0.0.1", ["port"] = "80" }); await options.WaitForChange(CancellationToken); await SettleNext(); options.CurrentValue.Host.Should().Be("127.0.0.1"); options.CurrentValue.Port.Should().Be(80); sub.Received(2).Invoke(Arg.Any <BinderSourceUrl>()); }
public void RemoveUser_Adds5FakeUser_Remove4FakeUser_CollectionHas2Users() { //arrange IUser fakeUser1 = Substitute.For <IUser>(); fakeUser1.Username = "******"; IUser fakeUser2 = Substitute.For <IUser>(); fakeUser2.Username = "******"; IUser fakeUser3 = Substitute.For <IUser>(); fakeUser3.Username = "******"; IUser fakeUser4 = Substitute.For <IUser>(); fakeUser4.Username = "******"; IUser fakeUser5 = Substitute.For <IUser>(); fakeUser5.Username = "******"; //act _uut.AddUser(fakeUser1.Username); _uut.AddUser(fakeUser2.Username); _uut.AddUser(fakeUser3.Username); _uut.AddUser(fakeUser4.Username); _uut.AddUser(fakeUser5.Username); _uut.RemoveUser(fakeUser5.Username); _uut.RemoveUser(fakeUser4.Username); _uut.RemoveUser(fakeUser3.Username); _uut.RemoveUser(fakeUser2.Username); var result = _uut.Usernames; //assert Assert.That(result.Count, Is.EqualTo(2)); }
private Config BuildInstance() { var instance = new Config(); var iConfig1 = Substitute.For <ILevelConfig>(); iConfig1.RenderNumber(Arg.Is(1)).Returns("I"); iConfig1.Text.Returns("ARTICLE - %1"); iConfig1.StartValue.Returns(1); var iConfig2 = Substitute.For <ILevelConfig>(); iConfig2.RenderNumber(Arg.Is(1)).Returns("1"); iConfig2.StartValue.Returns(1); var iConfig3 = Substitute.For <ILevelConfig>(); iConfig3.RenderNumber(Arg.Is(2)).Returns("2"); var iConfig4 = Substitute.For <ILevelConfig>(); iConfig4.RenderNumber(Arg.Is(2)).Returns("b"); iConfig4.Text.Returns("%2.%3 (%4)"); var iConfig5 = Substitute.For <ILevelConfig>(); iConfig5.RenderNumber(Arg.Is(1)).Returns("1"); iConfig5.Text.Returns("%4.%5"); iConfig5.ForceNumbericRendering.Returns(true); instance.AddLevel(iConfig1); instance.AddLevel(iConfig2); instance.AddLevel(iConfig3); instance.AddLevel(iConfig4); instance.AddLevel(iConfig5); return(instance); }
public void ShouldCorrectlyHandleConcurrency() { // Arrange int threadsCount = 5; int itemsPerThread = 10; var dataRows = Enumerable.Range(0, threadsCount * itemsPerThread) .Select(_ => { var call = Substitute.For <ICall>(); var callSpec = Substitute.For <ICallSpecification>(); callSpec.IsSatisfiedBy(call).Returns(true); var result = new CallResultData(Maybe.Nothing <object>(), Enumerable.Empty <CallResultData.ArgumentValue>()); return(call: call, callSpec: callSpec, result: result); }) .ToList(); var sut = new CallResultCache(); // Act dataRows .AsParallel() .WithExecutionMode(ParallelExecutionMode.ForceParallelism) .WithDegreeOfParallelism(threadsCount) .Select(data => { sut.AddResult(data.callSpec, data.result); return(true); }) .ToArray(); // Assert Assert.True(dataRows.All(row => sut.TryGetResult(row.call, out CallResultData result) && ReferenceEquals(result, row.result))); }
public override void ConfigureServices(ServiceConfigurationContext context) { context.Services.AddSingleton <IBlobProvider>(Substitute.For <FakeBlobProvider1>()); Configure <AbpBlobStoringOptions>(options => { options.Containers .ConfigureDefault(container => { container.ProviderType = typeof(FakeBlobProvider1); }) .Configure <TestContainer1>(container => { container.SetAuthorizationHandler <AuthorizationHandler>(); }) .Configure <TestContainer2>(container => { container.AddBlobSizeLimitHandler(config => config.MaximumBlobSize = 1 / 1024 ); }) .Configure <TestContainer3>(container => { container.AddFileTypeCheckHandler(config => config.AllowedFileTypeNames = new string[] { ".jpeg" } ); }) .Configure <TestContainer4>(container => { container.AddImageResizeHandler(imageResize => { imageResize.ImageWidth = 200; imageResize.ImageHeight = 200; imageResize.ImageSizeMustBeLargerThanPreset = false; }); }); }); }
public void ToHtml_ColoringTextWithLangaugeThatHasOneRules_ReturnValueWillContainSourceText() { // arrange var language = Substitute.For <ILanguage>(); var theme = Substitute.For <ITheme>(); language.GetRules().Returns( new List <Rule> { new Rule { RegularExpression = "samplerule", Scope = TokenScope.Keyword } }); theme.GetStyle(Arg.Any <TokenScope>()) .Returns(new Style { HexColor = string.Empty }); theme.BackgroundHexColor.Returns(string.Empty); theme.BaseHexColor.Returns(string.Empty); const string SourceText = "sample text that could be anything."; // act var coloredHtml = Colorizer.Colorize(SourceText) .WithLanguage(language) .WithTheme(theme) .ToHtml(); // assert Assert.IsTrue(coloredHtml.Contains(SourceText)); }
public BlockObserverTests() { this.minimumDepositConfirmations = 10; this.federationGatewaySettings = Substitute.For <IFederationGatewaySettings>(); this.federationGatewaySettings.MinimumDepositConfirmations.Returns(this.minimumDepositConfirmations); this.federationWalletSyncManager = Substitute.For <IFederationWalletSyncManager>(); this.fullNode = Substitute.For <IFullNode>(); this.federationGatewayClient = Substitute.For <IFederationGatewayClient>(); this.chain = Substitute.ForPartsOf <ConcurrentChain>(); this.fullNode.NodeService <ConcurrentChain>().Returns(this.chain); this.loggerFactory = Substitute.For <ILoggerFactory>(); this.opReturnDataReader = Substitute.For <IOpReturnDataReader>(); this.consensusManager = Substitute.For <IConsensusManager>(); this.withdrawalExtractor = Substitute.For <IWithdrawalExtractor>(); this.extractedWithdrawals = TestingValues.GetWithdrawals(2); this.withdrawalExtractor.ExtractWithdrawalsFromBlock(null, 0).ReturnsForAnyArgs(this.extractedWithdrawals); this.withdrawalReceiver = Substitute.For <IWithdrawalReceiver>(); this.signals = Substitute.For <ISignals>(); this.signals.OnBlockConnected.Returns(Substitute.For <EventNotifier <ChainedHeaderBlock> >()); this.depositExtractor = new DepositExtractor( this.loggerFactory, this.federationGatewaySettings, this.opReturnDataReader, this.fullNode); this.blockObserver = new BlockObserver( this.federationWalletSyncManager, this.depositExtractor, this.withdrawalExtractor, this.withdrawalReceiver, this.federationGatewayClient, this.signals); }
public void ProcessActionMessage( [Values(MessageType.Notification, MessageType.Request, MessageType.Response)] MessageType pMessageType, [Values(true, true, false)] bool pHasAction ) { //Arrange var objClient = Substitute.For <IRouter>(); var objProvider = Substitute.For <IMessageProvider>(); var objRequestManager = Substitute.For <IRequestManager>(); var objActionManager = Substitute.For <IActionManager>(); var objMessage = Substitute.For <IRequestMessage>(); var objAction = Substitute.For <IAction>(); objMessage.Type.Returns(pMessageType); objProvider.GetMessage(Arg.Is <byte[]>(b => b.SequenceEqual(new byte[] { 1, 2, 3, 4 }))).Returns(objMessage); objProvider.GetAction(Arg.Any <IClient>(), Arg.Is(objMessage)).Returns(objAction); Config.Initialize(new Config.ConfigParams() { MessageProvider = objProvider }); //Act new MessageProcessor(objRequestManager, objActionManager).Process(objClient, new byte[] { 1, 2, 3, 4 }); //Assert objProvider.Received(1).GetMessage(Arg.Is <byte[]>(b => b.SequenceEqual(new byte[] { 1, 2, 3, 4 }))); if (pHasAction) { objProvider.Received(1).GetAction(Arg.Any <IClient>(), Arg.Is(objMessage)); objActionManager.Received(1).RunAction(Arg.Any <IClient>(), Arg.Is(objMessage), Arg.Is(objAction)); } else { objProvider.Received(0).GetAction(Arg.Any <IClient>(), Arg.Any <IRequestMessage>()); objActionManager.Received(0).RunAction(Arg.Any <IClient>(), Arg.Any <IRequestMessage>(), Arg.Any <IAction>()); } }
public void SetUp() { nEventsReceived = 0; receivedData = new SeperationsEventArgs.Msg(); Timestamp = "20181006123456789"; fakeDetectSeparationEvent = Substitute.For <IDetectSeparationEvent>(); fakePlane1 = Substitute.For <IPlane>(); fakePlane2 = Substitute.For <IPlane>(); fakePlane1 = new Plane() { Course = 0, Altitude = 14900, Tag = "ATR423", XCoordinate = 39045, YCoordinate = 12932, Velocity = 0, }; fakePlane2 = new Plane() { Course = 0, Altitude = 15000, Tag = "BRW500", XCoordinate = 39000, YCoordinate = 13000, Velocity = 0, }; uut = new DetectSeparationEvent(); fakeDetectSeparationEvent.RaisedSerparationEvent += (o, args) => { receivedData = args.Message; ++nEventsReceived; }; }
public void Good_Get_Edit() { // Arrange var id = 1; var sauce = new Sauce() { ID = id, Name = "Ostry", Price = 2.00M }; var sauceViewModel = new SauceViewModel() { ID = id, Name = "Ostry", Price = 2.00M }; var service = Substitute.For <ISauceRepository>(); var mapper = Substitute.For <IMapper>(); var fakeController = new FakeController(); var controller = new SauceController(service, mapper); fakeController.PrepareFakeAjaxRequest(); controller.ControllerContext = fakeController.GetControllerContext <SauceController>(new RouteData(), controller); service.Get(id).Returns(sauce); mapper.Map <Sauce, SauceViewModel>(sauce).Returns(sauceViewModel); // Act var result = controller.Edit(id) as PartialViewResult; var viewName = result.ViewName; var model = result.Model; var ajaxRequest = controller.Request.IsAjaxRequest(); // Assert Assert.That(result, !Is.Null); Assert.That("_EditPartial", Is.EqualTo(viewName)); Assert.That(ajaxRequest, Is.True); Assert.That(model, !Is.Null); }
public void Index() { // Arrange var sauces = new List <Sauce>() { new Sauce() { Name = "Ostry", Price = 2.00M }, new Sauce() { Name = "Czosnkowo-ziołowy", Price = 2.00M }, new Sauce() { Name = "Pomodorowy", Price = 3.00M } }; var service = Substitute.For <ISauceRepository>(); var mapper = Substitute.For <IMapper>(); var controller = new SauceController(service, mapper); controller.TempData["ModelIsNotValid"] = "Fake content."; controller.ViewBag.ModelIsNotValid = controller.TempData["ModelIsNotValid"]; service.GetAll().Returns(sauces); // Act var result = controller.Index() as ViewResult; var viewName = result.ViewName; var model = result.Model; var tempData = controller.TempData["ModelIsNotValid"]; //Assert Assert.That(result, !Is.Null); Assert.That("Fake content.", Is.EqualTo(tempData)); Assert.That("Index", Is.EqualTo(viewName)); Assert.That(model, !Is.Null); }
public async Task ModifyingBufferMarksThreadsAsStaleAndSignalsRebuild() { var textView = CreateTextView(); var sessionService = CreateSessionService(); var rebuild = Substitute.For<ISubject<ITextSnapshot, ITextSnapshot>>(); sessionService.CreateRebuildSignal().Returns(rebuild); var threads = new List<IInlineCommentThreadModel> { CreateInlineCommentThreadModel(1), CreateInlineCommentThreadModel(2), }; var target = CreateTarget(sessionService: sessionService); sessionService.BuildCommentThreads( target.CurrentSession.PullRequest, FilePath, Arg.Any<IReadOnlyList<DiffChunk>>(), Arg.Any<string>()) .Returns(threads); var file = (PullRequestSessionLiveFile)await target.GetLiveFile(FilePath, textView, textView.TextBuffer); var linesChangedReceived = false; file.LinesChanged.Subscribe(x => linesChangedReceived = true); // Make the first tracking points return a different value so that the thread is marked as stale. var snapshot = textView.TextSnapshot; file.TrackingPoints[file.InlineCommentThreads[0]].GetPosition(snapshot).ReturnsForAnyArgs(5); SignalTextChanged(textView.TextBuffer); threads[0].Received().IsStale = true; threads[1].DidNotReceive().IsStale = true; Assert.That(linesChangedReceived, Is.True); file.Rebuild.Received().OnNext(Arg.Any<ITextSnapshot>()); }
public async Task TransportRouting_TryOpenFailedWithSupportedExceptionTwoTimes_Fail() { var amqpTransportSettings = Substitute.For <ITransportSettings>(); var mqttTransportSettings = Substitute.For <ITransportSettings>(); var innerHandler = Substitute.For <IDelegatingHandler>(); innerHandler.CloseAsync().Returns(TaskConstants.Completed); int openCallCounter = 0; innerHandler.OpenAsync(Arg.Is(false), Arg.Any <CancellationToken>()).Returns(async ci => { openCallCounter++; await Task.Yield(); throw new TimeoutException(); }); var sut = new RoutingDelegatingHandler((cs, ts) => innerHandler, null, new [] { amqpTransportSettings, mqttTransportSettings }); var cancellationToken = new CancellationToken(); await sut.OpenAsync(Arg.Is(false), cancellationToken).ExpectedAsync <IotHubCommunicationException>(); await innerHandler.Received(2).CloseAsync(); Assert.AreEqual(2, openCallCounter); }
private static OctopusDeploymentPlanner GetSutForVersion(string versionNumber) { var repo = Substitute.For<IOctopusRepository>(); var project2 = new ProjectResource("124", "", "Projects-124"); repo.Projects.GetAll().Returns(new List<ReferenceDataItem> { new ReferenceDataItem("123", "") }); repo.Projects.FindAll().Returns(new List<ProjectResource> { project2 }); var project1 = new ProjectResource() { Id = "123" }; repo.Projects.Get("123").Returns(project1); repo.Projects.GetReleases(project1) .Returns(new ResourceCollection<ReleaseResource>(new[] { new ReleaseResource(versionNumber, "123", "") }, new LinkCollection())); repo.Projects.Get("124").Returns(project2); repo.Projects.GetReleases(project2) .Returns(new ResourceCollection<ReleaseResource>(new[] { new ReleaseResource(versionNumber, "124", "") }, new LinkCollection())); var sut = new OctopusDeploymentPlanner(repo); return sut; }
public async Task RemovePropertyCommandWillRemoveAndSaveContentType() { var service = Substitute.For <IContentTypeService>(); var ct = Substitute.For <IContentType>(); service.GetContentType(Arg.Any <string>()).Returns(ct); service.Save(Arg.Any <IContentType>()); var deliverable = new ContentTypeDeliverable( null, Substitute.For <TextWriter>(), service, null, null, null, null ); await deliverable.Run("", new[] { "remove-property", "alias", "property-alias" }); ct.Received(1).RemovePropertyType(Arg.Any <string>()); service.Received(1).Save(Arg.Is(ct)); }
public void GetMaturedBlocksReturnsDeposits() { this.blocks = ChainedHeadersHelper.CreateConsecutiveHeadersAndBlocks(10, true, this.mainChainNetwork); ChainedHeader tip = this.blocks.Last().ChainedHeader; IFederatedPegSettings federatedPegSettings = Substitute.For<IFederatedPegSettings>(); federatedPegSettings.MinimumConfirmationsNormalDeposits.Returns(0); var deposits = new List<IDeposit>() { new Deposit(new uint256(0), DepositRetrievalType.Normal, 100, "test", 0, new uint256(1)) }; // Set the first block up to return 100 normal deposits. IDepositExtractor depositExtractor = Substitute.For<IDepositExtractor>(); depositExtractor.ExtractDepositsFromBlock(this.blocks.First().Block, this.blocks.First().ChainedHeader.Height, new[] { DepositRetrievalType.Normal }).ReturnsForAnyArgs(deposits); this.consensusManager.Tip.Returns(tip); // Makes every block a matured block. var maturedBlocksProvider = new MaturedBlocksProvider(this.consensusManager, depositExtractor, federatedPegSettings); SerializableResult<List<MaturedBlockDepositsModel>> depositsResult = maturedBlocksProvider.RetrieveDeposits(0); Assert.Equal(11, depositsResult.Value.Count); }
public async Task GetBillingTypesPaginatedAsync_ExpectedResult() { IUKFastDRaaSClient client = Substitute.For <IUKFastDRaaSClient>(); client.GetPaginatedAsync <BillingType>("/draas/v1/billing-types", null).Returns(Task.Run(() => new Paginated <BillingType>(client, "/draas/v1/billing-types", null, new ClientResponse <IList <BillingType> >() { Body = new ClientResponseBody <IList <BillingType> >() { Data = new List <BillingType>() { new BillingType(), new BillingType() } } }))); var ops = new BillingTypeOperations <BillingType>(client); var billingTypes = await ops.GetBillingTypesPaginatedAsync(); Assert.AreEqual(2, billingTypes.Items.Count); }
public void TestCreateRequest() { var twilioRestClient = Substitute.For <ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Preview, "/TrustedComms/Business/BrandedCalls", "" ); request.AddPostParam("From", Serialize("from")); request.AddPostParam("To", Serialize("to")); request.AddPostParam("Reason", Serialize("reason")); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { BrandedCallResource.Create("from", "to", "reason", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); }
public void GetMessagesStatisticsAsyncShouldQueryDocument() { var storageService = Substitute.For <IStorageService>(); var document = Substitute.For <IDocument <Message> >(); var message1 = new Message { ProbabilityPercentage = 96 }; var message2 = new Message { ProbabilityPercentage = 82 }; storageService.GetMessages().Returns(new[] { message1, message2 }); ServiceLocator.DefaultInstance.BuildServiceProviderWithDescriptors( new ServiceDescriptor(typeof(IStorageService), storageService)); var result = Queries.GetMessagesStatisticsAsync(null); var array = result.ToArray(); Assert.AreEqual(2, array.Length); Assert.AreEqual(90, array[0].ProbabilityPercentage); Assert.AreEqual(80, array[1].ProbabilityPercentage); }
public void Should_call_Nack_on_nested_subscriptions_with_all_delivery_tag() { // Arrange var channel = Substitute.For <IModel>(); channel.IsOpen.Returns(true); var subs = new CompositeSubscription(); var subscription = new Subscription { ConsumerTag = "ConsumerTag", QueueName = "QueueName", SubscriptionName = "SubscriptionName" }; subscription.SetChannel(channel); subs.AddSubscription(subscription); // Action subs.Nack("ConsumerTag", new[] { (ulong)1, (ulong)2, (ulong)3, (ulong)4, (ulong)5 }, false); // Assert channel.Received().BasicNack(5, true, false); }
public async Task HandleErrorAsync_WithPublishReturningNull_NoMessagePublished() { var publisher = Substitute.For<IPublisher>(); var serviceProvider = new ServiceCollection().AddScoped(_ => publisher) .BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); var policy = new TestErrorPolicy() .Publish(_ => null) .Build(serviceProvider); var envelope = new InboundEnvelope( new MemoryStream(), new[] { new MessageHeader(DefaultMessageHeaders.FailedAttempts, "3") }, new TestOffset(), TestConsumerEndpoint.GetDefault(), TestConsumerEndpoint.GetDefault().Name); await policy.HandleErrorAsync( ConsumerPipelineContextHelper.CreateSubstitute(envelope, serviceProvider), new ArgumentNullException()); await publisher.DidNotReceive().PublishAsync(Arg.Any<object>()); }