public async Task ReIndexAllocationNotificationFeeds_GivenPublishedProviderFoundAndMajorMinorFeatureToggleIsEnabledAndIsAllAllocationResultsVersionsInFeedIndexEnabled_IndexesAndReturnsNoContentResult() { //Arrange int major = 2; int minor = 7; Message message = new Message(); const string specificationId = "spec-1"; IEnumerable <PublishedProviderResult> results = CreatePublishedProviderResultsWithDifferentProviders(); foreach (PublishedProviderResult result in results) { result.FundingStreamResult.AllocationLineResult.Current.Status = AllocationLineStatus.Approved; result.FundingStreamResult.AllocationLineResult.Current.ProfilingPeriods = new[] { new ProfilingPeriod() }; result.FundingStreamResult.AllocationLineResult.Current.Major = major; result.FundingStreamResult.AllocationLineResult.Current.Minor = minor; result.FundingStreamResult.AllocationLineResult.Current.FeedIndexId = "feed-index-id"; } IPublishedProviderResultsRepository repository = CreatePublishedProviderResultsRepository(); repository .GetAllNonHeldPublishedProviderResults() .Returns(results); ILogger logger = CreateLogger(); IEnumerable <PublishedAllocationLineResultVersion> history = results.Select(m => m.FundingStreamResult.AllocationLineResult.Current); history.ElementAt(0).Status = AllocationLineStatus.Approved; foreach (var providerVersion in history.GroupBy(c => c.PublishedProviderResultId)) { if (providerVersion.Any()) { IEnumerable <PublishedAllocationLineResultVersion> providerHistory = providerVersion.AsEnumerable(); string providerId = providerHistory.First().ProviderId; providerId .Should() .NotBeNullOrWhiteSpace(); repository .GetAllNonHeldPublishedProviderResultVersions(Arg.Is(providerVersion.Key), Arg.Is(providerId)) .Returns(providerHistory); } } ISearchRepository <AllocationNotificationFeedIndex> searchRepository = CreateAllocationNotificationFeedSearchRepository(); SpecificationCurrentVersion specification = CreateSpecification(specificationId); ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository(); specificationsRepository .GetCurrentSpecificationById(Arg.Is("spec-1")) .Returns(specification); IEnumerable <AllocationNotificationFeedIndex> resultsBeingSaved = null; await searchRepository.Index(Arg.Do <IEnumerable <AllocationNotificationFeedIndex> >(r => resultsBeingSaved = r)); PublishedResultsService resultsService = CreateResultsService( logger, publishedProviderResultsRepository: repository, allocationNotificationFeedSearchRepository: searchRepository, specificationsRepository: specificationsRepository); //Act await resultsService.ReIndexAllocationNotificationFeeds(message); //Assert await searchRepository .Received(1) .Index(Arg.Is <IEnumerable <AllocationNotificationFeedIndex> >(m => m.Count() == 3)); AllocationNotificationFeedIndex feedResult = resultsBeingSaved.FirstOrDefault(m => m.ProviderId == "1111"); feedResult.ProviderId.Should().Be("1111"); feedResult.Title.Should().Be("Allocation test allocation line 1 was Approved"); feedResult.Summary.Should().Be($"UKPRN: 1111, version {major}.{minor}"); feedResult.DatePublished.HasValue.Should().Be(false); feedResult.FundingStreamId.Should().Be("fs-1"); feedResult.FundingStreamName.Should().Be("funding stream 1"); feedResult.FundingPeriodId.Should().Be("1819"); feedResult.ProviderUkPrn.Should().Be("1111"); feedResult.ProviderUpin.Should().Be("2222"); feedResult.AllocationLineId.Should().Be("AAAAA"); feedResult.AllocationLineName.Should().Be("test allocation line 1"); feedResult.AllocationVersionNumber.Should().Be(1); feedResult.AllocationAmount.Should().Be(50.0); feedResult.ProviderProfiling.Should().Be("[{\"period\":null,\"occurrence\":0,\"periodYear\":0,\"periodType\":null,\"profileValue\":0.0,\"distributionPeriod\":null}]"); feedResult.ProviderName.Should().Be("test provider name 1"); feedResult.LaCode.Should().Be("77777"); feedResult.Authority.Should().Be("London"); feedResult.ProviderType.Should().Be("test type"); feedResult.SubProviderType.Should().Be("test sub type"); feedResult.EstablishmentNumber.Should().Be("es123"); feedResult.FundingPeriodStartYear.Should().Be(DateTime.Now.Year); feedResult.FundingPeriodEndYear.Should().Be(DateTime.Now.Year + 1); feedResult.FundingStreamStartDay.Should().Be(1); feedResult.FundingStreamStartMonth.Should().Be(8); feedResult.FundingStreamEndDay.Should().Be(31); feedResult.FundingStreamEndMonth.Should().Be(7); feedResult.FundingStreamPeriodName.Should().Be("period-type 1"); feedResult.FundingStreamPeriodId.Should().Be("pt1"); feedResult.AllocationLineContractRequired.Should().Be(true); feedResult.AllocationLineFundingRoute.Should().Be("LA"); feedResult.MajorVersion.Should().Be(major); feedResult.MinorVersion.Should().Be(minor); }
public (bool, object) validate_params(BlockHeader parentBlock, BlockHeader block, Action <AuRaParameters> modifyParameters) { object cause = null; _reportingValidator.ReportBenign(Arg.Any <Address>(), Arg.Any <long>(), Arg.Do <IReportingValidator.BenignCause>(c => cause ??= c)); _reportingValidator.ReportMalicious(Arg.Any <Address>(), Arg.Any <long>(), Arg.Any <byte[]>(), Arg.Do <IReportingValidator.MaliciousCause>(c => cause ??= c)); BlockHeader header = null, parent = null; _reportingValidator.TryReportSkipped(Arg.Do <BlockHeader>(h => header = h), Arg.Do <BlockHeader>(h => parent = h)); modifyParameters?.Invoke(_auRaParameters); var validateParams = _sealValidator.ValidateParams(parentBlock, block); if (header?.AuRaStep > parent?.AuRaStep + 1) { _reportingValidator.ReportBenign(header.Beneficiary, header.Number, IReportingValidator.BenignCause.SkippedStep); } return(validateParams, cause); }
public async Task InvalidatesEntitiesAsync() { var debugSessionFactory = (DebugSessionFactory)Sfi; var cache = Substitute.For <UpdateTimestampsCache>(Sfi.Settings, new Dictionary <string, string>()); var updateTimestampsCacheField = typeof(SessionFactoryImpl).GetField( "updateTimestampsCache", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); updateTimestampsCacheField.SetValue(debugSessionFactory.ActualFactory, cache); //"Received" assertions can not be used since the collection is reused and cleared between calls. //The received args are cloned and stored var preInvalidations = new List <IReadOnlyCollection <string> >(); var invalidations = new List <IReadOnlyCollection <string> >(); await(cache.PreInvalidateAsync(Arg.Do <IReadOnlyCollection <string> >(x => preInvalidations.Add(x.ToList())), CancellationToken.None)); await(cache.InvalidateAsync(Arg.Do <IReadOnlyCollection <string> >(x => invalidations.Add(x.ToList())), CancellationToken.None)); using (var session = OpenSession()) { //Add Item using (var tx = session.BeginTransaction()) { foreach (var i in Enumerable.Range(1, 10)) { var item = new Item { Id = i }; await(session.SaveAsync(item)); } await(tx.CommitAsync()); } //Update Item using (var tx = session.BeginTransaction()) { foreach (var i in Enumerable.Range(1, 10)) { var item = await(session.GetAsync <Item>(i)); item.Name = item.Id.ToString(); } await(tx.CommitAsync()); } //Delete Item using (var tx = session.BeginTransaction()) { foreach (var i in Enumerable.Range(1, 10)) { var item = await(session.GetAsync <Item>(i)); await(session.DeleteAsync(item)); } await(tx.CommitAsync()); } //Update Item using HQL using (var tx = session.BeginTransaction()) { await(session.CreateQuery("UPDATE Item SET Name='Test'").ExecuteUpdateAsync()); await(tx.CommitAsync()); } //Update Item using LINQ using (var tx = session.BeginTransaction()) { await(session.Query <Item>() .UpdateBuilder() .Set(x => x.Name, "Test") .UpdateAsync(CancellationToken.None)); await(tx.CommitAsync()); } //Update Item using SQL using (var tx = session.BeginTransaction()) { await(session.CreateSQLQuery("UPDATE Item SET Name='Test'") .AddSynchronizedQuerySpace("Item") .ExecuteUpdateAsync()); await(tx.CommitAsync()); } } //Should receive one preinvalidation per non-DML commit Assert.That(preInvalidations, Has.Count.EqualTo(3)); Assert.That(preInvalidations, Has.All.Count.EqualTo(1).And.Contains("Item")); ///...and one invalidation per commit Assert.That(invalidations, Has.Count.EqualTo(6)); Assert.That(invalidations, Has.All.Count.EqualTo(1).And.Contains("Item")); }
public async Task Queue_Set_With_Sequence() { //Arrange var set = new Set(); var jobId1 = set.Add <TestJobWithoutInput>(); var sequence = new Sequence(); var jobId2 = sequence.Add <TestJobWithoutInput>(); var jobId3 = sequence.Add <TestJobWithoutInput>(); set.Add(sequence); var jobId4 = set.Add <TestJobWithoutInput>(); var batch = new Batch(set); IEnumerable <JobDescription> jobs = null; await _store.AddJobsAsync(Arg.Do <IEnumerable <JobDescription> >(x => jobs = x)); //Act await _scheduler.QueueAsync(batch); //Assert await _store.Received(1).AddJobsAsync(jobs); var result1 = jobs.ElementAt(0); var result2 = jobs.ElementAt(1); var result3 = jobs.ElementAt(2); var result4 = jobs.ElementAt(3); Assert.Equal(batch.Id, result1.BatchId); Assert.Equal(batch.Id, result2.BatchId); Assert.Equal(batch.Id, result3.BatchId); Assert.Equal(batch.Id, result4.BatchId); Assert.Equal(_now, result1.CreatedTime); Assert.Equal(_now, result2.CreatedTime); Assert.Equal(_now, result3.CreatedTime); Assert.Equal(_now, result4.CreatedTime); Assert.Equal(_now, result1.UpdatedTime); Assert.Equal(_now, result2.UpdatedTime); Assert.Equal(_now, result3.UpdatedTime); Assert.Equal(_now, result4.UpdatedTime); Assert.Equal(jobId1, result1.Id); Assert.Equal(jobId2, result2.Id); Assert.Equal(jobId3, result3.Id); Assert.Equal(jobId4, result4.Id); Assert.Equal(0, result1.WaitCount); Assert.Equal(0, result2.WaitCount); Assert.Equal(1, result3.WaitCount); Assert.Equal(0, result4.WaitCount); Assert.Null(result1.PrevId); Assert.Null(result2.PrevId); Assert.Equal(result2.Id, result3.PrevId); Assert.Null(result4.PrevId); Assert.Null(result1.NextId); Assert.Null(result2.NextId); Assert.Null(result3.NextId); Assert.Null(result4.NextId); }
protected override void Before() { CommandService.RaiseAsync(Arg.Do <CommandMessage>(c => _capturedCommand = c)); }
public FieldExtensionsTest() { selected = new Field(typeof(TestType).GetField(nameof(TestType.Field)) !, instance); object arrange = select.Invoke(Arg.Do <IEnumerable <Field> >(f => selection = f)).Returns(selected); }
public void TestApply__Loop() { UrlDir.UrlFile file = UrlBuilder.CreateFile("abc/def.cfg"); ConfigNode config = new TestConfigNode("NODE") { { "name", "000" }, { "aaa", "1" }, }; INodeMatcher nodeMatcher = Substitute.For <INodeMatcher>(); nodeMatcher.IsMatch(Arg.Is <ConfigNode>(node => int.Parse(node.GetValue("aaa")) < 10)).Returns(true); EditPatch patch = new EditPatch(UrlBuilder.CreateConfig("ghi/jkl", new TestConfigNode("@NODE") { { "@aaa *", "2" }, { "bbb", "002" }, new ConfigNode("MM_PATCH_LOOP"), }), nodeMatcher, Substitute.For <IPassSpecifier>()); IProtoUrlConfig urlConfig = Substitute.For <IProtoUrlConfig>(); urlConfig.Node.Returns(config); urlConfig.UrlFile.Returns(file); urlConfig.FullUrl.Returns("abc/def.cfg/NODE"); LinkedList <IProtoUrlConfig> configs = new LinkedList <IProtoUrlConfig>(); configs.AddLast(urlConfig); IPatchProgress progress = Substitute.For <IPatchProgress>(); IBasicLogger logger = Substitute.For <IBasicLogger>(); List <IProtoUrlConfig> modifiedUrlConfigs = new List <IProtoUrlConfig>(); progress.ApplyingUpdate(Arg.Do <IProtoUrlConfig>(url => modifiedUrlConfigs.Add(url)), patch.UrlConfig); patch.Apply(configs, progress, logger); Assert.Single(configs); AssertNodesEqual(new TestConfigNode("NODE") { { "name", "000" }, { "aaa", "16" }, { "bbb", "002" }, { "bbb", "002" }, { "bbb", "002" }, { "bbb", "002" }, }, configs.First.Value.Node); Assert.Same(file, configs.First.Value.UrlFile); Assert.Same(urlConfig, modifiedUrlConfigs[0]); Assert.NotSame(urlConfig, modifiedUrlConfigs[1]); Assert.NotSame(urlConfig, modifiedUrlConfigs[2]); Assert.NotSame(urlConfig, modifiedUrlConfigs[3]); Received.InOrder(delegate { logger.Log(LogType.Log, "Looping on ghi/jkl/@NODE to abc/def.cfg/NODE"); progress.ApplyingUpdate(urlConfig, patch.UrlConfig); progress.ApplyingUpdate(modifiedUrlConfigs[1], patch.UrlConfig); progress.ApplyingUpdate(modifiedUrlConfigs[2], patch.UrlConfig); progress.ApplyingUpdate(modifiedUrlConfigs[3], patch.UrlConfig); }); progress.DidNotReceiveWithAnyArgs().ApplyingCopy(null, null); progress.DidNotReceiveWithAnyArgs().ApplyingDelete(null, null); progress.DidNotReceiveWithAnyArgs().Error(null, null); progress.DidNotReceiveWithAnyArgs().Exception(null, null); progress.DidNotReceiveWithAnyArgs().Exception(null, null, null); }
public async void GetMazebotRandom_Should_Add_MaxSize_Query_If_Supplied() { Dictionary <string, string> queries = null; _requestProvider.CreateGetRequest(Arg.Any <string>(), Arg.Any <Dictionary <string, string> >(), Arg.Do <Dictionary <string, string> >(a => queries = a)); var maxSize = 456; await _client.GetMazebotRandom(null, maxSize); queries.Should().HaveCount(1); queries.Keys.Should().Contain("maxSize"); queries["maxSize"].Should().Be(maxSize.ToString()); }
public void FindCommand() { DispatcherHelper.Initialize(); var projectService = Substitute.For <IProjectService>(); var dialogService = Substitute.For <IDialogService>(); var busyService = Substitute.For <IBusyService>(); var analysisService = Substitute.For <IAnalysisService>(); var importService = Substitute.For <IImportService>(); var exportService = Substitute.For <IExportService>(); WordViewModel.Factory wordFactory = word => new WordViewModel(busyService, analysisService, word); WordListsVarietyMeaningViewModel.Factory varietyglossFactory = (variety, meaning) => new WordListsVarietyMeaningViewModel(busyService, analysisService, wordFactory, variety, meaning); WordListsVarietyViewModel.Factory varietyFactory = variety => new WordListsVarietyViewModel(projectService, varietyglossFactory, variety); var wordLists = new WordListsViewModel(projectService, dialogService, importService, exportService, analysisService, varietyFactory); var project = new CogProject(_spanFactory) { Meanings = { new Meaning("gloss1", "cat1"), new Meaning("gloss2", "cat2"), new Meaning("gloss3", "cat3") }, Varieties = { new Variety("variety1"), new Variety("variety2") } }; project.Varieties[0].Words.AddRange(new[] { new Word("hello", project.Meanings[0]), new Word("good", project.Meanings[1]), new Word("bad", project.Meanings[2]) }); project.Varieties[1].Words.AddRange(new[] { new Word("help", project.Meanings[0]), new Word("google", project.Meanings[1]), new Word("batter", project.Meanings[2]) }); projectService.Project.Returns(project); projectService.ProjectOpened += Raise.Event(); wordLists.VarietiesView = new ListCollectionView(wordLists.Varieties); FindViewModel findViewModel = null; Action closeCallback = null; dialogService.ShowModelessDialog(wordLists, Arg.Do <FindViewModel>(vm => findViewModel = vm), Arg.Do <Action>(callback => closeCallback = callback)); wordLists.FindCommand.Execute(null); Assert.That(findViewModel, Is.Not.Null); Assert.That(closeCallback, Is.Not.Null); // already open, shouldn't get opened twice dialogService.ClearReceivedCalls(); wordLists.FindCommand.Execute(null); dialogService.DidNotReceive().ShowModelessDialog(wordLists, Arg.Any <FindViewModel>(), Arg.Any <Action>()); // form searches findViewModel.Field = FindField.Form; // nothing selected, no match findViewModel.String = "fall"; findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.Null); // nothing selected, matches findViewModel.String = "he"; findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[0].Meanings[0])); findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[1].Meanings[0])); findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[1].Meanings[0])); // first word selected, matches wordLists.SelectedVarietyMeaning = wordLists.Varieties[0].Meanings[0]; findViewModel.String = "o"; findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[0].Meanings[1])); findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[1].Meanings[1])); findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[0].Meanings[0])); findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[0].Meanings[0])); // start search over findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[0].Meanings[1])); // last word selected, matches wordLists.SelectedVarietyMeaning = wordLists.Varieties[1].Meanings[2]; findViewModel.String = "ba"; findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[0].Meanings[2])); findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[1].Meanings[2])); findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[1].Meanings[2])); // last word selected, matches, change selected word findViewModel.String = "ba"; findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[0].Meanings[2])); wordLists.SelectedVarietyMeaning = wordLists.Varieties[0].Meanings[0]; findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[0].Meanings[2])); findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[1].Meanings[2])); findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[1].Meanings[2])); // gloss searches // nothing selected, no match wordLists.SelectedVarietyMeaning = null; findViewModel.Field = FindField.Gloss; findViewModel.String = "gloss4"; findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.Null); // nothing selected, matches wordLists.SelectedVarietyMeaning = null; findViewModel.Field = FindField.Gloss; findViewModel.String = "gloss2"; findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[0].Meanings[1])); findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[0].Meanings[1])); // selected, matches findViewModel.String = "gloss"; wordLists.SelectedVarietyMeaning = wordLists.Varieties[1].Meanings[1]; findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[1].Meanings[2])); findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[1].Meanings[0])); findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[1].Meanings[1])); findViewModel.FindNextCommand.Execute(null); Assert.That(wordLists.SelectedVarietyMeaning, Is.EqualTo(wordLists.Varieties[1].Meanings[1])); }
public async Task GetsOrCreatesAuthenticationWithFingerprintAtCorrectUrl() { var data = new NewAuthorization { Fingerprint = "ha-ha-fingerprint" }; var client = Substitute.For <IApiConnection>(); var authEndpoint = new AuthorizationsClient(client); Uri calledUri = null; dynamic calledBody = null; client.Put <ApplicationAuthorization>(Arg.Do <Uri>(u => calledUri = u), Arg.Do <dynamic>(body => calledBody = body)); authEndpoint.GetOrCreateApplicationAuthentication("clientId", "secret", data); Assert.NotNull(calledUri); Assert.Equal("authorizations/clients/clientId", calledUri.ToString()); Assert.NotNull(calledBody); var fingerprintProperty = ((IEnumerable <PropertyInfo>)calledBody.GetType().DeclaredProperties).FirstOrDefault(x => x.Name == "fingerprint"); Assert.NotNull(fingerprintProperty); Assert.Equal(fingerprintProperty.GetValue(calledBody), "ha-ha-fingerprint"); }
public async void GetMazebotRandom_Should_Call_IApiRequestProvider_CreateGetRequest() { Dictionary <string, string> queries = null; _requestProvider.CreateGetRequest(Arg.Any <string>(), Arg.Any <Dictionary <string, string> >(), Arg.Do <Dictionary <string, string> >(a => queries = a)); await _client.GetMazebotRandom(null, null); _requestProvider.Received(1).CreateGetRequest($"{_noopsUrl}/mazebot/random", Arg.Any <Dictionary <string, string> >(), Arg.Any <Dictionary <string, string> >()); queries.Should().BeEmpty(); }
public async Task GetsOrCreatesAuthenticationWithFingerprintAtCorrectUrl() { var data = new NewAuthorization { Fingerprint = "ha-ha-fingerprint" }; var client = Substitute.For <IApiConnection>(); var authEndpoint = new AuthorizationsClient(client); Uri calledUri = null; dynamic calledBody = null; client.Put <ApplicationAuthorization>(Arg.Do <Uri>(u => calledUri = u), Arg.Do <object>(body => calledBody = body)); authEndpoint.GetOrCreateApplicationAuthentication("clientId", "secret", data); Assert.NotNull(calledUri); Assert.Equal(calledUri.ToString(), "authorizations/clients/clientId"); Assert.NotNull(calledBody); Assert.Equal(calledBody.fingerprint, "ha-ha-fingerprint"); }
/// <summary> /// Capture any argument compatible with type <typeparamref name="T"/> and use it to call the <paramref name="useArgument"/> function /// whenever a matching call is made to the substitute. /// This is provided for compatibility with older compilers -- /// if possible use <see cref="Arg.Do{T}" /> instead. /// </summary> public static T Do <T>(Action <T> useArgument) => Arg.Do(useArgument);
public async Task Saml2Handler_Acs_Works() { var context = new Saml2HandlerTestContext(); context.HttpContext.Request.Method = "POST"; context.HttpContext.Request.Path = "/Saml2/Acs"; var authProps = new AuthenticationProperties() { IssuedUtc = new DateTimeOffset(DateTime.UtcNow) }; authProps.Items["Test"] = "TestValue"; var state = new StoredRequestState( new EntityId("https://idp.example.com"), new Uri("https://localhost/LoggedIn"), new Saml2Id("InResponseToId"), authProps.Items); var relayState = SecureKeyGenerator.CreateRelayState(); var cookieData = HttpRequestData.ConvertBinaryData( StubDataProtector.Protect(state.Serialize())); var cookieName = $"{StoredRequestState.CookieNameBase}{relayState}"; context.HttpContext.Request.Cookies = new StubCookieCollection( Enumerable.Repeat(new KeyValuePair <string, string>( cookieName, cookieData), 1)); var response = @"<saml2p:Response xmlns:saml2p=""urn:oasis:names:tc:SAML:2.0:protocol"" xmlns:saml2=""urn:oasis:names:tc:SAML:2.0:assertion"" ID = """ + MethodBase.GetCurrentMethod().Name + @""" Version=""2.0"" IssueInstant=""2013-01-01T00:00:00Z"" InResponseTo=""InResponseToId"" > <saml2:Issuer> https://idp.example.com </saml2:Issuer> <saml2p:Status> <saml2p:StatusCode Value=""urn:oasis:names:tc:SAML:2.0:status:Success"" /> </saml2p:Status> <saml2:Assertion Version=""2.0"" ID=""" + MethodBase.GetCurrentMethod().Name + @"_Assertion1"" IssueInstant=""2013-09-25T00:00:00Z""> <saml2:Issuer>https://idp.example.com</saml2:Issuer> <saml2:Subject> <saml2:NameID>SomeUser</saml2:NameID> <saml2:SubjectConfirmation Method=""urn:oasis:names:tc:SAML:2.0:cm:bearer"" /> </saml2:Subject> <saml2:Conditions NotOnOrAfter=""2100-01-01T00:00:00Z""> <saml2:AudienceRestriction> <saml2:Audience>http://sp.example.com/saml2</saml2:Audience> </saml2:AudienceRestriction> </saml2:Conditions> </saml2:Assertion> </saml2p:Response>"; var form = Substitute.For <IFormCollection>(); IEnumerator <KeyValuePair <string, StringValues> > formCollectionEnumerator = new KeyValuePair <string, StringValues>[] { new KeyValuePair <string, StringValues>( "SAMLResponse", new StringValues( Convert.ToBase64String( Encoding.UTF8.GetBytes(SignedXmlHelper.SignXml(response))))), new KeyValuePair <string, StringValues>( "RelayState", new StringValues(relayState)) }.AsEnumerable().GetEnumerator(); form.GetEnumerator().Returns(formCollectionEnumerator); context.HttpContext.Request.Form.Returns(form); var authService = Substitute.For <IAuthenticationService>(); context.HttpContext.RequestServices.GetService(typeof(IAuthenticationService)) .Returns(authService); ClaimsPrincipal principal = null; AuthenticationProperties actualAuthProps = null; await authService.SignInAsync( context.HttpContext, TestHelpers.defaultSignInScheme, Arg.Do <ClaimsPrincipal>(p => principal = p), Arg.Do <AuthenticationProperties>(ap => actualAuthProps = ap)); await context.Subject.HandleRequestAsync(); principal.HasClaim(ClaimTypes.NameIdentifier, "SomeUser").Should().BeTrue(); actualAuthProps.IssuedUtc.Should().Be(authProps.IssuedUtc); actualAuthProps.Items["Test"].Should().Be("TestValue"); context.HttpContext.Response.Headers["Location"].Single().Should().Be( state.ReturnUrl.OriginalString); context.HttpContext.Response.StatusCode.Should().Be(303); }
private void GivenAServerIsCreated() { _plexService.AddServer(Arg.Do <PlexServerRow>(x => _createdServer = x)); }
public async Task Invoke_Should_Return200_When_ActionContainsAction() { int code = default; _response.StatusCode = Arg.Do <int>(args => code = args); var thingId = _fixture.Create <string>(); var thing = _fixture.Create <Thing>(); _thingActivator.CreateInstance(_service, thingId) .Returns(thing); var actionName = _fixture.Create <string>(); var action = Substitute.For <Action>(); var actionId = _fixture.Create <string>(); action.Id.Returns(actionId); action.Name.Returns(actionName); thing.Actions.Add(action); _routeValue.GetValue <string>("thing") .Returns(thingId); var descriptor = Substitute.For <IDescriptor <Action> >(); descriptor.CreateDescription(action) .Returns(_fixture.Create <Dictionary <string, object> >()); _service.GetService(typeof(IDescriptor <Action>)) .Returns(descriptor); var cancel = CancellationToken.None; _httpContext.RequestAborted .Returns(cancel); var writer = Substitute.For <IHttpBodyWriter>(); writer.WriteAsync(Arg.Any <LinkedList <Dictionary <string, object> > >(), cancel) .Returns(new ValueTask()); _service.GetService(typeof(IHttpBodyWriter)) .Returns(writer); await Invoke(_httpContext); code.Should().Be((int)HttpStatusCode.OK); _thingActivator .Received(1) .CreateInstance(_service, thingId); descriptor .Received(1) .CreateDescription(action); await writer .Received(1) .WriteAsync(Arg.Any <LinkedList <Dictionary <string, object> > >(), cancel); }
public async Task CommandResultExtensions_Apply() { var context = TestHelpers.CreateHttpContext(); var state = new StoredRequestState( new EntityId("https://idp.example.com"), new Uri("https://sp.example.com/ReturnUrl"), new Saml2Id(), new Dictionary <string, string>() { { "Key1", "Value1" }, { "Key2", "value2" } }); var redirectLocation = "https://destination.com"; var commandResult = new CommandResult() { HttpStatusCode = System.Net.HttpStatusCode.Redirect, Location = new Uri(redirectLocation), SetCookieName = "Saml2.123", RelayState = "123", RequestState = state, ContentType = "application/json", Content = "{ value: 42 }", ClearCookieName = "Clear-Cookie", Principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "SomerUser") }, "authType")), RelayData = new Dictionary <string, string>() { { "Relayed", "Value" } } }; ClaimsPrincipal principal = null; AuthenticationProperties authProps = null; var authService = Substitute.For <IAuthenticationService>(); context.RequestServices.GetService(typeof(IAuthenticationService)) .Returns(authService); await authService.SignInAsync( context, "TestSignInScheme", Arg.Do <ClaimsPrincipal>(p => principal = p), Arg.Do <AuthenticationProperties>(ap => authProps = ap)); await commandResult.Apply(context, new StubDataProtector(), "TestSignInScheme", null); var expectedCookieData = HttpRequestData.ConvertBinaryData( StubDataProtector.Protect(commandResult.GetSerializedRequestState())); context.Response.StatusCode.Should().Be(302); context.Response.Headers["Location"].SingleOrDefault() .Should().Be("https://destination.com/", "location header should be set"); context.Response.Cookies.Received().Append( "Saml2.123", expectedCookieData, Arg.Is <CookieOptions>(co => co.HttpOnly && co.SameSite == SameSiteMode.None)); context.Response.Cookies.Received().Delete("Clear-Cookie"); context.Response.ContentType .Should().Be("application/json", "content type should be set"); context.Response.Body.Seek(0, SeekOrigin.Begin); new StreamReader(context.Response.Body).ReadToEnd() .Should().Be("{ value: 42 }", "content should be set"); principal.HasClaim(ClaimTypes.NameIdentifier, "SomerUser").Should().BeTrue(); authProps.Items["Relayed"].Should().Be("Value"); authProps.RedirectUri.Should().Be(redirectLocation); }
public (bool, object) validate_params(BlockHeader parentBlock, BlockHeader block, Action <AuRaParameters> modifyParameters, Repeat repeat, bool parentIsHead, bool isValidSealer) { _blockTree.Head.Returns(parentIsHead ? new Block(parentBlock) : new Block(Build.A.BlockHeader.WithNumber(parentBlock.Number - 1).TestObject)); _validSealerStrategy.IsValidSealer(Arg.Any <IList <Address> >(), block.Beneficiary, block.AuRaStep.Value).Returns(isValidSealer); object cause = null; _reportingValidator.ReportBenign(Arg.Any <Address>(), Arg.Any <long>(), Arg.Do <IReportingValidator.BenignCause>(c => cause ??= c)); _reportingValidator.ReportMalicious(Arg.Any <Address>(), Arg.Any <long>(), Arg.Any <byte[]>(), Arg.Do <IReportingValidator.MaliciousCause>(c => cause ??= c)); BlockHeader header = null, parent = null; _reportingValidator.TryReportSkipped(Arg.Do <BlockHeader>(h => header = h), Arg.Do <BlockHeader>(h => parent = h)); modifyParameters?.Invoke(_auRaParameters); var validateParams = _sealValidator.ValidateParams(parentBlock, block); if (header?.AuRaStep > parent?.AuRaStep + 1) { _reportingValidator.ReportBenign(header.Beneficiary, header.Number, IReportingValidator.BenignCause.SkippedStep); } if (repeat != Repeat.No) { if (repeat == Repeat.YesChangeHash) { block.Hash = Keccak.Compute("AAA"); } validateParams = _sealValidator.ValidateParams(parentBlock, block); } return(validateParams, cause); }
public PropertyExtensionsTest() { selected = new Property(typeof(TestType).GetProperty(nameof(TestType.Property)) !, instance); object arrange = select.Invoke(Arg.Do <IEnumerable <Property> >(p => selection = p)).Returns(selected); }
public void SetNextStatementFailToJump() { // We need CanSetNextStatement() to pass in order to execute SetNexStatement(). const string NAME = "test"; const ulong ADDRESS = 0xabcd; var threadId = 1u; var mockThread = Substitute.For <RemoteThread>(); mockThread.GetThreadId().Returns(threadId); var mockStackFrame = Substitute.For <IDebugStackFrame2>(); string name; mockStackFrame.GetName(out name).Returns(x => { x[0] = NAME; return(VSConstants.S_OK); }); IDebugThread2 outThread; IDebugThread thread = CreateDebugThread <IDebugThread>(mockThread); mockStackFrame.GetThread(out outThread).Returns(x => { x[0] = thread; return(VSConstants.S_OK); }); var mockCodeContext = Substitute.For <IDebugCodeContext2>(); var contextInfoFields = enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS | enum_CONTEXT_INFO_FIELDS.CIF_FUNCTION; System.Action <CONTEXT_INFO[]> setContext = (infos => { infos[0].bstrFunction = NAME; infos[0].bstrAddress = "0xabcd"; infos[0].dwFields = contextInfoFields; }); mockCodeContext .GetInfo(Arg.Any <enum_CONTEXT_INFO_FIELDS>(), Arg.Do(setContext)) .Returns(VSConstants.S_OK); ((IDebugMemoryContext2)mockCodeContext) .GetInfo(Arg.Any <enum_CONTEXT_INFO_FIELDS>(), Arg.Do(setContext)) .Returns(VSConstants.S_OK); const string DIR = "path\\to"; const string FILE_NAME = "file"; const uint LINE = 2; var mockProcess = Substitute.For <SbProcess>(); mockThread.GetProcess().Returns(mockProcess); var mockTarget = Substitute.For <RemoteTarget>(); mockProcess.GetTarget().Returns(mockTarget); var mockAddress = Substitute.For <SbAddress>(); var lineEntry = Substitute.For <LineEntryInfo>(); lineEntry.Directory = DIR; lineEntry.FileName = FILE_NAME; lineEntry.Line = LINE; var mockError = Substitute.For <SbError>(); mockError.Fail().Returns(true); mockError.GetCString().Returns("JumpToLine() failed for some reason."); mockThread.JumpToLine(Path.Combine(DIR, FILE_NAME), LINE).Returns(mockError); mockAddress.GetLineEntry().Returns(lineEntry); mockTarget.ResolveLoadAddress(ADDRESS).Returns(mockAddress); Assert.AreEqual(VSConstants.E_FAIL, thread.SetNextStatement(mockStackFrame, mockCodeContext)); }
public void FindCommand() { DispatcherHelper.Initialize(); var segmentPool = new SegmentPool(); var projectService = Substitute.For <IProjectService>(); var dialogService = Substitute.For <IDialogService>(); var busyService = Substitute.For <IBusyService>(); var graphService = new GraphService(projectService); var imageExportService = Substitute.For <IImageExportService>(); var analysisService = new AnalysisService(_spanFactory, segmentPool, projectService, dialogService, busyService); WordPairsViewModel.Factory wordPairsFactory = () => new WordPairsViewModel(busyService); var globalCorrespondences = new GlobalCorrespondencesViewModel(projectService, busyService, dialogService, imageExportService, graphService, wordPairsFactory); CogProject project = TestHelpers.GetTestProject(_spanFactory, segmentPool); project.Meanings.AddRange(new[] { new Meaning("gloss1", "cat1"), new Meaning("gloss2", "cat2"), new Meaning("gloss3", "cat3") }); project.Varieties.AddRange(new[] { new Variety("variety1"), new Variety("variety2"), new Variety("variety3") }); project.Varieties[0].Words.AddRange(new[] { new Word("hɛ.loʊ", project.Meanings[0]), new Word("gʊd", project.Meanings[1]), new Word("kæd", project.Meanings[2]) }); project.Varieties[1].Words.AddRange(new[] { new Word("hɛlp", project.Meanings[0]), new Word("gu.gəl", project.Meanings[1]), new Word("gu.fi", project.Meanings[2]) }); project.Varieties[2].Words.AddRange(new[] { new Word("wɜrd", project.Meanings[0]), new Word("kɑr", project.Meanings[1]), new Word("fʊt.bɔl", project.Meanings[2]) }); projectService.Project.Returns(project); analysisService.SegmentAll(); var varietyPairGenerator = new VarietyPairGenerator(); varietyPairGenerator.Process(project); var wordPairGenerator = new SimpleWordPairGenerator(segmentPool, project, 0.3, ComponentIdentifiers.PrimaryWordAligner); var globalCorrIdentifier = new SoundCorrespondenceIdentifier(segmentPool, project, ComponentIdentifiers.PrimaryWordAligner); foreach (VarietyPair vp in project.VarietyPairs) { wordPairGenerator.Process(vp); foreach (WordPair wp in vp.WordPairs) { wp.AreCognatePredicted = true; } vp.SoundChangeFrequencyDistribution = new ConditionalFrequencyDistribution <SoundContext, Ngram <Segment> >(); vp.SoundChangeProbabilityDistribution = new ConditionalProbabilityDistribution <SoundContext, Ngram <Segment> >(vp.SoundChangeFrequencyDistribution, (sc, fd) => new MaxLikelihoodProbabilityDistribution <Ngram <Segment> >(fd)); globalCorrIdentifier.Process(vp); } projectService.AreAllVarietiesCompared.Returns(true); projectService.ProjectOpened += Raise.Event(); WordPairsViewModel observedWordPairs = globalCorrespondences.ObservedWordPairs; observedWordPairs.WordPairsView = new ListCollectionView(observedWordPairs.WordPairs); FindViewModel findViewModel = null; Action closeCallback = null; dialogService.ShowModelessDialog(globalCorrespondences, Arg.Do <FindViewModel>(vm => findViewModel = vm), Arg.Do <Action>(callback => closeCallback = callback)); globalCorrespondences.FindCommand.Execute(null); Assert.That(findViewModel, Is.Not.Null); Assert.That(closeCallback, Is.Not.Null); // already open, shouldn't get opened twice dialogService.ClearReceivedCalls(); globalCorrespondences.FindCommand.Execute(null); dialogService.DidNotReceive().ShowModelessDialog(globalCorrespondences, Arg.Any <FindViewModel>(), Arg.Any <Action>()); // form searches findViewModel.Field = FindField.Form; // no word pairs, no match findViewModel.String = "nothing"; findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.Empty); globalCorrespondences.SelectedCorrespondence = globalCorrespondences.Graph.Edges.First(e => e.Source.StrRep == "k" && e.Target.StrRep == "g"); WordPairViewModel[] wordPairsArray = observedWordPairs.WordPairsView.Cast <WordPairViewModel>().ToArray(); // nothing selected, no match findViewModel.String = "nothing"; findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.Empty); // nothing selected, matches findViewModel.String = "d"; findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[1].ToEnumerable())); findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[2].ToEnumerable())); findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[2].ToEnumerable())); // first word selected, matches observedWordPairs.SelectedWordPairs.Clear(); observedWordPairs.SelectedWordPairs.Add(wordPairsArray[0]); findViewModel.String = "g"; findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[1].ToEnumerable())); findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[2].ToEnumerable())); findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[0].ToEnumerable())); findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[0].ToEnumerable())); // start search over findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[1].ToEnumerable())); // last word selected, matches observedWordPairs.SelectedWordPairs.Clear(); observedWordPairs.SelectedWordPairs.Add(wordPairsArray[2]); findViewModel.String = "u"; findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[0].ToEnumerable())); findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[2].ToEnumerable())); findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[2].ToEnumerable())); // nothing selected, matches, change selected word observedWordPairs.SelectedWordPairs.Clear(); findViewModel.String = "."; findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[0].ToEnumerable())); findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[2].ToEnumerable())); observedWordPairs.SelectedWordPairs.Clear(); observedWordPairs.SelectedWordPairs.Add(wordPairsArray[1]); findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[2].ToEnumerable())); findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[0].ToEnumerable())); findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[0].ToEnumerable())); // gloss searches findViewModel.Field = FindField.Gloss; findViewModel.String = "gloss2"; findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[1].ToEnumerable())); findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[0].ToEnumerable())); findViewModel.FindNextCommand.Execute(null); Assert.That(observedWordPairs.SelectedWordPairs, Is.EquivalentTo(wordPairsArray[0].ToEnumerable())); }
public async void ShouldPassExpectedParametersToKomfoProviderAndReturnResponse() { // arrange var komfoProvider = Substitute.For <IKomfoProvider>(); var configurationFactory = Substitute.For <IConfigurationProvider>(); var clientId = Guid.NewGuid().ToString(); var clientSecret = Guid.NewGuid().ToString(); var scopes = new[] { Guid.NewGuid().ToString() }; var token = new Token { AccessToken = Guid.NewGuid().ToString(), ExpiresIn = TimeSpan.FromDays(60) }; komfoProvider.RetrieveAccessTokenAsync(clientId, clientSecret, scopes).Returns(Task.FromResult(token)); // act using (var komfoSession = new NonAuthenticatedSession(configurationFactory, komfoProvider)) { var tokensRequest = komfoSession.Requests.OAuth20.Tokens .ClientId(clientId) .ClientSecret(clientSecret) .Scopes(scopes) .Create(); await komfoSession.ExecuteAsync(tokensRequest).ContinueWith(task => { // assert komfoProvider.Received(1).RetrieveAccessTokenAsync(Arg.Is(clientId), Arg.Is(clientSecret), Arg.Do <string[]>(strings => strings.ShouldAllBeEquivalentTo(scopes))); task.Result.Should().NotBeNull(); task.Result.Data.ShouldBeEquivalentTo(token); }); } }
public async Task Queue_Set_With_Set_Should_Insert_Sync_Job() { //Arrange var set1 = new Set(); var jobId1 = set1.Add <TestJobWithoutInput>(); var jobId2 = set1.Add <TestJobWithoutInput>(); var set2 = new Set(); var jobId3 = set2.Add <TestJobWithoutInput>(); var jobId4 = set2.Add <TestJobWithoutInput>(); var sequence = new Sequence(); sequence.Add(set1); sequence.Add(set2); var batch = new Batch(sequence); IEnumerable <JobDescription> jobs = null; await _store.AddJobsAsync(Arg.Do <IEnumerable <JobDescription> >(x => jobs = x)); //Act await _scheduler.QueueAsync(batch); //Assert await _store.Received(1).AddJobsAsync(jobs); var result1 = jobs.ElementAt(0); var result2 = jobs.ElementAt(1); var sync = jobs.ElementAt(2); var result3 = jobs.ElementAt(3); var result4 = jobs.ElementAt(4); Assert.Equal(batch.Id, result1.BatchId); Assert.Equal(batch.Id, result2.BatchId); Assert.Equal(batch.Id, sync.BatchId); Assert.Equal(batch.Id, result3.BatchId); Assert.Equal(batch.Id, result4.BatchId); Assert.Equal(_now, result1.CreatedTime); Assert.Equal(_now, result2.CreatedTime); Assert.Equal(_now, sync.CreatedTime); Assert.Equal(_now, result3.CreatedTime); Assert.Equal(_now, result4.CreatedTime); Assert.Equal(_now, result1.UpdatedTime); Assert.Equal(_now, result2.UpdatedTime); Assert.Equal(_now, sync.UpdatedTime); Assert.Equal(_now, result3.UpdatedTime); Assert.Equal(_now, result4.UpdatedTime); Assert.Equal(jobId1, result1.Id); Assert.Equal(jobId2, result2.Id); Assert.NotEqual(Guid.Empty, sync.Id); Assert.Equal(jobId3, result3.Id); Assert.Equal(jobId4, result4.Id); Assert.Equal(0, result1.WaitCount); Assert.Equal(0, result2.WaitCount); Assert.Equal(2, sync.WaitCount); Assert.Equal(1, result3.WaitCount); Assert.Equal(1, result4.WaitCount); Assert.Null(result1.PrevId); Assert.Null(result2.PrevId); Assert.Null(sync.PrevId); Assert.Equal(sync.Id, result3.PrevId); Assert.Equal(sync.Id, result4.PrevId); Assert.Equal(sync.Id, result1.NextId); Assert.Equal(sync.Id, result2.NextId); Assert.Null(sync.NextId); Assert.Null(result3.NextId); Assert.Null(result4.NextId); Assert.Equal(typeof(SyncJob).AssemblyQualifiedName, sync.Type); Assert.Null(sync.Input); Assert.Equal(ExecutionState.Waiting, sync.State); }
public void OpenFindDialog() { _dialogService.ShowModelessDialog(_varietiesViewModel, Arg.Do <FindViewModel>(vm => _findViewModel = vm), Arg.Any <Action>()); _varietiesViewModel.FindCommand.Execute(null); }
public void TestGetTaskListReturnsItems() { // GIVEN var taskList = new Models.TalendApiListResponseRaw <Models.Task> { ReturnCode = 0, ExecutionTime = new Models.TalendApiResponse.Executiontime { millis = 500, seconds = 2 }, Results = new System.Collections.Generic.List <Models.Task> { new Models.Task { active = "true", id = "123", label = "test-task", addStatisticsCodeEnabled = "true", applicationBundleName = "org.rsc", applicationFeatureURL = "url", applicationGroup = "org.rsc", applicationId = "50", applicationName = "one", applicationType = "first", applicationVersion = "0.1.1", applyContextToChildren = "true", artifactGroupId = "org.rsc", artifactId = "org.rsc", artifactVersion = "0.5", awaitingExecutions = "true", branch = "branch", commandLineVersion = "0.1", concurrentExecution = "true", contextName = "context", description = "describe this", errorStatus = "errored", execStatisticsEnabled = "false", executionServerId = "013", featuresName = "feature2", featuresVersion = "feature0.5.1", framework = "framework1", frozenExecutions = "execute2", idQuartzJob = "id1", jobscriptarchivefilename = "/first/folder", jobServerLabelHost = "label", lastDeploymentDate = "one", lastEndedRunDate = "1/1/1999", lastRunDate = "first", lastScriptGenerationDate = "1/12/2011", lastTaskTraceError = "errored somewhere", latestVersion = "0.2", log4jLevel = "WARN", nextFireDate = "05/05/2022", onlineStatus = "online", onUnknownStateJob = "unknown", originType = "origin", pid = "123", processingState = "BLOCKED", projectId = "42", projectName = "project one", regenerateJobOnChange = "regenerate", remaingTimeForNextFire = "10 minutes", repositoryName = "repo2", runAsUser = "******", snapshot = "true", status = "active", svnConnectionAvailable = "false", svnRevision = "0.1.5.2", taskType = "ESB", timeOut = "5 minutes", triggersStatus = "status", virtualServerLabel = "virtual label" } } }; var response = Substitute.For <RestResponse <Models.TalendApiListResponseRaw <Models.Task> > >(); response.Data = taskList; var apiCommand = new Models.ApiCommandRequest { authPass = _settings.TalendAdminPassword, authUser = _settings.TalendAdminUsername, actionName = TalendAdminApiCommands.LIST_TASKS }; var encodedApiCommand = GetMetaservletCommand(apiCommand); var restClient = Substitute.For <IRestClient>(); restClient.Execute <Models.TalendApiListResponseRaw <Models.Task> >( Arg.Do <RestRequest>(x => x.Resource.ShouldEqual($"metaServlet?{encodedApiCommand}"))).Returns(response); // WHEN ITalendAdminApi api = new TalendAdminApi(_settings.TalendAdminAddress, _settings.TalendAdminUsername, _settings.TalendAdminPassword, restClient); var items = api.GetTaskList(); // THEN items.ShouldNotBeEmpty(); items.First().id.ShouldEqual("123"); items.First().label.ShouldEqual("test-task"); }
public async Task CourseDirectoryDataService_ImportProviders_With_Multiple_Items_Returns_Expected_Result() { var httpClientFactory = Substitute.For <IHttpClientFactory>(); httpClientFactory .CreateClient(CourseDirectoryDataService.CourseDirectoryHttpClientName) .Returns(new TestHttpClientFactory() .CreateHttpClientWithBaseUri(SettingsBuilder.FindCourseApiBaseUri, CourseDirectoryDataService.CourseDetailEndpoint, new CourseDirectoryJsonBuilder() .BuildValidTLevelsMultiItemResponse())); var deletedProviders = new List <Provider>(); var savedProviders = new List <Provider>(); //Get a list of providers and change one var providers = new ProviderListBuilder().CreateKnownList().Build(); providers.Single(p => p.UkPrn == 10000055) .Locations.First() .Name = "Old Venue Name"; var tableStorageService = Substitute.For <ITableStorageService>(); tableStorageService .GetAllProviders() .Returns(providers); tableStorageService .RemoveProviders( Arg.Do <IList <Provider> >(p => deletedProviders.AddRange(p))) .Returns(x => ((IList <Provider>)x[0]).Count); tableStorageService .SaveProviders( Arg.Do <IList <Provider> >(p => savedProviders.AddRange(p))) .Returns(x => ((IList <Provider>)x[0]).Count); var logger = Substitute.For <ILogger <CourseDirectoryDataService> >(); var service = BuildCourseDirectoryDataService(httpClientFactory, tableStorageService, logger); var(savedCount, deletedCount) = await service .ImportProvidersFromCourseDirectoryApi(); savedCount.Should().Be(1); deletedCount.Should().Be(1); savedProviders.Should().HaveCount(1); deletedProviders.Should().HaveCount(1); deletedProviders.Should().HaveCount(1); ValidateProvider(deletedProviders[0], 10000001, "TEST COLLEGE TO BE DELETED"); var provider = savedProviders.OrderBy(p => p.Name).First(); ValidateProvider(provider, 10000055, "ABINGDON AND WITNEY COLLEGE"); provider.Locations.Should().HaveCount(1); var firstLocation = provider.Locations.OrderBy(l => l.Name).First(); ValidateLocation(firstLocation, "ABINGDON CAMPUS", "OX14 1GG", "Abingdon", "http://www.abingdon-witney.ac.uk", 51.680637, -1.286943); ValidateDeliveryYear(firstLocation.DeliveryYears.First(), 2021, new[] { 36 }); const string expectedMessage = "Venue name for 10000055 ABINGDON AND WITNEY COLLEGE OX14 1GG changed from 'Old Venue Name' to 'ABINGDON CAMPUS'"; logger.ReceivedCalls() .Select(call => call.GetArguments()) .Count(callArguments => { var logLevel = (LogLevel)callArguments[0]; var logValues = (IReadOnlyList <KeyValuePair <string, object> >)callArguments[2]; return(logLevel.Equals(LogLevel.Warning) && logValues[^ 1].Value.Equals(expectedMessage)); }) .Should().Be(1); }
public void Setup() { var asyncClient = Substitute.For <IOctopusAsyncClient>(); asyncRepository = new OctopusAsyncRepository(asyncClient); asyncClient.Post <ConvertProjectToGitCommand, ConvertProjectToGitResponse>(Arg.Do <string>(x => asyncUrlUsed = x), Arg.Any <ConvertProjectToGitCommand>()).Returns(new ConvertProjectToGitResponse()); var syncClient = Substitute.For <IOctopusClient>(); syncRepository = new OctopusRepository(syncClient); syncClient.Post <ConvertProjectToGitCommand, ConvertProjectToGitResponse>(Arg.Do <string>(x => syncUrlUsed = x), Arg.Any <ConvertProjectToGitCommand>()).Returns(new ConvertProjectToGitResponse()); }
private void GivenAnAdminIsCreated() { _userService.AddUser(Arg.Do <UserRow>(x => _createdAdminUser = x)); }
public SmartOnFhirAuditLoggingFilterAttributeTests() { _correlationId = Guid.NewGuid().ToString(); _fhirRequestContextAccessor.FhirRequestContext.CorrelationId.Returns(_correlationId); _filter = new SmartOnFhirAuditLoggingFilterAttribute(Action, _auditLogger, _fhirRequestContextAccessor); _auditLogger.LogAudit(Arg.Any <AuditAction>(), Arg.Any <string>(), Arg.Any <string>(), Arg.Any <Uri>(), Arg.Any <HttpStatusCode?>(), Arg.Any <string>(), Arg.Do <IReadOnlyCollection <KeyValuePair <string, string> > >(c => _loggedClaims = c)); var passedValues = new Dictionary <string, StringValues> { { "client_id", new StringValues("1234") }, { "secret", new StringValues("secret") }, }; _queryCollection = new QueryCollection( passedValues); _formCollection = new FormCollection( passedValues); }
public async Task ReIndexAllocationNotificationFeeds_GivenResultHasProviderDataChange_AndHasNotBeenVariedInAnyOtherWay_IndexesAndReturnsNoContentResult() { //Arrange Message message = new Message(); const string specificationId = "spec-1"; IEnumerable <PublishedProviderResult> results = CreatePublishedProviderResultsWithDifferentProviders(); foreach (PublishedProviderResult result in results) { result.FundingStreamResult.AllocationLineResult.Current.Status = AllocationLineStatus.Approved; result.FundingStreamResult.AllocationLineResult.Current.ProfilingPeriods = new[] { new ProfilingPeriod() }; result.FundingStreamResult.AllocationLineResult.Current.FinancialEnvelopes = new[] { new FinancialEnvelope() }; result.FundingStreamResult.AllocationLineResult.Current.Calculations = new[] { new PublishedProviderCalculationResult { CalculationSpecification = new Common.Models.Reference("calc-id-1", "calc1"), Policy = new PolicySummary("policy-id-1", "policy1", "desc") }, new PublishedProviderCalculationResult { CalculationSpecification = new Common.Models.Reference("calc-id-2", "calc2"), Policy = new PolicySummary("policy-id-1", "policy1", "desc") }, new PublishedProviderCalculationResult { CalculationSpecification = new Common.Models.Reference("calc-id-3", "calc3"), Policy = new PolicySummary("policy-id-2", "policy2", "desc") }, }; } PublishedAllocationLineResult publishedAllocationLineResult = results.First().FundingStreamResult.AllocationLineResult; publishedAllocationLineResult.HasResultBeenVaried = false; publishedAllocationLineResult.Current.VariationReasons = new[] { VariationReason.AuthorityFieldUpdated, VariationReason.NameFieldUpdated }; IPublishedProviderResultsRepository repository = CreatePublishedProviderResultsRepository(); repository .GetAllNonHeldPublishedProviderResults() .Returns(results); IEnumerable <PublishedAllocationLineResultVersion> history = results.Select(m => m.FundingStreamResult.AllocationLineResult.Current); history.ElementAt(0).Status = AllocationLineStatus.Approved; history.ElementAt(1).Status = AllocationLineStatus.Approved; history.ElementAt(2).Status = AllocationLineStatus.Published; foreach (var providerVersion in history.GroupBy(c => c.PublishedProviderResultId)) { if (providerVersion.Any()) { IEnumerable <PublishedAllocationLineResultVersion> providerHistory = providerVersion.AsEnumerable(); string providerId = providerHistory.First().ProviderId; providerId .Should() .NotBeNullOrWhiteSpace(); repository .GetAllNonHeldPublishedProviderResultVersions(Arg.Is(providerVersion.Key), Arg.Is(providerId)) .Returns(providerHistory); } } ILogger logger = CreateLogger(); ISearchRepository <AllocationNotificationFeedIndex> searchRepository = CreateAllocationNotificationFeedSearchRepository(); SpecificationCurrentVersion specification = CreateSpecification(specificationId); ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository(); specificationsRepository .GetCurrentSpecificationById(Arg.Is(specificationId)) .Returns(specification); IEnumerable <AllocationNotificationFeedIndex> resultsBeingSaved = null; await searchRepository .Index(Arg.Do <IEnumerable <AllocationNotificationFeedIndex> >(r => resultsBeingSaved = r)); PublishedResultsService resultsService = CreateResultsService( logger, publishedProviderResultsRepository: repository, allocationNotificationFeedSearchRepository: searchRepository, specificationsRepository: specificationsRepository); //Act await resultsService.ReIndexAllocationNotificationFeeds(message); //Assert await searchRepository .Received(1) .Index(Arg.Is <IEnumerable <AllocationNotificationFeedIndex> >(m => m.Count() == 3)); AllocationNotificationFeedIndex feedResult = resultsBeingSaved.FirstOrDefault(m => m.ProviderId == "1111"); feedResult.ProviderId.Should().Be("1111"); feedResult.Title.Should().Be("Allocation test allocation line 1 was Approved"); feedResult.Summary.Should().Be("UKPRN: 1111, version 0.1"); feedResult.DatePublished.HasValue.Should().Be(false); feedResult.FundingStreamId.Should().Be("fs-1"); feedResult.FundingStreamName.Should().Be("funding stream 1"); feedResult.FundingPeriodId.Should().Be("1819"); feedResult.ProviderUkPrn.Should().Be("1111"); feedResult.ProviderUpin.Should().Be("2222"); feedResult.AllocationLineId.Should().Be("AAAAA"); feedResult.AllocationLineName.Should().Be("test allocation line 1"); feedResult.AllocationVersionNumber.Should().Be(1); feedResult.AllocationAmount.Should().Be(50.0); feedResult.ProviderProfiling.Should().Be("[{\"period\":null,\"occurrence\":0,\"periodYear\":0,\"periodType\":null,\"profileValue\":0.0,\"distributionPeriod\":null}]"); feedResult.ProviderName.Should().Be("test provider name 1"); feedResult.LaCode.Should().Be("77777"); feedResult.Authority.Should().Be("London"); feedResult.ProviderType.Should().Be("test type"); feedResult.SubProviderType.Should().Be("test sub type"); feedResult.EstablishmentNumber.Should().Be("es123"); feedResult.FundingPeriodStartYear.Should().Be(DateTime.Now.Year); feedResult.FundingPeriodEndYear.Should().Be(DateTime.Now.Year + 1); feedResult.FundingStreamStartDay.Should().Be(1); feedResult.FundingStreamStartMonth.Should().Be(8); feedResult.FundingStreamEndDay.Should().Be(31); feedResult.FundingStreamEndMonth.Should().Be(7); feedResult.FundingStreamPeriodName.Should().Be("period-type 1"); feedResult.FundingStreamPeriodId.Should().Be("pt1"); feedResult.AllocationLineContractRequired.Should().Be(true); feedResult.AllocationLineFundingRoute.Should().Be("LA"); feedResult.AllocationLineShortName.Should().Be("tal1"); feedResult.PolicySummaries.Should().Be("[{\"policy\":{\"description\":\"test decscription\",\"parentPolicyId\":null,\"id\":\"policy-1\",\"name\":\"policy one\"},\"policies\":[{\"policy\":{\"description\":\"test decscription\",\"parentPolicyId\":null,\"id\":\"subpolicy-1\",\"name\":\"sub policy one\"},\"policies\":[],\"calculations\":[]}],\"calculations\":[]}]"); feedResult.Calculations.Should().Be("[{\"calculationName\":\"calc1\",\"calculationDisplayName\":\"calc1\",\"calculationVersion\":0,\"calculationType\":\"Number\",\"calculationAmount\":null,\"allocationLineId\":\"AAAAA\",\"policyId\":\"policy-id-1\",\"policyName\":\"policy1\"},{\"calculationName\":\"calc2\",\"calculationDisplayName\":\"calc2\",\"calculationVersion\":0,\"calculationType\":\"Number\",\"calculationAmount\":null,\"allocationLineId\":\"AAAAA\",\"policyId\":\"policy-id-1\",\"policyName\":\"policy1\"},{\"calculationName\":\"calc3\",\"calculationDisplayName\":\"calc3\",\"calculationVersion\":0,\"calculationType\":\"Number\",\"calculationAmount\":null,\"allocationLineId\":\"AAAAA\",\"policyId\":\"policy-id-2\",\"policyName\":\"policy2\"}]"); feedResult.OpenReason.Should().BeNull(); feedResult.CloseReason.Should().BeNull(); feedResult.Predecessors.Should().BeNull(); feedResult.Successors.Should().BeNull(); }