public async Task GetFundingStructure_GivenNoTemplateVersionForFundingStream_ReturnsServerError() { string publishedProviderVersionId = NewRandomString(); string specificationId = NewRandomString(); string fundingPeriodId = NewRandomString(); string providerId = NewRandomString(); string fundingStreamId = NewRandomString(); int templateVersion = NewRandomNumber(); PublishedProviderVersion publishedProviderVersion = NewPublishedProviderVersion(_ => _ .WithFundingStreamId(fundingStreamId) .WithFundingPeriodId(fundingPeriodId) .WithProviderId(providerId) .WithSpecificationId(specificationId)); SpecificationSummary specificationSummary = NewSpecificationSummary(_ => _.WithId(specificationId)); _publishedFundingRepository.GetPublishedProviderVersionById(publishedProviderVersionId) .Returns(publishedProviderVersion); _specificationService.GetSpecificationSummaryById(specificationId) .Returns(specificationSummary); var result = await _service.GetPublishedProviderFundingStructure(publishedProviderVersionId); InternalServerErrorResult notFoundObjectResult = result.Should() .BeAssignableTo <InternalServerErrorResult>() .Which .As <InternalServerErrorResult>(); notFoundObjectResult.Value .Should() .Be($"Specification contains no matching template version for funding stream '{fundingStreamId}'"); }
public void TestInternalServerErrorResult_should_work_as_expected_with_method_without_arguments() { ApiControllerHttpActionResultActionTester actionTester = _controllerTester.Action(x => x.HttpActionResultActionWithoutArguments); _controller.HttpActionResult = new InternalServerErrorResult(_controller); InternalServerErrorResult result = null; InternalServerErrorResult validatedResult = null; bool validateWasCalled = false; Action action = () => { result = actionTester.TestInternalServerErrorResult(r => { validatedResult = r; validateWasCalled = true; }); }; action.Should().NotThrow(); result.Should().Be(_controller.HttpActionResult); validateWasCalled.Should().BeTrue(); validatedResult.Should().Be(_controller.HttpActionResult); _controller.HttpActionResult = _okResult; action.Should().Throw <ControllerTestException>().WithMessage( "Expected IHttpActionResult type System.Web.Http.Results.InternalServerErrorResult. Actual: System.Web.Http.Results.OkResult."); }
public async Task SearchCalculationProviderResults_GivenNullResultsReturnedFromSearch_ReturnsStatusCode500() { // Arrange SearchRequestViewModel requestModel = new SearchRequestViewModel(); ICalculationProviderResultsSearchService searchService = CreateCalculationProviderResultsSearchService(); searchService .PerformSearch(Arg.Any <SearchRequestViewModel>()) .Returns((CalculationProviderResultSearchResultViewModel)null); ProviderSearchController controller = CreateController(calculationProviderResultsSearchService: searchService); // Act IActionResult actionResult = await controller.SearchCalculationProviderResults(requestModel); // Asserts actionResult .Should() .BeOfType <InternalServerErrorResult>(); InternalServerErrorResult statusCodeResult = actionResult as InternalServerErrorResult; statusCodeResult .StatusCode .Should() .Be(500); }
public void ForbiddenResultHasStatusCode409() { // Arrange var result = new InternalServerErrorResult(); // Assert Assert.Equal(500, result.StatusCode); }
async public Task SaveFundingConfiguration_GivenValidConfigurationButFailedToSaveToDatabase_ReturnsStatusCode(string fundingStreamId, string fundingPeriodId) { //Arrange FundingStream fundingStream = new FundingStream { Id = fundingStreamId }; FundingPeriod fundingPeriod = new FundingPeriod { Id = fundingPeriodId }; ILogger logger = CreateLogger(); HttpStatusCode statusCode = HttpStatusCode.BadRequest; IPolicyRepository policyRepository = CreatePolicyRepository(); policyRepository .GetFundingStreamById(Arg.Is(fundingStreamId)) .Returns(fundingStream); policyRepository .GetFundingPeriodById(Arg.Is(fundingPeriodId)) .Returns(fundingPeriod); policyRepository .SaveFundingConfiguration(Arg.Is <FundingConfiguration>(x => x.FundingStreamId == fundingStreamId && x.FundingPeriodId == fundingPeriodId)) .Returns(statusCode); FundingConfigurationService fundingConfigurationsService = CreateFundingConfigurationService(logger: logger, policyRepository: policyRepository); FundingConfigurationViewModel fundingConfigurationViewModel = CreateConfigurationModel(); //Act IActionResult result = await fundingConfigurationsService.SaveFundingConfiguration("Action", "Controller", fundingConfigurationViewModel, fundingStreamId, fundingPeriodId); //Assert result .Should() .BeOfType <InternalServerErrorResult>(); InternalServerErrorResult statusCodeResult = (InternalServerErrorResult)result; statusCodeResult .StatusCode .Should() .Be(500); logger .Received(1) .Error(Arg.Is($"Failed to save configuration file for funding stream id: {fundingStreamId} and period id: {fundingPeriodId} to cosmos db with status 400")); }
public async Task ExecuteWhenDeleteSubscriptionCalledReturnsGenericInternalServerErrorResult() { //Arrange A.CallTo(() => subscriptionRegistrationService.DeleteSubscription(A <string> .Ignored)).Throws <ArithmeticException>(); A.CallTo(() => _request.Method).Returns("DELETE"); //Act InternalServerErrorResult result = (InternalServerErrorResult) await RunFunction("test-subscription-name"); // Assert Assert.Equal((int?)HttpStatusCode.InternalServerError, result.StatusCode); }
public void OnException(ExceptionContext context) { this._logger.LogError(new EventId(context.Exception.HResult), context.Exception, context.Exception.Message); var result = new ErrorResult("An error occurred, please try again later."); if (this._environment.IsDevelopment()) { result.Errors = context.Exception.ToString(); } var response = new InternalServerErrorResult(result); context.Result = response; }
public async Task ExecuteWhenAddSubscriptionCalledReturnsInternalServerErrorResult() { //Arrange A.CallTo(() => subscriptionRegistrationService.AddSubscription(A <SubscriptionSettings> .Ignored)).Returns(HttpStatusCode.InternalServerError); A.CallTo(() => _request.Method).Returns("POST"); A.CallTo(() => _request.Body).Returns(new MemoryStream(Encoding.UTF8.GetBytes(GetRequestBody(true, true, true, true)))); A.CallTo(() => advancedFilterOptions.CurrentValue).Returns(new AdvancedFilterOptions { MaximumAdvancedFilterValues = 25, MaximumAdvancedFilters = 5 }); //Act InternalServerErrorResult result = (InternalServerErrorResult) await RunFunction(null); // Assert Assert.Equal((int?)HttpStatusCode.InternalServerError, result.StatusCode); }
public async Task OnGetAsync_GivenDatasetPerformSearchReturnsNullResults_ThenErrorReturned() { //Arrange IDatasetSearchService searchService = CreateSearchService(); DatasetSearchResultViewModel searchResult = null; searchService .PerformSearch(Arg.Any <SearchRequestViewModel>()) .Returns(searchResult); ManageDatasetsPageModel DatasetModel = CreateDatasetPageModel(searchService); //Act IActionResult result = await DatasetModel.OnGetAsync(null, null); //Assert result .Should() .BeOfType <InternalServerErrorResult>(); InternalServerErrorResult statusCodeResult = result as InternalServerErrorResult; statusCodeResult .StatusCode .Should() .Be(500); statusCodeResult .Value .Should() .Equals("There was an error retrieving data sources from the Search Index."); await searchService .Received(1) .PerformSearch(Arg.Is <SearchRequestViewModel>( c => c.PageNumber == null && c.SearchTerm == null)); }
public void Test_ApiErrorResult_Instance(string key, string message) { // Arrange var serviceProviderMock = new Mock <IServiceProvider>(); serviceProviderMock.Setup(serviceProvider => serviceProvider.GetService(typeof(ILogger <ValidateModelAttribute>))) .Returns(Mock.Of <ILogger <ValidateModelAttribute> >()); var httpContext = new DefaultHttpContext { RequestServices = serviceProviderMock.Object }; // Act var err = new ApiErrorResult(new Exception(message), key); var servErr = new InternalServerErrorResult(new Exception(message)); var res = httpContext.Response; var req = httpContext.Request; var apiError = new ApiErrorMessage("", ""); apiError = new ApiErrorMessage(null, ""); apiError = new ApiErrorMessage("test", ""); // Assert err.Message.Should().Be(key); err.Errors.Count.Should().Be(1); err.Errors[0].Message.Should().Be(message); servErr.StatusCode.Should().Be(500); Assert.IsType <ApiErrorResult>(servErr.Value); res.Headers.Add(key, message); res.StatusCode = 200; res.Body = new MemoryStream(Encoding.ASCII.GetBytes(message)); res.ToFormattedString().Length.Should().BeGreaterThan(0); req.Headers.Add(key, message); req.Body = new MemoryStream(Encoding.ASCII.GetBytes(message)); req.ToFormattedString().Length.Should().BeGreaterThan(0); }
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, TraceWriter log) { StringValues name; StringValues surname; IActionResult result = new InternalServerErrorResult(); try { log.Info("C# HTTP trigger shakehand function processed a request"); string requestBody = new StreamReader(req.Body).ReadToEnd(); dynamic reqData = JsonConvert.DeserializeObject(requestBody); bool hasValues = req.Query.TryGetValue("name", out name) && req.Query.TryGetValue("surname", out surname); result = !hasValues?BuildBadReques(name, surname) : new OkObjectResult($"Hello, {name.FirstOrDefault() ?? reqData?.name } " + $"{surname.FirstOrDefault() ?? reqData?.surname} "); } catch (Exception ex) { log.Error($"I am glad to present you this exception message : {ex.Message}"); result = new BadRequestObjectResult(ex); } return(result); }
public async Task GetFundingStructure_GivenNoTemplateMetadataContents_ReturnsServerError() { string publishedProviderVersionId = NewRandomString(); string specificationId = NewRandomString(); string fundingPeriodId = NewRandomString(); string providerId = NewRandomString(); string fundingStreamId = NewRandomString(); int templateVersion = NewRandomNumber(); PublishedProviderVersion publishedProviderVersion = NewPublishedProviderVersion(_ => _ .WithFundingStreamId(fundingStreamId) .WithFundingPeriodId(fundingPeriodId) .WithProviderId(providerId) .WithSpecificationId(specificationId)); SpecificationSummary specificationSummary = NewSpecificationSummary(_ => _ .WithId(specificationId) .WithTemplateIds((fundingStreamId, templateVersion.ToString())));; _publishedFundingRepository.GetPublishedProviderVersionById(publishedProviderVersionId) .Returns(publishedProviderVersion); _specificationService.GetSpecificationSummaryById(specificationId) .Returns(specificationSummary); _policiesService.GetTemplateMetadataContents(fundingStreamId, fundingPeriodId, templateVersion.ToString()) .Returns((TemplateMetadataContents)null); var result = await _service.GetPublishedProviderFundingStructure(publishedProviderVersionId); InternalServerErrorResult notFoundObjectResult = result.Should() .BeAssignableTo <InternalServerErrorResult>() .Which .As <InternalServerErrorResult>(); notFoundObjectResult.Value .Should() .Be($"Unable to locate funding template contents for {fundingStreamId} {fundingPeriodId} {templateVersion}"); }