public async Task ApplicationControllerGetActionAddsModelStateErrorWhenPathIsNull() { var requestModel = new ActionGetRequestModel { Path = BadChildAppPath }; var fakeApplicationService = A.Fake <IApplicationService>(); A.CallTo(() => fakeApplicationService.GetMarkupAsync(A <ApplicationModel> .Ignored, A <string> .Ignored, A <PageViewModel> .Ignored, A <string> .Ignored)).Throws <RedirectException>(); A.CallTo(() => fakeApplicationService.GetApplicationAsync(ChildAppPath)).Returns(defaultApplicationModel); var applicationController = new ApplicationController(defaultMapper, defaultLogger, fakeApplicationService, defaultVersionedFiles, defaultConfiguration, defaultBaseUrlService) { ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext(), }, }; await applicationController.Action(requestModel).ConfigureAwait(false); //A.CallTo(() => defaultLogger.Log(LogLevel.Information, 0, A<IReadOnlyList<KeyValuePair<string, object>>>.Ignored, A<Exception>.Ignored, A<Func<object, Exception, string>>.Ignored)).MustHaveHappened(3, Times.Exactly); A.CallTo(() => defaultLogger.Log <ApplicationController>(A <LogLevel> .Ignored, A <EventId> .Ignored, A <ApplicationController> .Ignored, A <Exception> .Ignored, A <Func <ApplicationController, Exception, string> > .Ignored)).MustHaveHappened(3, Times.Exactly); applicationController.Dispose(); }
public async Task GetApplicationAsyncReturnsPathsAndRegionsAndRootUriPagesApp() { // Arrange var bodyAndFooterRegions = new List <RegionModel> { defaultBodyRegion, defaultBodyFooterRegion, }; var thisChildAppActionGetRequestModel = new ActionGetRequestModel { Path = "help-me", Data = string.Empty }; var appRegistryModel = appRegistryDataService.GetAppRegistrationModel(AppRegistryPathNameForPagesApp).Result; appRegistryModel.Regions = bodyAndFooterRegions; appRegistryModel.PageLocations = new Dictionary <Guid, PageLocationModel> { { Guid.NewGuid(), new PageLocationModel { Locations = new List <string> { "/help-me" } } } }; // Act var service = new ApplicationService(appRegistryDataService, contentRetriever, contentProcessor, taskHelper, markupMessages); var result = await service.GetApplicationAsync(thisChildAppActionGetRequestModel).ConfigureAwait(false); // Assert Assert.Equal(AppRegistryPathNameForPagesApp, result.AppRegistrationModel.Path); Assert.Equal(bodyAndFooterRegions.Count, result.AppRegistrationModel.Regions.Count); Assert.Equal(RequestBaseUrl, result.RootUrl); }
private async Task <ApplicationModel> DetermineArticleLocation(ActionGetRequestModel data) { const string appRegistryPathNameForPagesApp = "pages"; var pageLocation = string.Join("/", new[] { data.Path, data.Data }); var pageLocations = pageLocation.Split("/", StringSplitOptions.RemoveEmptyEntries); var article = string.Join("/", pageLocations); var applicationModel = new ApplicationModel(); var pagesAppRegistrationModel = await appRegistryDataService.GetAppRegistrationModel(appRegistryPathNameForPagesApp); if (pagesAppRegistrationModel?.PageLocations != null && pagesAppRegistrationModel.PageLocations.Values.SelectMany(s => s.Locations).Contains("/" + article)) { applicationModel.AppRegistrationModel = pagesAppRegistrationModel; applicationModel.Article = article; } if (applicationModel.AppRegistrationModel == null) { applicationModel.AppRegistrationModel = await appRegistryDataService.GetAppRegistrationModel(article) ?? await appRegistryDataService.GetAppRegistrationModel(data.Path); if (applicationModel.AppRegistrationModel != null) { applicationModel.Article = article.Length > applicationModel.AppRegistrationModel.Path.Length ? article.Substring(applicationModel.AppRegistrationModel.Path.Length + 1) : null; } } return(applicationModel); }
public async Task ApplicationControllerGetActionReturnsSuccess() { var requestModel = new ActionGetRequestModel { Path = ChildAppPath }; var response = await defaultGetController.Action(requestModel).ConfigureAwait(false); var viewResult = Assert.IsAssignableFrom <ViewResult>(response); var model = Assert.IsAssignableFrom <PageViewModelResponse>(viewResult.ViewData.Model); Assert.Equal(model.Path, ChildAppPath); }
private ActionGetRequestModel[] GetRequestItemModels(ActionGetRequestModel requestViewModel) { var notFoundErrorRequestViewModel = new ActionGetRequestModel { Path = AlertPathName, Data = $"{(int)HttpStatusCode.NotFound}", }; var internalServerErrorRequestViewModel = new ActionGetRequestModel { Path = AlertPathName, Data = $"{(int)HttpStatusCode.InternalServerError}", }; return(new[] { requestViewModel, notFoundErrorRequestViewModel, internalServerErrorRequestViewModel, }); }
public async Task <ApplicationModel> GetApplicationAsync(ActionGetRequestModel data) { var applicationModel = await DetermineArticleLocation(data).ConfigureAwait(false); if (applicationModel.AppRegistrationModel == null) { return(applicationModel); } var bodyRegion = applicationModel.AppRegistrationModel.Regions?.FirstOrDefault(x => x.PageRegion == PageRegion.Body); if (bodyRegion != null && !string.IsNullOrWhiteSpace(bodyRegion.RegionEndpoint)) { var uri = new Uri(bodyRegion.RegionEndpoint); var url = $"{uri.Scheme}://{uri.Authority}"; applicationModel.RootUrl = url; } return(applicationModel); }
public async Task ApplicationControllerPostActionAddsModelStateErrorWhenPathIsNull() { var fakeApplicationService = A.Fake <IApplicationService>(); var childAppActionGetRequestModel = new ActionGetRequestModel { Path = BadChildAppPath, Data = BadChildAppData }; A.CallTo(() => fakeApplicationService.PostMarkupAsync(A <ApplicationModel> .Ignored, A <IEnumerable <KeyValuePair <string, string> > > .Ignored, A <PageViewModel> .Ignored)).Throws <RedirectException>(); A.CallTo(() => fakeApplicationService.GetApplicationAsync(childAppActionGetRequestModel)).Returns(null as ApplicationModel); using var applicationController = new ApplicationController(defaultMapper, defaultLogger, fakeApplicationService, defaultVersionedFiles, defaultConfiguration, defaultBaseUrlService, neo4JService) { ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext { Request = { Method = "POST" }, }, }, }; await applicationController.Action(defaultPostRequestViewModel).ConfigureAwait(false); A.CallTo(() => defaultLogger.Log(LogLevel.Information, 0, A <IReadOnlyList <KeyValuePair <string, object> > > .Ignored, A <Exception> .Ignored, A <Func <object, Exception, string> > .Ignored)).MustHaveHappened(3, Times.Exactly); }
public async Task ApplicationControllerGetActionThrowsAndLogsRedirectExceptionWhenExceptionOccurs() { var requestModel = new ActionGetRequestModel { Path = ChildAppPath, Data = ChildAppData }; var fakeApplicationService = A.Fake <IApplicationService>(); A.CallTo(() => fakeApplicationService.GetMarkupAsync(A <ApplicationModel> .Ignored, A <PageViewModel> .Ignored, A <string> .Ignored)).Throws <RedirectException>(); A.CallTo(() => fakeApplicationService.GetApplicationAsync(childAppActionGetRequestModel)).Returns(defaultApplicationModel); using var applicationController = new ApplicationController(defaultMapper, defaultLogger, fakeApplicationService, defaultVersionedFiles, defaultConfiguration, defaultBaseUrlService, neo4JService) { ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext(), }, }; await applicationController.Action(requestModel).ConfigureAwait(false); A.CallTo(() => defaultLogger.Log(LogLevel.Information, 0, A <IReadOnlyList <KeyValuePair <string, object> > > .Ignored, A <Exception> .Ignored, A <Func <object, Exception, string> > .Ignored)).MustHaveHappened(4, Times.Exactly); }
public async Task ApplicationControllerGetActionAddsModelStateErrorWhenPathIsNull() { var requestModel = new ActionGetRequestModel { Path = BadChildAppPath, Data = BadChildAppData }; var fakeApplicationService = A.Fake <IApplicationService>(); A.CallTo(() => fakeApplicationService.GetMarkupAsync(A <ApplicationModel> .Ignored, A <PageViewModel> .Ignored, A <string> .Ignored, A <string> .Ignored, A <IHeaderDictionary> .Ignored)).Throws <RedirectException>(); A.CallTo(() => fakeApplicationService.GetApplicationAsync(childAppActionGetRequestModel)).Returns(defaultApplicationModel); using var applicationController = new ApplicationController(defaultMapper, defaultLogger, fakeApplicationService, defaultVersionedFiles, defaultConfiguration, defaultBaseUrlService, neo4JService) { ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext(), }, }; await applicationController.Action(requestModel); A.CallTo(() => defaultLogger.Log <ApplicationController>(A <LogLevel> .Ignored, A <EventId> .Ignored, A <ApplicationController> .Ignored, A <Exception> .Ignored, A <Func <ApplicationController, Exception, string> > .Ignored)).MustHaveHappened(3, Times.Exactly); }
public async Task <ApplicationModel> GetApplicationAsync(ActionGetRequestModel data) { _ = data ?? throw new ArgumentNullException(nameof(data)); var applicationModel = await DetermineArticleLocation(data); if (applicationModel.AppRegistrationModel == null) { return(applicationModel); } var bodyRegion = applicationModel.AppRegistrationModel.Regions?.FirstOrDefault(x => x.PageRegion == PageRegion.Body); if (!string.IsNullOrWhiteSpace(bodyRegion?.RegionEndpoint)) { var uri = new Uri(bodyRegion.RegionEndpoint); var url = $"{uri.Scheme}://{uri.Authority}"; applicationModel.RootUrl = url; } return(applicationModel); }
public async Task ApplicationControllerGetActionReturnsRedirectWhenRedirectExceptionOccurs() { var requestModel = new ActionGetRequestModel { Path = ChildAppPath, Data = ChildAppData }; var fakeApplicationService = A.Fake <IApplicationService>(); A.CallTo(() => fakeApplicationService.GetMarkupAsync(A <ApplicationModel> .Ignored, A <PageViewModel> .Ignored, A <string> .Ignored)).Throws <RedirectException>(); A.CallTo(() => fakeApplicationService.GetApplicationAsync(A <ActionGetRequestModel> .Ignored)).Returns(defaultApplicationModel); var context = new DefaultHttpContext(); using var applicationController = new ApplicationController(defaultMapper, defaultLogger, fakeApplicationService, defaultVersionedFiles, defaultConfiguration, defaultBaseUrlService, neo4JService) { ControllerContext = new ControllerContext() { HttpContext = context, }, }; await applicationController.Action(requestModel).ConfigureAwait(false); Assert.True(context.Response.StatusCode == (int)HttpStatusCode.Redirect); }
public async Task <IActionResult> Action(ActionGetRequestModel requestViewModel) { var viewModel = versionedFiles.BuildDefaultPageViewModel(configuration); if (requestViewModel != null) { requestViewModel.Path = requestViewModel.Path?.ToLowerInvariant(); requestViewModel.Data = requestViewModel.Data?.ToLowerInvariant(); var errorRequestViewModel = new ActionGetRequestModel { Path = AlertPathName, Data = $"{(int)HttpStatusCode.NotFound}", }; var requestItems = new[] { requestViewModel, errorRequestViewModel, new ActionGetRequestModel { Path = AlertPathName, Data = $"{(int)HttpStatusCode.InternalServerError}", }, }; foreach (var requestItem in requestItems) { try { logger.LogInformation($"{nameof(Action)}: Getting child response for: {requestItem.Path}/{requestItem.Data}"); await neo4JService.InsertNewRequest(Request).ConfigureAwait(false); var application = await applicationService.GetApplicationAsync(requestItem).ConfigureAwait(false); if (application?.AppRegistrationModel == null) { var errorString = $"The path '{requestItem.Path}' is not registered"; logger.LogWarning($"{nameof(Action)}: {errorString}"); Response.StatusCode = (int)HttpStatusCode.NotFound; } else if (application.AppRegistrationModel.ExternalURL != null) { logger.LogInformation($"{nameof(Action)}: Redirecting to external for: {application.AppRegistrationModel.Path}/{application.Article}"); return(Redirect(application.AppRegistrationModel.ExternalURL.ToString())); } else { await mapper.Map(application, viewModel).ConfigureAwait(false); applicationService.RequestBaseUrl = baseUrlService.GetBaseUrl(Request, Url); await applicationService.GetMarkupAsync(application, viewModel, Request.QueryString.Value).ConfigureAwait(false); logger.LogInformation($"{nameof(Action)}: Received child response for: {application.AppRegistrationModel.Path}/{application.Article}"); if (string.Compare(application.AppRegistrationModel.Path, AlertPathName, true, CultureInfo.InvariantCulture) == 0 && int.TryParse(application.Article, out var statusCode)) { Response.StatusCode = statusCode; } break; } } catch (EnhancedHttpException ex) { var errorString = $"The content {ex.Url} responded with {ex.StatusCode}"; logger.LogWarning($"{nameof(Action)}: {errorString}"); Response.StatusCode = (int)ex.StatusCode; errorRequestViewModel.Data = $"{Response.StatusCode}"; } catch (RedirectException ex) { var redirectTo = ex.Location?.OriginalString; logger.LogInformation(ex, $"{nameof(Action)}: Redirecting from: {ex.OldLocation?.ToString()} to: {redirectTo}"); Response.Redirect(redirectTo, ex.IsPermenant); break; } } } return(View(MainRenderViewName, Map(viewModel))); }
public ApplicationControllerTests() { defaultAppRegistryDataService = A.Fake <IAppRegistryDataService>(); defaultMapper = new ApplicationToPageModelMapper(defaultAppRegistryDataService); defaultLogger = A.Fake <ILogger <ApplicationController> >(); defaultApplicationService = A.Fake <IApplicationService>(); defaultVersionedFiles = A.Fake <IVersionedFiles>(); defaultConfiguration = A.Fake <IConfiguration>(); defaultBaseUrlService = A.Fake <IBaseUrlService>(); neo4JService = A.Fake <INeo4JService>(); defaultApplicationModel = new ApplicationModel { AppRegistrationModel = new AppRegistrationModel { Path = ChildAppPath, Regions = new List <RegionModel> { new RegionModel { IsHealthy = true, PageRegion = PageRegion.Body, RegionEndpoint = "http://childApp/bodyRegion", }, }, }, }; defaultPostRequestViewModel = new ActionPostRequestModel { Path = ChildAppPath, Data = ChildAppData, FormCollection = new FormCollection(new Dictionary <string, StringValues> { { "someKey", "someFormValue" }, }), }; childAppActionGetRequestModel = defaultPostRequestViewModel; A.CallTo(() => defaultApplicationService.GetApplicationAsync(childAppActionGetRequestModel)).Returns(defaultApplicationModel); var fakeHttpContext = new DefaultHttpContext { Request = { QueryString = QueryString.Create("test", "testvalue") } }; defaultGetController = new ApplicationController(defaultMapper, defaultLogger, defaultApplicationService, defaultVersionedFiles, defaultConfiguration, defaultBaseUrlService, neo4JService) { ControllerContext = new ControllerContext { HttpContext = fakeHttpContext, }, }; defaultPostController = new ApplicationController(defaultMapper, defaultLogger, defaultApplicationService, defaultVersionedFiles, defaultConfiguration, defaultBaseUrlService, neo4JService) { ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext() { Request = { Method = "POST" }, }, }, }; bearerTokenController = new ApplicationController(defaultMapper, defaultLogger, defaultApplicationService, defaultVersionedFiles, defaultConfiguration, defaultBaseUrlService, neo4JService) { ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext { User = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim> { new Claim("bearer", "test") }, "mock")) }, }, }; postBearerTokenController = new ApplicationController(defaultMapper, defaultLogger, defaultApplicationService, defaultVersionedFiles, defaultConfiguration, defaultBaseUrlService, neo4JService) { ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext { User = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim> { new Claim("bearer", "test") }, "mock")) }, }, }; }
public async Task <IActionResult> Action(ActionGetRequestModel requestViewModel) { var viewModel = versionedFiles.BuildDefaultPageViewModel(configuration); if (requestViewModel != null) { var requestItems = GetRequestItemModels(requestViewModel); foreach (var requestItem in requestItems) { try { logger.LogInformation($"{nameof(Action)}: Getting child response for: {requestItem.Path}"); var application = await applicationService.GetApplicationAsync(requestItem.Path).ConfigureAwait(false); if (application?.Path == null) { var errorString = $"The path '{requestItem.Path}' is not registered"; logger.LogWarning($"{nameof(Action)}: {errorString}"); Response.StatusCode = (int)HttpStatusCode.NotFound; } else if (!string.IsNullOrWhiteSpace(application.Path.ExternalURL)) { logger.LogInformation($"{nameof(Action)}: Redirecting to external for: {requestItem.Path}"); return(Redirect(application.Path.ExternalURL)); } else { mapper.Map(application, viewModel); applicationService.RequestBaseUrl = baseUrlService.GetBaseUrl(Request, Url); await applicationService.GetMarkupAsync(application, requestItem.Data, viewModel, Request.QueryString.Value).ConfigureAwait(false); logger.LogInformation($"{nameof(Action)}: Received child response for: {requestItem.Path}"); if (string.Compare(requestItem.Path, AlertPathName, true, CultureInfo.InvariantCulture) == 0 && int.TryParse(requestItem.Data, out var statusCode)) { Response.StatusCode = statusCode; } break; } } catch (EnhancedHttpException ex) { var errorString = $"The content {ex.Url} responded with {ex.StatusCode}"; logger.LogWarning($"{nameof(Action)}: {errorString}"); Response.StatusCode = (int)ex.StatusCode; requestItems.First(m => m.Data == $"{(int)HttpStatusCode.NotFound}").Data = $"{Response.StatusCode}"; } catch (RedirectException ex) { var redirectTo = ex.Location?.OriginalString; logger.LogInformation(ex, $"{nameof(Action)}: Redirecting from: {ex.OldLocation?.ToString()} to: {redirectTo}"); Response.Redirect(redirectTo, ex.IsPermenant); } } } return(View(MainRenderViewName, Map(viewModel))); }