public void OrdinalInsensitiveKeyComparison() { var headerDict = new HeaderDictionary(); headerDict.Add("Name", new string[1] { "Value" }); Assert.Throws<ArgumentException>(() => headerDict.Add("nAmE", new string[1] { "whatever" })); }
private static HttpResponse GetResponseWithHeader(string headerName, string headerValue) { var headers = new HeaderDictionary(); if (headerValue != null) { headers.Add(headerName, headerValue); } return CreateResponse(headers); }
public void HeadersValuesAreArrayCopies() { var headerDict = new HeaderDictionary(); headerDict.Add("Name", new string[1] { "Value" }); string[] copy = headerDict["Name"]; Assert.AreEqual("Value", copy [0]); // Change and make sure it is still the same in the original! copy [0] = "Something different"; string[] copy2 = headerDict["Name"]; Assert.AreEqual("Value", copy2 [0]); }
public async Task ShouldGetImmunizations() { // Setup string hdid = "EXTRIOYFPNX35TWEBUAJ3DNFDFXSYTBC6J4M76GYE3HC5ER2NKWQ"; string token = "Fake Access Token"; string userId = "1001"; var expectedAgents = new List <ImmunizationAgent>(); expectedAgents.Add(new ImmunizationAgent() { Name = "mocked agent", Code = "mocked code", LotNumber = "mocekd lot number", ProductName = "mocked product", }); var expectedImmunizations = new List <ImmunizationEvent>(); expectedImmunizations.Add(new ImmunizationEvent() { DateOfImmunization = DateTime.Today, ProviderOrClinic = "Mocked Clinic", Immunization = new ImmunizationDefinition() { Name = "Mocked Name", ImmunizationAgents = expectedAgents } }); // Add a blank agent expectedImmunizations.Add(new ImmunizationEvent() { DateOfImmunization = DateTime.Today, Immunization = new ImmunizationDefinition() { Name = "Mocked Name", ImmunizationAgents = expectedAgents } }); var expectedImmzResult = new ImmunizationResult() { Immunizations = expectedImmunizations, LoadState = new LoadStateModel() { RefreshInProgress = false }, }; RequestResult <ImmunizationResult> expectedRequestResult = new RequestResult <ImmunizationResult>() { ResultStatus = Common.Constants.ResultType.Success, TotalResultCount = 2, ResourcePayload = expectedImmzResult, }; IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary.Add("Authorization", token); Mock <HttpRequest> httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(s => s.Headers).Returns(headerDictionary); List <Claim> claims = new List <Claim>() { new Claim(ClaimTypes.Name, "username"), new Claim(ClaimTypes.NameIdentifier, userId), new Claim("hdid", hdid), }; ClaimsIdentity identity = new ClaimsIdentity(claims, "TestAuth"); ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity); Mock <HttpContext> httpContextMock = new Mock <HttpContext>(); httpContextMock.Setup(s => s.User).Returns(claimsPrincipal); httpContextMock.Setup(s => s.Request).Returns(httpRequestMock.Object); Mock <IHttpContextAccessor> httpContextAccessorMock = new Mock <IHttpContextAccessor>(); httpContextAccessorMock.Setup(s => s.HttpContext).Returns(httpContextMock.Object); Mock <IAuthenticationService> authenticationMock = new Mock <IAuthenticationService>(); httpContextAccessorMock .Setup(x => x.HttpContext.RequestServices.GetService(typeof(IAuthenticationService))) .Returns(authenticationMock.Object); var authResult = AuthenticateResult.Success(new AuthenticationTicket(claimsPrincipal, JwtBearerDefaults.AuthenticationScheme)); authResult.Properties.StoreTokens(new[] { new AuthenticationToken { Name = "access_token", Value = token } }); authenticationMock .Setup(x => x.AuthenticateAsync(httpContextAccessorMock.Object.HttpContext, It.IsAny <string>())) .ReturnsAsync(authResult); Mock <IImmunizationService> svcMock = new Mock <IImmunizationService>(); svcMock.Setup(s => s.GetImmunizations(token, 0)).ReturnsAsync(expectedRequestResult); using var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); ImmunizationController controller = new ImmunizationController(loggerFactory.CreateLogger <ImmunizationController>(), svcMock.Object, httpContextAccessorMock.Object); // Act IActionResult actual = await controller.GetImmunizations(hdid); // Verify Assert.IsType <JsonResult>(actual); JsonResult jsonResult = (JsonResult)actual; Assert.IsType <RequestResult <ImmunizationResult> >(jsonResult.Value); RequestResult <ImmunizationResult> result = (RequestResult <ImmunizationResult>)jsonResult.Value; Assert.Equal(Common.Constants.ResultType.Success, result.ResultStatus); int count = 0; foreach (var immz in result.ResourcePayload.Immunizations) { count++; } Assert.Equal(2, count); }
public async Task GetLabOrderError() { // Setup string hdid = "EXTRIOYFPNX35TWEBUAJ3DNFDFXSYTBC6J4M76GYE3HC5ER2NKWQ"; string token = "Fake Access Token"; string userId = "1001"; IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary.Add("Authorization", token); Mock <HttpRequest> httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(s => s.Headers).Returns(headerDictionary); List <Claim> claims = new List <Claim>() { new Claim(ClaimTypes.Name, "username"), new Claim(ClaimTypes.NameIdentifier, userId), new Claim("hdid", hdid), }; ClaimsIdentity identity = new ClaimsIdentity(claims, "TestAuth"); ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity); Mock <HttpContext> httpContextMock = new Mock <HttpContext>(); httpContextMock.Setup(s => s.User).Returns(claimsPrincipal); httpContextMock.Setup(s => s.Request).Returns(httpRequestMock.Object); Mock <IHttpContextAccessor> httpContextAccessorMock = new Mock <IHttpContextAccessor>(); httpContextAccessorMock.Setup(s => s.HttpContext).Returns(httpContextMock.Object); Mock <IAuthenticationService> authenticationMock = new Mock <IAuthenticationService>(); httpContextAccessorMock .Setup(x => x.HttpContext !.RequestServices.GetService(typeof(IAuthenticationService))) .Returns(authenticationMock.Object); var authResult = AuthenticateResult.Success(new AuthenticationTicket(claimsPrincipal, JwtBearerDefaults.AuthenticationScheme)); authResult.Properties !.StoreTokens(new[] { new AuthenticationToken { Name = "access_token", Value = token, }, }); authenticationMock .Setup(x => x.AuthenticateAsync(httpContextAccessorMock.Object !.HttpContext !, It.IsAny <string>())) .ReturnsAsync(authResult); Mock <ILaboratoryService> svcMock = new Mock <ILaboratoryService>(); svcMock.Setup(s => s.GetLaboratoryOrders(token, hdid, 0)).ReturnsAsync(new RequestResult <IEnumerable <LaboratoryModel> >() { ResultStatus = Common.Constants.ResultType.Error, ResultError = new RequestResultError() { ResultMessage = "Test Error" }, TotalResultCount = 0, }); using var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); LaboratoryController controller = new LaboratoryController(loggerFactory.CreateLogger <LaboratoryController>(), svcMock.Object, httpContextAccessorMock.Object); // Act IActionResult actual = await controller.GetLaboratoryOrders(hdid).ConfigureAwait(true); // Verify Assert.IsType <JsonResult>(actual); JsonResult jsonResult = (JsonResult)actual; Assert.IsType <RequestResult <IEnumerable <LaboratoryModel> > >(jsonResult.Value); RequestResult <IEnumerable <LaboratoryModel> > result = (RequestResult <IEnumerable <LaboratoryModel> >)jsonResult.Value; Assert.True(result.ResultStatus == Common.Constants.ResultType.Error); }
internal static bool TryGetServiceMessage(this HttpRequestPacket request, out ServiceMessage message) { if (request == null) { throw new ArgumentNullException("request"); } message = new ServiceMessage(); //Build Request IHttpRequestFeature req = message as IHttpRequestFeature; Uri uri; try { uri = request.BuildUri(null, null); } catch { message = null; return(false); } req.Path = uri.AbsolutePath; req.Protocol = "HTTP/" + request.Version; req.QueryString = uri.Query; req.Method = request.Method; if (request.Content != null && request.Content.Length > 0) { message.CreateRequestBody(request.Content); } //Add Request Headers { var headers = new HeaderDictionary(); foreach (var hdr in request.Headers) { if (hdr.Key != null && hdr.Key.Trim().ToUpperInvariant() == "CONTENT-LENGTH") { continue; // Content-length is calculated based on actual content. } //NOTE: Client already folds Request Headers into RequestPacket, so there's no need to fold it again here. headers.Add(hdr.Key, hdr.Value.ToArray()); } if (message.OriginalRequestBody != null) { headers.Add("Content-Length", request.Content.Length.ToString()); } req.Headers = headers; } //Create Response message.CreateResponseBody(); IHttpResponseFeature resp = message as IHttpResponseFeature; resp.StatusCode = 200; //Add Response Headers { var headers = new HeaderDictionary(); headers.Add("Server", HTTP_RESPONSE_SERVER_HEADER[0]); resp.Headers = headers; } return(true); }
public async Task SaveDefinition_GivenValidYamlAndDoesContainsExistingItemWithNoModelUpdates_ThenDoesNotAddMessageToTopicAndReturnsOK() { //Arrange string yaml = CreateRawDefinition(); string definitionId = "9183"; byte[] byteArray = Encoding.UTF8.GetBytes(yaml); MemoryStream stream = new MemoryStream(byteArray); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary .Add("yaml-file", new StringValues(yamlFile)); HttpRequest request = Substitute.For <HttpRequest>(); request .Headers .Returns(headerDictionary); request .Body .Returns(stream); ILogger logger = CreateLogger(); HttpStatusCode statusCode = HttpStatusCode.Created; DatasetDefinition existingDatasetDefinition = new DatasetDefinition { Id = definitionId }; IDatasetRepository datasetsRepository = CreateDataSetsRepository(); datasetsRepository .SaveDefinition(Arg.Any <DatasetDefinition>()) .Returns(statusCode); datasetsRepository .GetDatasetDefinition(Arg.Is(definitionId)) .Returns(existingDatasetDefinition); byte[] excelAsBytes = new byte[100]; IExcelWriter <DatasetDefinition> excelWriter = CreateExcelWriter(); excelWriter .Write(Arg.Any <DatasetDefinition>()) .Returns(excelAsBytes); ICloudBlob blob = Substitute.For <ICloudBlob>(); IBlobClient blobClient = CreateBlobClient(); blobClient .GetBlockBlobReference(Arg.Any <string>()) .Returns(blob); DatasetDefinitionChanges datasetDefinitionChanges = new DatasetDefinitionChanges(); IDefinitionChangesDetectionService definitionChangesDetectionService = CreateChangesDetectionService(); definitionChangesDetectionService .DetectChanges(Arg.Any <DatasetDefinition>(), Arg.Is(existingDatasetDefinition)) .Returns(datasetDefinitionChanges); IMessengerService messengerService = CreateMessengerService(); DefinitionsService service = CreateDefinitionsService( logger, datasetsRepository, excelWriter: excelWriter, blobClient: blobClient, definitionChangesDetectionService: definitionChangesDetectionService, messengerService: messengerService); //Act IActionResult result = await service.SaveDefinition(request); //Assert result .Should() .BeOfType <OkResult>(); await messengerService .DidNotReceive() .SendToTopic( Arg.Is(ServiceBusConstants.TopicNames.DataDefinitionChanges), Arg.Any <DatasetDefinitionChanges>(), Arg.Any <IDictionary <string, string> >()); }
public async Task GetNotifications_GivenSearchFeedReturnsResultsButTitleIsBlank_EnsuresTitleGenerated() { //Arrange IEnumerable <AllocationNotificationFeedIndex> allocationNotificationFeeds = CreateFeedIndexes(); allocationNotificationFeeds.First().Title = null; SearchFeed <AllocationNotificationFeedIndex> feeds = new SearchFeed <AllocationNotificationFeedIndex> { PageRef = 3, Top = 500, TotalCount = 3, Entries = allocationNotificationFeeds }; IAllocationNotificationsFeedsSearchService feedsSearchService = CreateSearchService(); feedsSearchService .GetFeeds(Arg.Is(3), Arg.Is(2), Arg.Any <IEnumerable <string> >()) .Returns(feeds); AllocationNotificationFeedsService service = CreateService(feedsSearchService); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary.Add("Accept", new StringValues("application/json")); IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues> { { "pageRef", new StringValues("3") }, { "allocationStatuses", new StringValues("Published,Approved") }, { "pageSize", new StringValues("2") } }); HttpRequest request = Substitute.For <HttpRequest>(); request.Scheme.Returns("https"); request.Path.Returns(new PathString("/api/v1/test")); request.Host.Returns(new HostString("wherever.naf:12345")); request.QueryString.Returns(new QueryString("?pageRef=3&pageSize=2&allocationStatuses=Published,Approved")); request.Headers.Returns(headerDictionary); request.Query.Returns(queryStringValues); //Act IActionResult result = await service.GetNotifications(3, "Published,Approved", 2, request); //Assert result .Should() .BeOfType <ContentResult>(); ContentResult contentResult = result as ContentResult; AtomFeed <AllocationModel> atomFeed = JsonConvert.DeserializeObject <AtomFeed <AllocationModel> >(contentResult.Content); atomFeed .Should() .NotBeNull(); atomFeed.AtomEntry.ElementAt(0).Title.Should().Be("Allocation al 1 was Published"); }
async public Task SaveDefinition_GivenValidYamlButFailsToGenerateExcelFile_ReturnsInvalidServerError() { //Arrange string yaml = CreateRawDefinition(); string definitionId = "9183"; byte[] byteArray = Encoding.UTF8.GetBytes(yaml); MemoryStream stream = new MemoryStream(byteArray); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary .Add("yaml-file", new StringValues(yamlFile)); HttpRequest request = Substitute.For <HttpRequest>(); request .Headers .Returns(headerDictionary); request .Body .Returns(stream); ILogger logger = CreateLogger(); HttpStatusCode statusCode = HttpStatusCode.Created; IDatasetRepository datasetsRepository = CreateDataSetsRepository(); datasetsRepository .SaveDefinition(Arg.Any <DatasetDefinition>()) .Returns(statusCode); ISearchRepository <DatasetDefinitionIndex> searchRepository = CreateDatasetDefinitionSearchRepository(); searchRepository .SearchById(Arg.Is(definitionId)) .Returns((DatasetDefinitionIndex)null); byte[] excelAsBytes = new byte[0]; IExcelWriter <DatasetDefinition> excelWriter = CreateExcelWriter(); excelWriter .Write(Arg.Any <DatasetDefinition>()) .Returns(excelAsBytes); DatasetDefinitionChanges datasetDefinitionChanges = new DatasetDefinitionChanges(); IDefinitionChangesDetectionService definitionChangesDetectionService = CreateChangesDetectionService(); definitionChangesDetectionService .DetectChanges(Arg.Any <DatasetDefinition>(), Arg.Any <DatasetDefinition>()) .Returns(datasetDefinitionChanges); DefinitionsService service = CreateDefinitionsService(logger, datasetsRepository, searchRepository, excelWriter: excelWriter, definitionChangesDetectionService: definitionChangesDetectionService); //Act IActionResult result = await service.SaveDefinition(request); //Assert result .Should() .BeOfType <InternalServerErrorResult>() .Which .Value .Should() .Be($"Failed to generate excel file for 14/15"); logger .Received(1) .Error(Arg.Is($"Failed to generate excel file for 14/15")); }
async public Task SaveDefinition_GivenValidYamlAndSearchDoesNotContainExistingItem_ThenSaveWasSuccesfulAndReturnsOK() { //Arrange string yaml = CreateRawDefinition(); string definitionId = "9183"; byte[] byteArray = Encoding.UTF8.GetBytes(yaml); MemoryStream stream = new MemoryStream(byteArray); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary .Add("yaml-file", new StringValues(yamlFile)); HttpRequest request = Substitute.For <HttpRequest>(); request .Headers .Returns(headerDictionary); request .Body .Returns(stream); ILogger logger = CreateLogger(); HttpStatusCode statusCode = HttpStatusCode.Created; IDatasetRepository datasetsRepository = CreateDataSetsRepository(); datasetsRepository .SaveDefinition(Arg.Any <DatasetDefinition>()) .Returns(statusCode); ISearchRepository <DatasetDefinitionIndex> searchRepository = CreateDatasetDefinitionSearchRepository(); searchRepository .SearchById(Arg.Is(definitionId)) .Returns((DatasetDefinitionIndex)null); byte[] excelAsBytes = new byte[100]; IExcelWriter <DatasetDefinition> excelWriter = CreateExcelWriter(); excelWriter .Write(Arg.Any <DatasetDefinition>()) .Returns(excelAsBytes); ICloudBlob blob = Substitute.For <ICloudBlob>(); IBlobClient blobClient = CreateBlobClient(); blobClient .GetBlockBlobReference(Arg.Any <string>()) .Returns(blob); DatasetDefinitionChanges datasetDefinitionChanges = new DatasetDefinitionChanges(); IDefinitionChangesDetectionService definitionChangesDetectionService = CreateChangesDetectionService(); definitionChangesDetectionService .DetectChanges(Arg.Any <DatasetDefinition>(), Arg.Any <DatasetDefinition>()) .Returns(datasetDefinitionChanges); DefinitionsService service = CreateDefinitionsService(logger, datasetsRepository, searchRepository, excelWriter: excelWriter, blobClient: blobClient, definitionChangesDetectionService: definitionChangesDetectionService); //Act IActionResult result = await service.SaveDefinition(request); //Assert result .Should() .BeOfType <OkResult>(); await searchRepository .Received(1) .SearchById(Arg.Is(definitionId)); await searchRepository .Received(1) .Index(Arg.Is <IEnumerable <DatasetDefinitionIndex> >( i => i.First().Description == "14/15 description" && i.First().Id == "9183" && !string.IsNullOrWhiteSpace(i.First().ModelHash) && i.First().Name == "14/15" && i.First().ProviderIdentifier == "None" )); await datasetsRepository .Received(1) .SaveDefinition(Arg.Is <DatasetDefinition>( i => i.Description == "14/15 description" && i.Id == "9183" && i.Name == "14/15" )); logger .Received(1) .Information(Arg.Is($"Successfully saved file: {yamlFile} to cosmos db")); }
public void ShouldGetMedicationsProvLookup() { // Setup string hdid = "EXTRIOYFPNX35TWEBUAJ3DNFDFXSYTBC6J4M76GYE3HC5ER2NKWQ"; string phn = "0009735353315"; string userId = "1001"; string ipAddress = "10.0.0.1"; string DIN = "00000000"; Mock <IIdentity> identityMock = new Mock <IIdentity>(); identityMock.Setup(s => s.Name).Returns(userId); Mock <ClaimsPrincipal> claimsPrincipalMock = new Mock <ClaimsPrincipal>(); claimsPrincipalMock.Setup(s => s.Identity).Returns(identityMock.Object); Mock <ConnectionInfo> connectionInfoMock = new Mock <ConnectionInfo>(); connectionInfoMock.Setup(s => s.RemoteIpAddress).Returns(IPAddress.Parse(ipAddress)); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary.Add("Authorization", "Bearer TestJWT"); Mock <HttpRequest> httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(s => s.Headers).Returns(headerDictionary); Mock <HttpContext> httpContextMock = new Mock <HttpContext>(); httpContextMock.Setup(s => s.Connection).Returns(connectionInfoMock.Object); httpContextMock.Setup(s => s.User).Returns(claimsPrincipalMock.Object); httpContextMock.Setup(s => s.Request).Returns(httpRequestMock.Object); Mock <IHttpContextAccessor> httpContextAccessorMock = new Mock <IHttpContextAccessor>(); httpContextAccessorMock.Setup(s => s.HttpContext).Returns(httpContextMock.Object); Mock <IPatientService> patientDelegateMock = new Mock <IPatientService>(); patientDelegateMock.Setup(s => s.GetPatient(hdid, Common.Constants.PatientIdentifierType.HDID)).Returns(Task.FromResult( new RequestResult <PatientModel>() { ResourcePayload = new PatientModel() { Birthdate = DateTime.Parse("2000/01/31"), FirstName = "Patient", LastName = "Zero", EmailAddress = "*****@*****.**", HdId = hdid, PersonalHealthNumber = phn, }, ResultStatus = Common.Constants.ResultType.Success, })); Mock <IDrugLookupDelegate> drugLookupDelegateMock = new Mock <IDrugLookupDelegate>(); // We need two tests, one for Fed data and one for Provincial data List <PharmaCareDrug> drugList = new List <PharmaCareDrug>() { new PharmaCareDrug() { DINPIN = DIN, BrandName = "Brand Name" }, }; drugLookupDelegateMock.Setup(p => p.GetDrugProductsByDIN(It.IsAny <List <string> >())).Returns(new List <DrugProduct>()); drugLookupDelegateMock.Setup(p => p.GetPharmaCareDrugsByDIN(It.IsAny <List <string> >())).Returns(drugList); Mock <IMedStatementDelegate> medStatementDelegateMock = new Mock <IMedStatementDelegate>(); RequestResult <MedicationHistoryResponse> requestResult = new RequestResult <MedicationHistoryResponse>() { ResultStatus = Common.Constants.ResultType.Success, ResourcePayload = new MedicationHistoryResponse() { TotalRecords = 1, Pages = 1, Results = new List <Models.ODR.MedicationResult>() { new Models.ODR.MedicationResult() { DIN = DIN, GenericName = "Generic Name", }, } }, }; medStatementDelegateMock.Setup(p => p.GetMedicationStatementsAsync(It.IsAny <ODRHistoryQuery>(), null, It.IsAny <string>(), ipAddress)).ReturnsAsync(requestResult); IMedicationStatementService service = new RestMedicationStatementService( new Mock <ILogger <RestMedicationStatementService> >().Object, httpContextAccessorMock.Object, patientDelegateMock.Object, drugLookupDelegateMock.Object, medStatementDelegateMock.Object); // Act RequestResult <IList <MedicationStatementHistory> > actual = Task.Run(async() => await service.GetMedicationStatementsHistory(hdid, null).ConfigureAwait(true)).Result; // Verify Assert.True(actual.ResultStatus == Common.Constants.ResultType.Success && actual.ResourcePayload.Count == 1); }
public async Task InvalidProtectiveWord() { // Setup string hdid = "EXTRIOYFPNX35TWEBUAJ3DNFDFXSYTBC6J4M76GYE3HC5ER2NKWQ"; string phn = "0009735353315"; string userId = "1001"; string ipAddress = "10.0.0.1"; Mock <IIdentity> identityMock = new Mock <IIdentity>(); identityMock.Setup(s => s.Name).Returns(userId); Mock <ClaimsPrincipal> claimsPrincipalMock = new Mock <ClaimsPrincipal>(); claimsPrincipalMock.Setup(s => s.Identity).Returns(identityMock.Object); Mock <ConnectionInfo> connectionInfoMock = new Mock <ConnectionInfo>(); connectionInfoMock.Setup(s => s.RemoteIpAddress).Returns(IPAddress.Parse(ipAddress)); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary.Add("Authorization", "Bearer TestJWT"); Mock <HttpRequest> httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(s => s.Headers).Returns(headerDictionary); Mock <HttpContext> httpContextMock = new Mock <HttpContext>(); httpContextMock.Setup(s => s.Connection).Returns(connectionInfoMock.Object); httpContextMock.Setup(s => s.User).Returns(claimsPrincipalMock.Object); httpContextMock.Setup(s => s.Request).Returns(httpRequestMock.Object); Mock <IHttpContextAccessor> httpContextAccessorMock = new Mock <IHttpContextAccessor>(); httpContextAccessorMock.Setup(s => s.HttpContext).Returns(httpContextMock.Object); Mock <IPatientService> patientDelegateMock = new Mock <IPatientService>(); patientDelegateMock.Setup(s => s.GetPatientPHN(hdid)).Returns(Task.FromResult( new RequestResult <string>() { ResourcePayload = phn, ResultStatus = Common.Constants.ResultType.Success, })); Mock <IDrugLookupDelegate> drugLookupDelegateMock = new Mock <IDrugLookupDelegate>(); drugLookupDelegateMock.Setup(p => p.GetDrugProductsByDIN(It.IsAny <List <string> >())).Returns(new List <DrugProduct>()); Mock <IMedStatementDelegate> medStatementDelegateMock = new Mock <IMedStatementDelegate>(); RequestResult <MedicationHistoryResponse> requestResult = new RequestResult <MedicationHistoryResponse>(); requestResult.ResourcePayload = new MedicationHistoryResponse(); medStatementDelegateMock.Setup(p => p.GetMedicationStatementsAsync(It.IsAny <ODRHistoryQuery>(), null, It.IsAny <string>(), ipAddress)).ReturnsAsync(requestResult); IMedicationStatementService service = new RestMedicationStatementService( new Mock <ILogger <RestMedicationStatementService> >().Object, httpContextAccessorMock.Object, patientDelegateMock.Object, drugLookupDelegateMock.Object, medStatementDelegateMock.Object); // Run and Verify protective word too long RequestResult <IList <MedicationStatementHistory> > actual = await service.GetMedicationStatementsHistory(hdid, "TOOLONG4U"); Assert.Equal(ResultType.ActionRequired, actual.ResultStatus); Assert.Equal(ActionType.Protected, actual.ResultError.ActionCode); Assert.Equal(ErrorMessages.ProtectiveWordTooLong, actual.ResultError.ResultMessage); // Run and Verify invalid char actual = await service.GetMedicationStatementsHistory(hdid, "SHORT"); Assert.Equal(ResultType.ActionRequired, actual.ResultStatus); Assert.Equal(ActionType.Protected, actual.ResultError.ActionCode); Assert.Equal(ErrorMessages.ProtectiveWordTooShort, actual.ResultError.ResultMessage); // Run and Verify invalid char actual = await service.GetMedicationStatementsHistory(hdid, "SHORT|"); Assert.Equal(ResultType.ActionRequired, actual.ResultStatus); Assert.Equal(ActionType.Protected, actual.ResultError.ActionCode); Assert.Equal(ErrorMessages.ProtectiveWordInvalidChars, actual.ResultError.ResultMessage); // Run and Verify invalid char actual = await service.GetMedicationStatementsHistory(hdid, "SHORT~"); Assert.Equal(ResultType.ActionRequired, actual.ResultStatus); Assert.Equal(ActionType.Protected, actual.ResultError.ActionCode); Assert.Equal(ErrorMessages.ProtectiveWordInvalidChars, actual.ResultError.ResultMessage); // Run and Verify invalid char actual = await service.GetMedicationStatementsHistory(hdid, "SHORT^"); Assert.Equal(ResultType.ActionRequired, actual.ResultStatus); Assert.Equal(ActionType.Protected, actual.ResultError.ActionCode); Assert.Equal(ErrorMessages.ProtectiveWordInvalidChars, actual.ResultError.ResultMessage); // Run and Verify invalid char actual = await service.GetMedicationStatementsHistory(hdid, "SHORT\\"); Assert.Equal(ResultType.ActionRequired, actual.ResultStatus); Assert.Equal(ActionType.Protected, actual.ResultError.ActionCode); Assert.Equal(ErrorMessages.ProtectiveWordInvalidChars, actual.ResultError.ResultMessage); // Run and Verify invalid char actual = await service.GetMedicationStatementsHistory(hdid, "SHORT&"); Assert.Equal(ResultType.ActionRequired, actual.ResultStatus); Assert.Equal(ActionType.Protected, actual.ResultError.ActionCode); Assert.Equal(ErrorMessages.ProtectiveWordInvalidChars, actual.ResultError.ResultMessage); // Run and Verify invalid char actual = await service.GetMedicationStatementsHistory(hdid, " "); Assert.Equal(ResultType.ActionRequired, actual.ResultStatus); Assert.Equal(ActionType.Protected, actual.ResultError.ActionCode); Assert.Equal(ErrorMessages.ProtectiveWordInvalidChars, actual.ResultError.ResultMessage); }
public async Task SendAsync_WritesExpectedTraces() { Assert.Equal(TestHostName, _hostNameProvider.Value); string requestId = Guid.NewGuid().ToString(); var context = new DefaultHttpContext(); Uri uri = new Uri("http://functions.com/api/testfunc?code=123"); var requestFeature = context.Request.HttpContext.Features.Get <IHttpRequestFeature>(); requestFeature.Method = "GET"; requestFeature.Scheme = uri.Scheme; requestFeature.Path = uri.GetComponents(UriComponents.KeepDelimiter | UriComponents.Path, UriFormat.Unescaped); requestFeature.PathBase = string.Empty; requestFeature.QueryString = uri.GetComponents(UriComponents.KeepDelimiter | UriComponents.Query, UriFormat.Unescaped); var headers = new HeaderDictionary(); headers.Add(ScriptConstants.AntaresLogIdHeaderName, new StringValues(requestId)); headers.Add(ScriptConstants.AntaresDefaultHostNameHeader, "test2.azurewebsites.net"); requestFeature.Headers = headers; var claims = new List <Claim> { new Claim(SecurityConstants.AuthLevelClaimType, AuthorizationLevel.Function.ToString()) }; var identity = new ClaimsIdentity(claims, AuthLevelAuthenticationDefaults.AuthenticationScheme); context.User = new ClaimsPrincipal(identity); await _middleware.Invoke(context); var logs = _loggerProvider.GetAllLogMessages().ToArray(); Assert.Equal(3, logs.Length); // validate hostname sync trace var log = logs[0]; Assert.Equal("Microsoft.Azure.WebJobs.Script.WebHost.HostNameProvider", log.Category); Assert.Equal(LogLevel.Information, log.Level); Assert.Equal("HostName updated from 'test.azurewebsites.net' to 'test2.azurewebsites.net'", log.FormattedMessage); // validate executing trace log = logs[1]; Assert.Equal(typeof(SystemTraceMiddleware).FullName, log.Category); Assert.Equal(LogLevel.Information, log.Level); var idx = log.FormattedMessage.IndexOf(':'); var message = log.FormattedMessage.Substring(0, idx).Trim(); Assert.Equal("Executing HTTP request", message); var details = log.FormattedMessage.Substring(idx + 1).Trim(); var jo = JObject.Parse(details); Assert.Equal(3, jo.Count); Assert.Equal(requestId, jo["requestId"]); Assert.Equal("GET", jo["method"]); Assert.Equal("/api/testfunc", jo["uri"]); // validate executed trace log = logs[2]; Assert.Equal(typeof(SystemTraceMiddleware).FullName, log.Category); Assert.Equal(LogLevel.Information, log.Level); idx = log.FormattedMessage.IndexOf(':'); message = log.FormattedMessage.Substring(0, idx).Trim(); Assert.Equal("Executed HTTP request", message); details = log.FormattedMessage.Substring(idx + 1).Trim(); jo = JObject.Parse(details); Assert.Equal(6, jo.Count); Assert.Equal(requestId, jo["requestId"]); Assert.Equal("GET", jo["method"]); Assert.Equal("/api/testfunc", jo["uri"]); Assert.Equal(200, jo["status"]); var duration = (long)jo["duration"]; Assert.True(duration > 0); var authentication = (JArray)jo["identities"]; Assert.Equal(1, authentication.Count); var keyIdentity = authentication.Single(); Assert.Equal(AuthLevelAuthenticationDefaults.AuthenticationScheme, keyIdentity["type"]); Assert.Equal("Function", keyIdentity["level"]); // verify the hostname was synchronized Assert.Equal("test2.azurewebsites.net", _hostNameProvider.Value); }
public async Task ValidProtectiveWord() { // Setup string hdid = "EXTRIOYFPNX35TWEBUAJ3DNFDFXSYTBC6J4M76GYE3HC5ER2NKWQ"; string protectiveWord = "TestWord"; string phn = "0009735353315"; string userId = "1001"; string ipAddress = "10.0.0.1"; Mock <IIdentity> identityMock = new Mock <IIdentity>(); identityMock.Setup(s => s.Name).Returns(userId); Mock <ClaimsPrincipal> claimsPrincipalMock = new Mock <ClaimsPrincipal>(); claimsPrincipalMock.Setup(s => s.Identity).Returns(identityMock.Object); Mock <ConnectionInfo> connectionInfoMock = new Mock <ConnectionInfo>(); connectionInfoMock.Setup(s => s.RemoteIpAddress).Returns(IPAddress.Parse(ipAddress)); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary.Add("Authorization", "Bearer TestJWT"); Mock <HttpRequest> httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(s => s.Headers).Returns(headerDictionary); Mock <HttpContext> httpContextMock = new Mock <HttpContext>(); httpContextMock.Setup(s => s.Connection).Returns(connectionInfoMock.Object); httpContextMock.Setup(s => s.User).Returns(claimsPrincipalMock.Object); httpContextMock.Setup(s => s.Request).Returns(httpRequestMock.Object); Mock <IHttpContextAccessor> httpContextAccessorMock = new Mock <IHttpContextAccessor>(); httpContextAccessorMock.Setup(s => s.HttpContext).Returns(httpContextMock.Object); Mock <IPatientService> patientDelegateMock = new Mock <IPatientService>(); patientDelegateMock.Setup(s => s.GetPatient(hdid, Common.Constants.PatientIdentifierType.HDID)).Returns(Task.FromResult( new RequestResult <PatientModel>() { ResourcePayload = new PatientModel() { Birthdate = DateTime.Parse("2000/01/31"), FirstName = "Patient", LastName = "Zero", EmailAddress = "*****@*****.**", HdId = hdid, PersonalHealthNumber = phn, }, ResultStatus = Common.Constants.ResultType.Success, })); Mock <IDrugLookupDelegate> drugLookupDelegateMock = new Mock <IDrugLookupDelegate>(); drugLookupDelegateMock.Setup(p => p.GetDrugProductsByDIN(It.IsAny <List <string> >())).Returns(new List <DrugProduct>()); Mock <IMedStatementDelegate> medStatementDelegateMock = new Mock <IMedStatementDelegate>(); RequestResult <MedicationHistoryResponse> requestResult = new RequestResult <MedicationHistoryResponse>() { ResultStatus = Common.Constants.ResultType.Success, }; requestResult.ResourcePayload = new MedicationHistoryResponse(); medStatementDelegateMock.Setup(p => p.GetMedicationStatementsAsync(It.IsAny <ODRHistoryQuery>(), It.IsAny <string>(), It.IsAny <string>(), ipAddress)).ReturnsAsync(requestResult); IMedicationStatementService service = new RestMedicationStatementService( new Mock <ILogger <RestMedicationStatementService> >().Object, httpContextAccessorMock.Object, patientDelegateMock.Object, drugLookupDelegateMock.Object, medStatementDelegateMock.Object); // Run and Verify RequestResult <IList <MedicationStatementHistory> > actual = await service.GetMedicationStatementsHistory(hdid, protectiveWord); Assert.True(actual.ResultStatus == Common.Constants.ResultType.Success); }
public static T GetConvertedObject <T>(this object o) where T : class { if (typeof(T) == typeof(HeaderDictionary) && o is JToken) { try { var entries = JObject.FromObject(o).ToObject <Dictionary <string, object> >(); var result = new HeaderDictionary(); foreach (var entry in entries) { string[] values = JsonConvert.DeserializeObject <string[]>(entry.Value.ToString()); result.Add(new KeyValuePair <string, StringValues>(entry.Key, values)); } return(result as T); } catch { throw new ServiceException(HttpStatusCode.InternalServerError, new ContractExecutionResult(ContractExecutionStatesEnum.InternalProcessingError, $"Missing or Wrong parameters passed to job with expected type {typeof(T)} whilst provided with {o.GetType()}")); } } if (typeof(T) != typeof(string) && o is JToken) { try { return((o as JToken).ToObject <T>()); } catch { throw new ServiceException(HttpStatusCode.InternalServerError, new ContractExecutionResult(ContractExecutionStatesEnum.InternalProcessingError, $"Missing or Wrong parameters passed to job with expected type {typeof(T)} whilst provided with {o.GetType()}")); } } if (typeof(T) != typeof(string) && o is JObject) { try { return((o as JToken).ToObject <T>()); } catch { throw new ServiceException(HttpStatusCode.InternalServerError, new ContractExecutionResult(ContractExecutionStatesEnum.InternalProcessingError, $"Missing or Wrong parameters passed to job with expected type {typeof(T)} whilst provided with {o.GetType()}")); } } if (o is T) { return(o as T); } throw new ServiceException(HttpStatusCode.InternalServerError, new ContractExecutionResult(ContractExecutionStatesEnum.InternalProcessingError, $"Missing or Wrong parameters passed to job with expected type {typeof(T)} whilst provided with {o?.GetType()}")); }
public Task StartAsync <TContext>(IHttpApplication <TContext> application, CancellationToken cancellationToken) { SetHttpHandler(new Action <dynamic, dynamic>(async(req, res) => { var resourceName = GetCurrentResourceName(); var bodyStream = (req.method != "GET" && req.method != "HEAD") ? await GetBodyStream(req) : Stream.Null; var oldSc = SynchronizationContext.Current; SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); var cts = new CancellationTokenSource(); req.setCancelHandler(new Action(() => { cts.Cancel(); })); await Task.Factory.StartNew(async() => { var owinEnvironment = new Dictionary <string, object>(); owinEnvironment["owin.RequestBody"] = bodyStream; var headers = new HeaderDictionary(); foreach (var headerPair in req.headers) { headers.Add(headerPair.Key, new string[] { headerPair.Value.ToString() }); } owinEnvironment["owin.RequestHeaders"] = headers; owinEnvironment["owin.RequestMethod"] = req.method; owinEnvironment["owin.RequestPath"] = req.path.Split('?')[0]; owinEnvironment["owin.RequestPathBase"] = "/" + resourceName; owinEnvironment["owin.RequestProtocol"] = "HTTP/1.0"; owinEnvironment["owin.RequestQueryString"] = (req.path.Contains('?')) ? req.path.Split('?', 2)[1] : ""; owinEnvironment["owin.RequestScheme"] = "http"; var outStream = new HttpOutStream(owinEnvironment, res); owinEnvironment["owin.ResponseBody"] = outStream; var outHeaders = new Dictionary <string, string[]>(); owinEnvironment["owin.ResponseHeaders"] = outHeaders; owinEnvironment["owin.CallCancelled"] = cts.Token; owinEnvironment["owin.Version"] = "1.0"; var ofc = new FxOwinFeatureCollection(owinEnvironment); var context = application.CreateContext(new FeatureCollection(ofc)); try { await application.ProcessRequestAsync(context); await ofc.InvokeOnStarting(); } catch (Exception ex) { Debug.WriteLine($"Exception while handling request. {ex}"); await ofc.InvokeOnCompleted(); application.DisposeContext(context, ex); var errorText = Encoding.UTF8.GetBytes("Error."); owinEnvironment["owin.ResponseStatusCode"] = 500; await outStream.WriteAsync(errorText, 0, errorText.Length); await outStream.EndStream(); return; } application.DisposeContext(context, null); await outStream.EndStream(); await ofc.InvokeOnCompleted(); }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); SynchronizationContext.SetSynchronizationContext(oldSc); })); return(Task.CompletedTask); }
public async Task GetAllocationAndHistoryByAllocationResultId_GivenResultFound_ReturnsContentResult() { //Arrange string allocationResultId = "12345"; IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary.Add("Accept", new StringValues("application/json")); HttpRequest request = Substitute.For <HttpRequest>(); request .Headers .Returns(headerDictionary); PublishedProviderResultWithHistory publishedProviderResult = CreatePublishedProviderResultWithHistory(); foreach (PublishedAllocationLineResultVersion historyItem in publishedProviderResult.History) { historyItem.Major = 1; historyItem.Minor = 0; } IPublishedResultsService resultsService = CreateResultsService(); resultsService .GetPublishedProviderResultWithHistoryByAllocationResultId(Arg.Is(allocationResultId)) .Returns(publishedProviderResult); AllocationsService service = CreateService(resultsService); //Act IActionResult result = await service.GetAllocationAndHistoryByAllocationResultId(allocationResultId, request); //Assert result .Should() .BeOfType <ContentResult>(); ContentResult contentResult = result as ContentResult; AllocationWithHistoryModel allocationModel = JsonConvert.DeserializeObject <AllocationWithHistoryModel>(contentResult.Content); string id = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{publishedProviderResult.PublishedProviderResult.SpecificationId}{publishedProviderResult.PublishedProviderResult.ProviderId}{publishedProviderResult.PublishedProviderResult.FundingStreamResult.AllocationLineResult.AllocationLine.Id}")); allocationModel .Should() .NotBeNull(); allocationModel.AllocationResultId.Should().Be(id); allocationModel.AllocationVersionNumber.Should().Be(1); allocationModel.AllocationStatus.Should().Be("Published"); allocationModel.AllocationAmount.Should().Be(50); allocationModel.FundingStream.Id.Should().Be("fs-1"); allocationModel.FundingStream.Name.Should().Be("funding stream 1"); allocationModel.Period.Id.Should().Be("Ay12345"); allocationModel.Provider.UkPrn.Should().Be("1111"); allocationModel.Provider.Upin.Should().Be("2222"); allocationModel.Provider.OpenDate.Should().NotBeNull(); allocationModel.AllocationLine.Id.Should().Be("AAAAA"); allocationModel.AllocationLine.Name.Should().Be("test allocation line 1"); allocationModel.ProfilePeriods.Length.Should().Be(1); allocationModel.History.Length.Should().Be(2); allocationModel.History[0].AllocationVersionNumber.Should().Be(2); allocationModel.History[0].AllocationAmount.Should().Be(40); allocationModel.History[0].Status.Should().Be("Approved"); allocationModel.History[0].AllocationVersion.Should().Be(1.0M); allocationModel.History[1].AllocationVersionNumber.Should().Be(1); allocationModel.History[1].AllocationAmount.Should().Be(50); allocationModel.History[1].Status.Should().Be("Held"); allocationModel.History[1].AllocationVersion.Should().Be(1.0M); }
async public Task SaveDefinition_GivenUpdatedYamlWithChangedIdentifierTypeFieldButAlreadyUsedInRelationship_ReturnsBadRequest() { //Arrange IEnumerable <string> specificationIds = new[] { "spec-1" }; string definitionId = "9183"; string yaml = CreateRawDefinition(); byte[] byteArray = Encoding.UTF8.GetBytes(yaml); MemoryStream stream = new MemoryStream(byteArray); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary .Add("yaml-file", new StringValues(yamlFile)); HttpRequest request = Substitute.For <HttpRequest>(); request .Headers .Returns(headerDictionary); request .Body .Returns(stream); ILogger logger = CreateLogger(); IDatasetRepository datasetRepository = CreateDataSetsRepository(); datasetRepository .GetDistinctRelationshipSpecificationIdsForDatasetDefinitionId(Arg.Is(definitionId)) .Returns(specificationIds); datasetRepository .GetDatasetDefinition(Arg.Is(definitionId)) .Returns(new DatasetDefinition()); DatasetDefinitionChanges datasetDefinitionChanges = new DatasetDefinitionChanges { Id = definitionId, }; FieldDefinitionChanges fieldDefinitionChanges = new FieldDefinitionChanges(); fieldDefinitionChanges.ChangeTypes.Add(FieldDefinitionChangeType.IdentifierType); TableDefinitionChanges tableDefinitionChanges = new TableDefinitionChanges(); tableDefinitionChanges.FieldChanges.Add(fieldDefinitionChanges); datasetDefinitionChanges.TableDefinitionChanges.Add(tableDefinitionChanges); IDefinitionChangesDetectionService definitionChangesDetectionService = CreateChangesDetectionService(); definitionChangesDetectionService .DetectChanges(Arg.Any <DatasetDefinition>(), Arg.Any <DatasetDefinition>()) .Returns(datasetDefinitionChanges); DefinitionsService service = CreateDefinitionsService(logger, definitionChangesDetectionService: definitionChangesDetectionService, datasetsRepository: datasetRepository); //Act IActionResult result = await service.SaveDefinition(request); //Assert result .Should() .BeOfType <BadRequestObjectResult>() .Which .Value .Should() .Be("Unable to change provider identifier as there are currently relationships setup against this schema"); }
public async Task ShouldGetPatientError() { // Setup string hdid = "EXTRIOYFPNX35TWEBUAJ3DNFDFXSYTBC6J4M76GYE3HC5ER2NKWQ"; string userId = "1001"; string ipAddress = "10.0.0.1"; Mock <IIdentity> identityMock = new Mock <IIdentity>(); identityMock.Setup(s => s.Name).Returns(userId); Mock <ClaimsPrincipal> claimsPrincipalMock = new Mock <ClaimsPrincipal>(); claimsPrincipalMock.Setup(s => s.Identity).Returns(identityMock.Object); Mock <ConnectionInfo> connectionInfoMock = new Mock <ConnectionInfo>(); connectionInfoMock.Setup(s => s.RemoteIpAddress).Returns(IPAddress.Parse(ipAddress)); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary.Add("Authorization", "Bearer TestJWT"); Mock <HttpRequest> httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(s => s.Headers).Returns(headerDictionary); Mock <HttpContext> httpContextMock = new Mock <HttpContext>(); httpContextMock.Setup(s => s.Connection).Returns(connectionInfoMock.Object); httpContextMock.Setup(s => s.User).Returns(claimsPrincipalMock.Object); httpContextMock.Setup(s => s.Request).Returns(httpRequestMock.Object); Mock <IHttpContextAccessor> httpContextAccessorMock = new Mock <IHttpContextAccessor>(); httpContextAccessorMock.Setup(s => s.HttpContext).Returns(httpContextMock.Object); Mock <IPatientService> patientDelegateMock = new Mock <IPatientService>(); patientDelegateMock.Setup(s => s.GetPatient(hdid, Common.Constants.PatientIdentifierType.HDID)).Returns(Task.FromResult( new RequestResult <PatientModel>() { ResultStatus = Common.Constants.ResultType.Error, })); Mock <IDrugLookupDelegate> drugLookupDelegateMock = new Mock <IDrugLookupDelegate>(); drugLookupDelegateMock.Setup(p => p.GetDrugProductsByDIN(It.IsAny <List <string> >())).Returns(new List <DrugProduct>()); Mock <IMedStatementDelegate> medStatementDelegateMock = new Mock <IMedStatementDelegate>(); RequestResult <MedicationHistoryResponse> requestResult = new RequestResult <MedicationHistoryResponse>() { ResultStatus = Common.Constants.ResultType.Success, ResourcePayload = new MedicationHistoryResponse() { TotalRecords = 0, }, }; requestResult.ResourcePayload = new MedicationHistoryResponse(); medStatementDelegateMock.Setup(p => p.GetMedicationStatementsAsync(It.IsAny <ODRHistoryQuery>(), null, It.IsAny <string>(), ipAddress)).ReturnsAsync(requestResult); IMedicationStatementService service = new RestMedicationStatementService( new Mock <ILogger <RestMedicationStatementService> >().Object, httpContextAccessorMock.Object, patientDelegateMock.Object, drugLookupDelegateMock.Object, medStatementDelegateMock.Object); // Act RequestResult <IList <MedicationStatementHistory> > actual = await service.GetMedicationStatementsHistory(hdid, null).ConfigureAwait(true); // Verify Assert.True(actual.ResultStatus == Common.Constants.ResultType.Error); }
async public Task SaveDefinition_GivenValidYamlButFailedToSaveToDatabase_ReturnsStatusCode() { //Arrange string yaml = CreateRawDefinition(); byte[] byteArray = Encoding.UTF8.GetBytes(yaml); MemoryStream stream = new MemoryStream(byteArray); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary .Add("yaml-file", new StringValues(yamlFile)); HttpRequest request = Substitute.For <HttpRequest>(); request .Headers .Returns(headerDictionary); request .Body .Returns(stream); ILogger logger = CreateLogger(); HttpStatusCode failedCode = HttpStatusCode.BadGateway; IDatasetRepository dataSetsRepository = CreateDataSetsRepository(); dataSetsRepository .SaveDefinition(Arg.Any <DatasetDefinition>()) .Returns(failedCode); DatasetDefinitionChanges datasetDefinitionChanges = new DatasetDefinitionChanges(); IDefinitionChangesDetectionService definitionChangesDetectionService = CreateChangesDetectionService(); definitionChangesDetectionService .DetectChanges(Arg.Any <DatasetDefinition>(), Arg.Any <DatasetDefinition>()) .Returns(datasetDefinitionChanges); DefinitionsService service = CreateDefinitionsService(logger, dataSetsRepository, definitionChangesDetectionService: definitionChangesDetectionService); //Act IActionResult result = await service.SaveDefinition(request); //Assert result .Should() .BeOfType <StatusCodeResult>(); StatusCodeResult statusCodeResult = (StatusCodeResult)result; statusCodeResult .StatusCode .Should() .Be(502); logger .Received(1) .Error(Arg.Is($"Failed to save yaml file: {yamlFile} to cosmos db with status 502")); }
private static HttpContext PrepareHttpContext( WebPubSubEventType type = WebPubSubEventType.System, string eventName = "connect", string uriStr = TestEndpoint, string connectionId = "0f9c97a2f0bf4706afe87a14e0797b11", string signatures = "sha256=7767effcb3946f3e1de039df4b986ef02c110b1469d02c0a06f41b3b727ab561", string hub = "testhub", string httpMethod = "POST", string userId = "testuser", string body = null, string contentType = Constants.ContentTypes.PlainTextContentType, Dictionary <string, BinaryData> connectionState = null) { var context = new DefaultHttpContext(); var services = new ServiceCollection(); var sp = services.BuildServiceProvider(); context.RequestServices = sp; var uri = new Uri(uriStr); var request = context.Request; var requestFeature = request.HttpContext.Features.Get <IHttpRequestFeature>(); requestFeature.Method = httpMethod; requestFeature.Scheme = uri.Scheme; requestFeature.PathBase = uri.Host; requestFeature.Path = uri.GetComponents(UriComponents.KeepDelimiter | UriComponents.Path, UriFormat.Unescaped); requestFeature.PathBase = "/"; requestFeature.QueryString = uri.GetComponents(UriComponents.KeepDelimiter | UriComponents.Query, UriFormat.Unescaped); var headers = new HeaderDictionary { { Constants.Headers.CloudEvents.Hub, hub }, { Constants.Headers.CloudEvents.Type, GetFormedType(type, eventName) }, { Constants.Headers.CloudEvents.EventName, eventName }, { Constants.Headers.CloudEvents.ConnectionId, connectionId }, { Constants.Headers.CloudEvents.Signature, signatures }, { Constants.Headers.CloudEvents.WebPubSubVersion, "1.0" }, }; if (!string.IsNullOrEmpty(uri.Host)) { headers.Add("Host", uri.Host); headers.Add(Constants.Headers.WebHookRequestOrigin, uri.Host); } if (userId != null) { headers.Add(Constants.Headers.CloudEvents.UserId, userId); } if (connectionState != null) { headers.Add(Constants.Headers.CloudEvents.State, connectionState.EncodeConnectionStates()); } if (body != null) { requestFeature.Body = new MemoryStream(Encoding.UTF8.GetBytes(body)); request.ContentLength = request.Body.Length; headers.Add("Content-Length", request.Body.Length.ToString()); request.ContentType = contentType; headers.Add("Content-Type", contentType); } requestFeature.Headers = headers; context.Response.Body = new MemoryStream(); return(context); }
async public Task SaveDefinition_GivenValidYamlButFailsToUploadToBlobStorage_ReturnsInvalidServerError() { //Arrange string yaml = CreateRawDefinition(); string definitionId = "9183"; byte[] byteArray = Encoding.UTF8.GetBytes(yaml); MemoryStream stream = new MemoryStream(byteArray); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary .Add("yaml-file", new StringValues(yamlFile)); HttpRequest request = Substitute.For <HttpRequest>(); request .Headers .Returns(headerDictionary); request .Body .Returns(stream); ILogger logger = CreateLogger(); HttpStatusCode statusCode = HttpStatusCode.Created; IDatasetRepository datasetsRepository = CreateDataSetsRepository(); datasetsRepository .SaveDefinition(Arg.Any <DatasetDefinition>()) .Returns(statusCode); ISearchRepository <DatasetDefinitionIndex> searchRepository = CreateDatasetDefinitionSearchRepository(); searchRepository .SearchById(Arg.Is(definitionId)) .Returns((DatasetDefinitionIndex)null); byte[] excelAsBytes = new byte[100]; IExcelWriter <DatasetDefinition> excelWriter = CreateExcelWriter(); excelWriter .Write(Arg.Any <DatasetDefinition>()) .Returns(excelAsBytes); ICloudBlob blob = Substitute.For <ICloudBlob>(); blob .When(x => x.UploadFromStreamAsync(Arg.Any <Stream>())) .Do(x => { throw new Exception($"Failed to upload 14/15 blob storage"); }); IBlobClient blobClient = CreateBlobClient(); blobClient .GetBlockBlobReference(Arg.Is("schemas/14_15.xlsx")) .Returns(blob); DatasetDefinitionChanges datasetDefinitionChanges = new DatasetDefinitionChanges(); IDefinitionChangesDetectionService definitionChangesDetectionService = CreateChangesDetectionService(); definitionChangesDetectionService .DetectChanges(Arg.Any <DatasetDefinition>(), Arg.Any <DatasetDefinition>()) .Returns(datasetDefinitionChanges); DefinitionsService service = CreateDefinitionsService(logger, datasetsRepository, searchRepository, excelWriter: excelWriter, blobClient: blobClient, definitionChangesDetectionService: definitionChangesDetectionService); //Act IActionResult result = await service.SaveDefinition(request); //Assert result .Should() .BeOfType <InternalServerErrorResult>() .Which .Value .Should() .Be($"Failed to upload 14/15 blob storage"); }
public async Task SendAsync_WritesExpectedTraces() { string requestId = Guid.NewGuid().ToString(); var context = new DefaultHttpContext(); Uri uri = new Uri("http://functions.com/api/testfunc?code=123"); var requestFeature = context.Request.HttpContext.Features.Get <IHttpRequestFeature>(); requestFeature.Method = "GET"; requestFeature.Scheme = uri.Scheme; requestFeature.Path = uri.GetComponents(UriComponents.KeepDelimiter | UriComponents.Path, UriFormat.Unescaped); requestFeature.PathBase = string.Empty; requestFeature.QueryString = uri.GetComponents(UriComponents.KeepDelimiter | UriComponents.Query, UriFormat.Unescaped); var headers = new HeaderDictionary(); headers.Add(ScriptConstants.AntaresLogIdHeaderName, new StringValues(requestId)); headers.Add("User-Agent", new StringValues("TestAgent")); requestFeature.Headers = headers; var principal = new ClaimsPrincipal(); principal.AddIdentity(new ClaimsIdentity(new List <Claim> { new Claim(SecurityConstants.AuthLevelClaimType, AuthorizationLevel.Function.ToString()) }, AuthLevelAuthenticationDefaults.AuthenticationScheme)); principal.AddIdentity(new ClaimsIdentity(new List <Claim> { new Claim(SecurityConstants.AuthLevelClaimType, "CustomLevel") }, "CustomScheme")); context.User = principal; await _middleware.Invoke(context); var logs = _loggerProvider.GetAllLogMessages().ToArray(); Assert.Equal(2, logs.Length); // validate executing trace var log = logs[0]; Assert.Equal(typeof(SystemTraceMiddleware).FullName, log.Category); Assert.Equal(LogLevel.Information, log.Level); var idx = log.FormattedMessage.IndexOf(':'); var message = log.FormattedMessage.Substring(0, idx).Trim(); Assert.Equal("Executing HTTP request", message); var details = log.FormattedMessage.Substring(idx + 1).Trim(); var jo = JObject.Parse(details); Assert.Equal(4, jo.Count); Assert.Equal(requestId, jo["requestId"]); Assert.Equal("GET", jo["method"]); Assert.Equal("/api/testfunc", jo["uri"]); Assert.Equal("TestAgent", jo["userAgent"]); // validate executed trace log = logs[1]; Assert.Equal(typeof(SystemTraceMiddleware).FullName, log.Category); Assert.Equal(LogLevel.Information, log.Level); idx = log.FormattedMessage.IndexOf(':'); message = log.FormattedMessage.Substring(0, idx).Trim(); Assert.Equal("Executed HTTP request", message); details = log.FormattedMessage.Substring(idx + 1).Trim(); jo = JObject.Parse(details); Assert.Equal(4, jo.Count); Assert.Equal(requestId, jo["requestId"]); Assert.Equal(200, jo["status"]); var duration = (long)jo["duration"]; Assert.True(duration > 0); string identities = (string)jo["identities"]; Assert.Equal($"({AuthLevelAuthenticationDefaults.AuthenticationScheme}:Function, CustomScheme:CustomLevel)", identities); }
public async Task SaveDefinition_GivenValidYamlAndSearchDoesContainsExistingItemWithNoUpdates_ThenDatasetDefinitionSavedInCosmosAndSearchNotUpdatedAndReturnsOK() { //Arrange string yaml = CreateRawDefinition(); string definitionId = "9183"; byte[] byteArray = Encoding.UTF8.GetBytes(yaml); MemoryStream stream = new MemoryStream(byteArray); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary .Add("yaml-file", new StringValues(yamlFile)); HttpRequest request = Substitute.For <HttpRequest>(); request .Headers .Returns(headerDictionary); request .Body .Returns(stream); ILogger logger = CreateLogger(); HttpStatusCode statusCode = HttpStatusCode.Created; IDatasetRepository datasetsRepository = CreateDataSetsRepository(); datasetsRepository .SaveDefinition(Arg.Any <DatasetDefinition>()) .Returns(statusCode); DatasetDefinitionIndex existingIndex = new DatasetDefinitionIndex() { Description = "14/15 description", Id = "9183", LastUpdatedDate = new DateTimeOffset(2018, 6, 19, 14, 10, 2, TimeSpan.Zero), ModelHash = "DFBD0E1ACD29CEBCF5AD45674688D3780D916294C4DF878074AFD01B67BF129C", Name = "14/15", ProviderIdentifier = "None", }; ISearchRepository <DatasetDefinitionIndex> searchRepository = CreateDatasetDefinitionSearchRepository(); searchRepository .SearchById(Arg.Is(definitionId)) .Returns(existingIndex); byte[] excelAsBytes = new byte[100]; IExcelWriter <DatasetDefinition> excelWriter = CreateExcelWriter(); excelWriter .Write(Arg.Any <DatasetDefinition>()) .Returns(excelAsBytes); ICloudBlob blob = Substitute.For <ICloudBlob>(); IBlobClient blobClient = CreateBlobClient(); blobClient .GetBlockBlobReference(Arg.Any <string>()) .Returns(blob); DatasetDefinitionChanges datasetDefinitionChanges = new DatasetDefinitionChanges(); IDefinitionChangesDetectionService definitionChangesDetectionService = CreateChangesDetectionService(); definitionChangesDetectionService .DetectChanges(Arg.Any <DatasetDefinition>(), Arg.Any <DatasetDefinition>()) .Returns(datasetDefinitionChanges); DefinitionsService service = CreateDefinitionsService(logger, datasetsRepository, searchRepository, excelWriter: excelWriter, blobClient: blobClient, definitionChangesDetectionService: definitionChangesDetectionService); //Act IActionResult result = await service.SaveDefinition(request); //Assert result .Should() .BeOfType <OkResult>(); await searchRepository .Received(1) .SearchById(Arg.Is(definitionId)); await searchRepository .Received(0) .Index(Arg.Any <IEnumerable <DatasetDefinitionIndex> >()); await datasetsRepository .Received(1) .SaveDefinition(Arg.Is <DatasetDefinition>( i => i.Description == "14/15 description" && i.Id == "9183" && i.Name == "14/15" )); logger .Received(1) .Information(Arg.Is($"Successfully saved file: {yamlFile} to cosmos db")); }
public void CreateCalculation_WhenSomethingGoesWrongDuringIndexing_ShouldThrowException() { //Arrange const string errorMessage = "Encountered 802 error code"; AllocationLine allocationLine = new AllocationLine { Id = "02a6eeaf-e1a0-476e-9cf9-8aa5d9129345", Name = "test alloctaion" }; List <FundingStream> fundingStreams = new List <FundingStream>(); FundingStream fundingStream = new FundingStream { AllocationLines = new List <AllocationLine> { allocationLine }, Id = FundingStreamId }; fundingStreams.Add(fundingStream); Policy policy = new Policy { Id = PolicyId, Name = PolicyName, }; Specification specification = CreateSpecification(); specification.Current.Policies = new[] { policy }; specification.Current.FundingStreams = new List <Reference>() { new Reference { Id = FundingStreamId } }; CalculationCreateModel model = new CalculationCreateModel { SpecificationId = SpecificationId, PolicyId = PolicyId, AllocationLineId = AllocationLineId }; string json = JsonConvert.SerializeObject(model); byte[] byteArray = Encoding.UTF8.GetBytes(json); MemoryStream stream = new MemoryStream(byteArray); ClaimsPrincipal principle = new ClaimsPrincipal(new[] { new ClaimsIdentity(new [] { new Claim(ClaimTypes.Sid, UserId), new Claim(ClaimTypes.Name, Username) }) }); HttpContext context = Substitute.For <HttpContext>(); context .User .Returns(principle); HttpRequest request = Substitute.For <HttpRequest>(); request .Body .Returns(stream); request .HttpContext .Returns(context); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary .Add("sfa-correlationId", new StringValues(SfaCorrelationId)); request .Headers .Returns(headerDictionary); ILogger logger = CreateLogger(); ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository(); specificationsRepository .GetSpecificationById(Arg.Is(SpecificationId)) .Returns(specification); specificationsRepository .GetFundingStreams(Arg.Any <Expression <Func <FundingStream, bool> > >()) .Returns(fundingStreams); specificationsRepository .UpdateSpecification(Arg.Is(specification)) .Returns(HttpStatusCode.OK); Calculation calculation = new Calculation { AllocationLine = new Reference() }; IMapper mapper = CreateMapper(); mapper .Map <Calculation>(Arg.Any <CalculationCreateModel>()) .Returns(calculation); IMessengerService messengerService = CreateMessengerService(); ISearchRepository <SpecificationIndex> mockSearchRepository = CreateSearchRepository(); mockSearchRepository .Index(Arg.Any <IEnumerable <SpecificationIndex> >()) .Returns(new List <IndexError>() { new IndexError() { ErrorMessage = errorMessage } }); SpecificationVersion newSpecVersion = specification.Current.Clone() as SpecificationVersion; newSpecVersion.PublishStatus = PublishStatus.Updated; newSpecVersion.Version = 2; IVersionRepository <SpecificationVersion> mockVersionRepository = CreateVersionRepository(); mockVersionRepository .CreateVersion(Arg.Any <SpecificationVersion>(), Arg.Any <SpecificationVersion>()) .Returns(newSpecVersion); SpecificationsService service = CreateService(logs: logger, specificationsRepository: specificationsRepository, mapper: mapper, messengerService: messengerService, specificationVersionRepository: mockVersionRepository, searchRepository: mockSearchRepository); //Act Func <Task <IActionResult> > createCalculation = async() => await service.CreateCalculation(request); //Assert createCalculation .Should() .Throw <ApplicationException>() .Which .Message .Should() .Be($"Could not index specification {specification.Current.Id} because: {errorMessage}"); }
public async Task GetNotifications_GivenSearchFeedReturnsNoResults_ReturnsAtomFeed() { //Arrange SearchFeed <AllocationNotificationFeedIndex> feeds = new SearchFeed <AllocationNotificationFeedIndex> { PageRef = 3, Top = 500, TotalCount = 3, Entries = CreateFeedIndexes() }; IAllocationNotificationsFeedsSearchService feedsSearchService = CreateSearchService(); feedsSearchService .GetFeeds(Arg.Is(3), Arg.Is(2), Arg.Any <IEnumerable <string> >()) .Returns(feeds); AllocationNotificationFeedsService service = CreateService(feedsSearchService); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary.Add("Accept", new StringValues("application/json")); IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues> { { "pageRef", new StringValues("3") }, { "allocationStatuses", new StringValues("Published,Approved") }, { "pageSize", new StringValues("2") } }); HttpRequest request = Substitute.For <HttpRequest>(); request.Scheme.Returns("https"); request.Path.Returns(new PathString("/api/v1/test")); request.Host.Returns(new HostString("wherever.naf:12345")); request.QueryString.Returns(new QueryString("?pageRef=3&pageSize=2&allocationStatuses=Published,Approved")); request.Headers.Returns(headerDictionary); request.Query.Returns(queryStringValues); //Act IActionResult result = await service.GetNotifications(3, "Published,Approved", 2, request); //Assert result .Should() .BeOfType <ContentResult>(); ContentResult contentResult = result as ContentResult; AtomFeed <AllocationModel> atomFeed = JsonConvert.DeserializeObject <AtomFeed <AllocationModel> >(contentResult.Content); atomFeed .Should() .NotBeNull(); atomFeed.Id.Should().NotBeEmpty(); atomFeed.Title.Should().Be("Calculate Funding Service Allocation Feed"); atomFeed.Author.Name.Should().Be("Calculate Funding Service"); atomFeed.Link.First(m => m.Rel == "self").Href.Should().Be("https://wherever.naf:12345/api/v1/notifications?pageRef=3&allocationStatuses=Published,Approved&pageSize=2"); atomFeed.Link.First(m => m.Rel == "first").Href.Should().Be("https://wherever.naf:12345/api/v1/notifications?pageRef=1&allocationStatuses=Published,Approved&pageSize=2"); atomFeed.Link.First(m => m.Rel == "last").Href.Should().Be("https://wherever.naf:12345/api/v1/notifications?pageRef=1&allocationStatuses=Published,Approved&pageSize=2"); atomFeed.Link.First(m => m.Rel == "previous").Href.Should().Be("https://wherever.naf:12345/api/v1/notifications?pageRef=2&allocationStatuses=Published,Approved&pageSize=2"); atomFeed.Link.First(m => m.Rel == "next").Href.Should().Be("https://wherever.naf:12345/api/v1/notifications?pageRef=3&allocationStatuses=Published,Approved&pageSize=2"); atomFeed.AtomEntry.Count.Should().Be(3); atomFeed.AtomEntry.ElementAt(0).Id.Should().Be("id-1"); atomFeed.AtomEntry.ElementAt(0).Title.Should().Be("test title 1"); atomFeed.AtomEntry.ElementAt(0).Summary.Should().Be("test summary 1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.FundingStream.Id.Should().Be("fs-1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.FundingStream.Name.Should().Be("fs 1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Period.Id.Should().Be("fp-1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.UkPrn.Should().Be("1111"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.Upin.Should().Be("0001"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.AllocationLine.Id.Should().Be("al-1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.AllocationLine.Name.Should().Be("al 1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.AllocationVersionNumber.Should().Be(1); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.AllocationStatus.Should().Be("Published"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.AllocationAmount.Should().Be(10); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.ProfilePeriods.Length.Should().Be(0); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.FundingStream.ShortName.Should().Be("fs-short-1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.FundingStream.PeriodType.Id.Should().Be("fspi-1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.FundingStream.PeriodType.Name.Should().Be("fspi1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.FundingStream.PeriodType.StartDay.Should().Be(1); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.FundingStream.PeriodType.StartMonth.Should().Be(8); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.FundingStream.PeriodType.EndDay.Should().Be(31); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.FundingStream.PeriodType.EndMonth.Should().Be(7); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Period.Name.Should().Be("fspi1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Period.StartYear.Should().Be(2018); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Period.EndYear.Should().Be(2019); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.Name.Should().Be("provider 1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.LegalName.Should().Be("legal 1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.Urn.Should().Be("01"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.DfeEstablishmentNumber.Should().Be("dfe-1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.EstablishmentNumber.Should().Be("e-1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.LaCode.Should().Be("la-1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.LocalAuthority.Should().Be("authority"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.Type.Should().Be("type 1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.SubType.Should().Be("sub type 1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.OpenDate.Should().NotBeNull(); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.CloseDate.Should().NotBeNull(); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.CrmAccountId.Should().Be("crm-1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.NavVendorNo.Should().Be("nv-1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.Provider.Status.Should().Be("Active"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.AllocationLine.ShortName.Should().Be("short-al1"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.AllocationLine.FundingRoute.Should().Be("LA"); atomFeed.AtomEntry.ElementAt(0).Content.Allocation.AllocationLine.ContractRequired.Should().Be("Y"); atomFeed.AtomEntry.ElementAt(1).Id.Should().Be("id-2"); atomFeed.AtomEntry.ElementAt(1).Title.Should().Be("test title 2"); atomFeed.AtomEntry.ElementAt(1).Summary.Should().Be("test summary 2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.FundingStream.Id.Should().Be("fs-2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.FundingStream.Name.Should().Be("fs 2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Period.Id.Should().Be("fp-2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.UkPrn.Should().Be("2222"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.Upin.Should().Be("0002"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.AllocationLine.Id.Should().Be("al-2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.AllocationLine.Name.Should().Be("al 2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.AllocationVersionNumber.Should().Be(1); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.AllocationStatus.Should().Be("Published"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.AllocationAmount.Should().Be(100); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.ProfilePeriods.Length.Should().Be(2); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.FundingStream.ShortName.Should().Be("fs-short-2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.FundingStream.PeriodType.Id.Should().Be("fspi-2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.FundingStream.PeriodType.Name.Should().Be("fspi2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.FundingStream.PeriodType.StartDay.Should().Be(1); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.FundingStream.PeriodType.StartMonth.Should().Be(8); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.FundingStream.PeriodType.EndDay.Should().Be(31); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.FundingStream.PeriodType.EndMonth.Should().Be(7); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Period.Name.Should().Be("fspi2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Period.StartYear.Should().Be(2018); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Period.EndYear.Should().Be(2019); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.Name.Should().Be("provider 2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.LegalName.Should().Be("legal 2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.Urn.Should().Be("02"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.DfeEstablishmentNumber.Should().Be("dfe-2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.EstablishmentNumber.Should().Be("e-2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.LaCode.Should().Be("la-2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.LocalAuthority.Should().Be("authority"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.Type.Should().Be("type 2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.SubType.Should().Be("sub type 2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.OpenDate.Should().NotBeNull(); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.CloseDate.Should().NotBeNull(); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.CrmAccountId.Should().Be("crm-2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.NavVendorNo.Should().Be("nv-2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.Provider.Status.Should().Be("Active"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.AllocationLine.ShortName.Should().Be("short-al2"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.AllocationLine.FundingRoute.Should().Be("LA"); atomFeed.AtomEntry.ElementAt(1).Content.Allocation.AllocationLine.ContractRequired.Should().Be("Y"); atomFeed.AtomEntry.ElementAt(2).Id.Should().Be("id-3"); atomFeed.AtomEntry.ElementAt(2).Title.Should().Be("test title 3"); atomFeed.AtomEntry.ElementAt(2).Summary.Should().Be("test summary 3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.FundingStream.Id.Should().Be("fs-3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.FundingStream.Name.Should().Be("fs 3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Period.Id.Should().Be("fp-3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.UkPrn.Should().Be("3333"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.Upin.Should().Be("0003"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.AllocationLine.Id.Should().Be("al-3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.AllocationLine.Name.Should().Be("al 3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.AllocationVersionNumber.Should().Be(1); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.AllocationStatus.Should().Be("Approved"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.AllocationAmount.Should().Be(20); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.ProfilePeriods.Length.Should().Be(0); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.FundingStream.ShortName.Should().Be("fs-short-3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.FundingStream.PeriodType.Id.Should().Be("fspi-3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.FundingStream.PeriodType.StartDay.Should().Be(1); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.FundingStream.PeriodType.StartMonth.Should().Be(8); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.FundingStream.PeriodType.EndDay.Should().Be(31); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.FundingStream.PeriodType.EndMonth.Should().Be(7); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Period.Name.Should().Be("fspi3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Period.StartYear.Should().Be(2018); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Period.EndYear.Should().Be(2019); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.Name.Should().Be("provider 3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.LegalName.Should().Be("legal 3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.Urn.Should().Be("03"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.DfeEstablishmentNumber.Should().Be("dfe-3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.EstablishmentNumber.Should().Be("e-3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.LaCode.Should().Be("la-3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.LocalAuthority.Should().Be("authority"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.Type.Should().Be("type 3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.SubType.Should().Be("sub type 3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.OpenDate.Should().NotBeNull(); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.CloseDate.Should().NotBeNull(); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.CrmAccountId.Should().Be("crm-3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.NavVendorNo.Should().Be("nv-3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.Provider.Status.Should().Be("Active"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.AllocationLine.ShortName.Should().Be("short-al3"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.AllocationLine.FundingRoute.Should().Be("LA"); atomFeed.AtomEntry.ElementAt(2).Content.Allocation.AllocationLine.ContractRequired.Should().Be("Y"); }
public async Task CreateCalculation_GivenValidModelForSubPolicyAndSubPolicyFoundAndUpdated_ReturnsOK() { //Arrange AllocationLine allocationLine = new AllocationLine { Id = "02a6eeaf-e1a0-476e-9cf9-8aa5d9129345", Name = "test alloctaion" }; List <FundingStream> fundingStreams = new List <FundingStream>(); FundingStream fundingStream = new FundingStream { AllocationLines = new List <AllocationLine> { allocationLine }, Id = FundingStreamId }; fundingStreams.Add(fundingStream); Policy policy = new Policy { Id = PolicyId, Name = PolicyName, }; Specification specification = CreateSpecification(); specification.Current.Policies = new[] { policy }; specification.Current.FundingStreams = new List <Reference>() { new Reference { Id = FundingStreamId } }; CalculationCreateModel model = new CalculationCreateModel { SpecificationId = SpecificationId, PolicyId = PolicyId, AllocationLineId = AllocationLineId }; string json = JsonConvert.SerializeObject(model); byte[] byteArray = Encoding.UTF8.GetBytes(json); MemoryStream stream = new MemoryStream(byteArray); ClaimsPrincipal principle = new ClaimsPrincipal(new[] { new ClaimsIdentity(new [] { new Claim(ClaimTypes.Sid, UserId), new Claim(ClaimTypes.Name, Username) }) }); HttpContext context = Substitute.For <HttpContext>(); context .User .Returns(principle); HttpRequest request = Substitute.For <HttpRequest>(); request .Body .Returns(stream); request .HttpContext .Returns(context); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary .Add("sfa-correlationId", new StringValues(SfaCorrelationId)); request .Headers .Returns(headerDictionary); ILogger logger = CreateLogger(); ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository(); specificationsRepository .GetSpecificationById(Arg.Is(SpecificationId)) .Returns(specification); specificationsRepository .GetFundingStreams(Arg.Any <Expression <Func <FundingStream, bool> > >()) .Returns(fundingStreams); specificationsRepository .UpdateSpecification(Arg.Is(specification)) .Returns(HttpStatusCode.OK); Calculation calculation = new Calculation { AllocationLine = new Reference() }; IMapper mapper = CreateMapper(); mapper .Map <Calculation>(Arg.Any <CalculationCreateModel>()) .Returns(calculation); IMessengerService messengerService = CreateMessengerService(); SpecificationVersion newSpecVersion = specification.Current.Clone() as SpecificationVersion; newSpecVersion.PublishStatus = PublishStatus.Updated; newSpecVersion.Version = 2; IVersionRepository <SpecificationVersion> mockVersionRepository = CreateVersionRepository(); mockVersionRepository .CreateVersion(Arg.Any <SpecificationVersion>(), Arg.Any <SpecificationVersion>()) .Returns(newSpecVersion); SpecificationsService service = CreateService(logs: logger, specificationsRepository: specificationsRepository, mapper: mapper, messengerService: messengerService, specificationVersionRepository: mockVersionRepository); //Act IActionResult result = await service.CreateCalculation(request); //Assert result .Should() .BeOfType <OkObjectResult>(); await messengerService .Received(1) .SendToQueue(Arg.Is("calc-events-create-draft"), Arg.Is <Models.Calcs.Calculation>(m => m.CalculationSpecification.Id == calculation.Id && m.CalculationSpecification.Name == calculation.Name && m.Name == calculation.Name && !string.IsNullOrEmpty(m.Id) && m.AllocationLine.Id == allocationLine.Id && m.AllocationLine.Name == allocationLine.Name), Arg.Is <IDictionary <string, string> >(m => m["user-id"] == UserId && m["user-name"] == Username && m["sfa-correlationId"] == SfaCorrelationId)); }
public async Task GetNotifications_GivenSearchFeedReturnsNoResultsWhenNoPageRefIsSpecified_EnsuresAtomLinksCorrect() { //Arrange SearchFeed <AllocationNotificationFeedIndex> feeds = new SearchFeed <AllocationNotificationFeedIndex> { PageRef = 3, Top = 500, TotalCount = 3, Entries = CreateFeedIndexes() }; IAllocationNotificationsFeedsSearchService feedsSearchService = CreateSearchService(); feedsSearchService .GetFeeds(Arg.Is(3), Arg.Is(2), Arg.Any <IEnumerable <string> >()) .Returns(feeds); AllocationNotificationFeedsService service = CreateService(feedsSearchService); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary.Add("Accept", new StringValues("application/json")); IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues> { { "allocationStatuses", new StringValues("Published,Approved") }, { "pageSize", new StringValues("2") } }); HttpRequest request = Substitute.For <HttpRequest>(); request.Scheme.Returns("https"); request.Path.Returns(new PathString("/api/v1/test")); request.Host.Returns(new HostString("wherever.naf:12345")); request.QueryString.Returns(new QueryString("?pageSize=2&allocationStatuses=Published,Approved")); request.Headers.Returns(headerDictionary); request.Query.Returns(queryStringValues); //Act IActionResult result = await service.GetNotifications(3, "Published,Approved", 2, request); //Assert result .Should() .BeOfType <ContentResult>(); ContentResult contentResult = result as ContentResult; AtomFeed <AllocationModel> atomFeed = JsonConvert.DeserializeObject <AtomFeed <AllocationModel> >(contentResult.Content); atomFeed .Should() .NotBeNull(); atomFeed.Id.Should().NotBeEmpty(); atomFeed.Title.Should().Be("Calculate Funding Service Allocation Feed"); atomFeed.Author.Name.Should().Be("Calculate Funding Service"); atomFeed.Link.First(m => m.Rel == "self").Href.Should().Be("https://wherever.naf:12345/api/v1/notifications?allocationStatuses=Published,Approved&pageSize=2&pageRef=3"); atomFeed.Link.First(m => m.Rel == "first").Href.Should().Be("https://wherever.naf:12345/api/v1/notifications?allocationStatuses=Published,Approved&pageSize=2&pageRef=1"); atomFeed.Link.First(m => m.Rel == "last").Href.Should().Be("https://wherever.naf:12345/api/v1/notifications?allocationStatuses=Published,Approved&pageSize=2&pageRef=1"); atomFeed.Link.First(m => m.Rel == "previous").Href.Should().Be("https://wherever.naf:12345/api/v1/notifications?allocationStatuses=Published,Approved&pageSize=2&pageRef=2"); atomFeed.Link.First(m => m.Rel == "next").Href.Should().Be("https://wherever.naf:12345/api/v1/notifications?allocationStatuses=Published,Approved&pageSize=2&pageRef=3"); }
public void Add(KeyValuePair <string, StringValues> item) => _headers.Add(item);
protected override void Arrange() { var configValueProvider = new ApiSettings(); configValueProvider.UseReverseProxyHeaders = true; Feature item = new Feature(); item.IsEnabled = true; item.Name = "openApiMetadata"; configValueProvider.Features.Add(item); _openApiMetadataCacheProvider = Stub <IOpenApiMetadataCacheProvider>(); _openApiMetadataCacheProvider = Stub <IOpenApiMetadataCacheProvider>(); A.CallTo(() => _openApiMetadataCacheProvider.GetOpenApiContentByFeedName(A <string> ._)) .Returns(OpenApiMetadataHelper.GetIdentityContent()); var fakeopenAPIcontent = A.Fake <List <OpenApiContent> >(); A.CallTo(() => _openApiMetadataCacheProvider.GetAllSectionDocuments(A <bool> ._)).Returns(fakeopenAPIcontent); var sectiondata = _openApiMetadataCacheProvider.GetOpenApiContentByFeedName("openApiMetadata"); fakeopenAPIcontent.Add(sectiondata); _controller = new OpenApiMetadataController(_openApiMetadataCacheProvider, configValueProvider); var request = A.Fake <HttpRequest>(); request.Method = "Post"; request.Scheme = "http"; A.CallTo(() => request.Host).Returns(new HostString("localhost", 80)); request.PathBase = "/"; request.RouteValues = new RouteValueDictionary { { "controller", "Token" } }; var headerDictionary = A.Fake <IHeaderDictionary>(); HeaderDictionary dict = new HeaderDictionary(); dict.Add(HeaderConstants.XForwardedProto, "https"); dict.Add(HeaderConstants.XForwardedHost, "api.com"); dict.Add(HeaderConstants.XForwardedPort, "443"); A.CallTo(() => request.Headers).Returns(dict); var httpContext = A.Fake <HttpContext>(); A.CallTo(() => httpContext.Request).Returns(request); var controllerContext = new ControllerContext() { HttpContext = httpContext, }; RouteValueDictionary dictionary = new RouteValueDictionary(); dictionary.Add("controller", "Token"); controllerContext.RouteData = new RouteData(dictionary); _controller.ControllerContext = controllerContext; }
public void ShouldNotAuthExpiredDelegate() { string hdid = "The User HDID"; string resourceHDID = "The Resource HDID"; string token = "Fake Access Token"; string userId = "User ID"; string username = "******"; string scopes = "user/Observation.read"; List <Claim> claims = new List <Claim>() { new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.NameIdentifier, userId), new Claim(GatewayClaims.HDID, hdid), new Claim(GatewayClaims.Scope, scopes), }; ClaimsIdentity identity = new ClaimsIdentity(claims, "TestAuth"); ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity); PatientModel patientModel = new PatientModel() { Birthdate = DateTime.Now .AddYears(MaxDependentAge * -1) }; RequestResult <PatientModel> getPatientResult = new RequestResult <PatientModel>(patientModel, ResultType.Success); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary.Add("Authorization", token); RouteValueDictionary routeValues = new RouteValueDictionary(); routeValues.Add("hdid", resourceHDID); Mock <HttpRequest> httpRequestMock = new Mock <HttpRequest>(); httpRequestMock.Setup(s => s.Headers).Returns(headerDictionary); httpRequestMock.Setup(s => s.RouteValues).Returns(routeValues); Mock <HttpContext> httpContextMock = new Mock <HttpContext>(); httpContextMock.Setup(s => s.User).Returns(claimsPrincipal); httpContextMock.Setup(s => s.Request).Returns(httpRequestMock.Object); Mock <IHttpContextAccessor> httpContextAccessorMock = new Mock <IHttpContextAccessor>(); httpContextAccessorMock.Setup(s => s.HttpContext).Returns(httpContextMock.Object); using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); ILogger <FhirResourceDelegateAuthorizationHandler> logger = loggerFactory.CreateLogger <FhirResourceDelegateAuthorizationHandler>(); Mock <IResourceDelegateDelegate> mockDependentDelegate = new Mock <IResourceDelegateDelegate>(); mockDependentDelegate.Setup(s => s.Exists(resourceHDID, hdid)).Returns(true); Mock <IPatientService> mockPatientService = new Mock <IPatientService>(); mockPatientService .Setup(s => s.GetPatient(resourceHDID, PatientIdentifierType.HDID)) .ReturnsAsync(getPatientResult); FhirResourceDelegateAuthorizationHandler authHandler = new FhirResourceDelegateAuthorizationHandler( logger, this.GetConfiguration(), httpContextAccessorMock.Object, mockPatientService.Object, mockDependentDelegate.Object ); var requirements = new[] { new FhirRequirement(FhirResource.Observation, FhirAccessType.Read, supportsUserDelegation: true) }; AuthorizationHandlerContext context = new AuthorizationHandlerContext(requirements, claimsPrincipal, null); authHandler.HandleAsync(context); Assert.False(context.HasSucceeded); Assert.False(context.HasFailed); }
public FilterContextBuilder WithHeader(string key, string value) { headerDictionary.Add(key, value); return(this); }
public void GetAllocationByAllocationResultId_GivenResultHasVariation_ReturnsContentResult() { //Arrange string allocationResultId = "12345"; IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary.Add("Accept", new StringValues("application/json")); HttpRequest request = Substitute.For <HttpRequest>(); request .Headers .Returns(headerDictionary); PublishedProviderResult publishedProviderResult = CreatePublishedProviderResult(); publishedProviderResult.FundingStreamResult.AllocationLineResult.Current.FeedIndexId = allocationResultId; publishedProviderResult.FundingStreamResult.AllocationLineResult.HasResultBeenVaried = true; publishedProviderResult.FundingStreamResult.AllocationLineResult.Current.VariationReasons = new[] { VariationReason.LegalNameFieldUpdated, VariationReason.LACodeFieldUpdated }; publishedProviderResult.FundingStreamResult.AllocationLineResult.Current.Provider.Successor = "provider3"; publishedProviderResult.FundingStreamResult.AllocationLineResult.Current.Predecessors = new[] { "provider1", "provider2" }; publishedProviderResult.FundingStreamResult.AllocationLineResult.Current.Provider.ReasonEstablishmentOpened = "Fresh Start"; publishedProviderResult.FundingStreamResult.AllocationLineResult.Current.Provider.ReasonEstablishmentClosed = "Closure"; IPublishedResultsService resultsService = CreateResultsService(); resultsService .GetPublishedProviderResultByVersionId(Arg.Is(allocationResultId)) .Returns(publishedProviderResult); AllocationsService service = CreateService(resultsService); //Act IActionResult result = service.GetAllocationByAllocationResultId(allocationResultId, request); //Assert result .Should() .BeOfType <ContentResult>(); ContentResult contentResult = result as ContentResult; AllocationModel allocationModel = JsonConvert.DeserializeObject <AllocationModel>(contentResult.Content); allocationModel .Should() .NotBeNull(); allocationModel.AllocationResultId.Should().Be(allocationResultId); allocationModel.AllocationStatus.Should().Be("Published"); allocationModel.AllocationAmount.Should().Be(50); allocationModel.FundingStream.Id.Should().Be("fs-1"); allocationModel.FundingStream.Name.Should().Be("funding stream 1"); allocationModel.Period.Id.Should().Be("Ay12345"); allocationModel.Provider.UkPrn.Should().Be("1111"); allocationModel.Provider.Upin.Should().Be("2222"); allocationModel.Provider.OpenDate.Should().NotBeNull(); allocationModel.AllocationLine.Id.Should().Be("AAAAA"); allocationModel.AllocationLine.Name.Should().Be("test allocation line 1"); allocationModel.ProfilePeriods.Should().HaveCount(1); ProviderVariation providerVariationModel = allocationModel.Provider.ProviderVariation; providerVariationModel.Should().NotBeNull(); providerVariationModel.VariationReasons.Should().BeEquivalentTo("LegalNameFieldUpdated", "LACodeFieldUpdated"); providerVariationModel.Successors.First().Ukprn.Should().Be("provider3"); providerVariationModel.Predecessors.First().Ukprn.Should().Be("provider1"); providerVariationModel.Predecessors[1].Ukprn.Should().Be("provider2"); providerVariationModel.OpenReason.Should().Be("Fresh Start"); providerVariationModel.CloseReason.Should().Be("Closure"); }