Esempio n. 1
0
        public async Task TestMiddleware_HttpAcceptHtml()
        {
            // Arrange
            var logger     = Mock.Of <ILogger <ErrorHandlingMiddleware> >();
            var middleware = new ErrorHandlingMiddleware((innerHttpContext) =>
            {
                throw new System.Exception("Error", new System.Exception("inner"));
            }, logger);

            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();
            var headerDict = new HeaderDictionary();
            var accept     = @"text/html; q=0.5, application/json, text/x-dvi; q=0.8, text/x-c";

            context.Request.Headers.Add(KeyValuePair.Create <string, StringValues>("Accept", accept));

            // Act
            await middleware.Invoke(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);
            var reader     = new StreamReader(context.Response.Body);
            var streamText = reader.ReadToEnd();

            // Assert
            context.Response.StatusCode
            .Should()
            .Be((int)HttpStatusCode.Redirect);

            context.Response.Headers["Location"]
            .Should().Contain(x => x == "/Error");
        }
Esempio n. 2
0
 public ErrorHandlingMiddlewareTests()
 {
     _next                    = A.Fake <RequestDelegate>();
     _httpContext             = new DefaultHttpContext();
     _logger                  = A.Fake <ILogger <ErrorHandlingMiddleware> >();
     _errorHandlingMiddleware = new ErrorHandlingMiddleware(_next, _logger);
 }
Esempio n. 3
0
        public async void HttpContextResponseMustConsistsOfValuesAccordingToEmptyCollectionException()
        {
            var loggerMock = new Mock <ILogger <ErrorHandlingMiddleware> >();
            var errorHandlingMiddleware = new ErrorHandlingMiddleware(
                next: (innerHttpContext) =>
            {
                throw new EmptyCollectionException("Collection is empty");
            },
                logger: loggerMock.Object);

            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            await errorHandlingMiddleware.Invoke(context);

            var responseMessage = "";
            var expectedMessage = JsonConvert.SerializeObject(new { errorMessage = "Collection is empty" });

            using (var memoryStream = context.Response.Body)
            {
                memoryStream.Position = 0;
                var streamReader = new StreamReader(memoryStream);
                responseMessage = streamReader.ReadToEnd();
            }

            Assert.Equal("application/json", context.Response.ContentType);
            Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode);
            Assert.Equal(expectedMessage, responseMessage);
        }
Esempio n. 4
0
        public async void HttpContextResponseMustConsistsOfDefaultValuesIfCatchedNotProcessableException()
        {
            var loggerMock = new Mock <ILogger <ErrorHandlingMiddleware> >();
            var errorHandlingMiddleware = new ErrorHandlingMiddleware(
                next: (innerHttpContext) =>
            {
                throw new Exception("Something bad is happening!");
            },
                logger: loggerMock.Object);

            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            await errorHandlingMiddleware.Invoke(context);

            var responseMessage = "";
            var expectedMessage = JsonConvert.SerializeObject(new { errorMessage = "Something bad is happening!" });

            using (var memoryStream = context.Response.Body)
            {
                memoryStream.Position = 0;
                var streamReader = new StreamReader(memoryStream);
                responseMessage = streamReader.ReadToEnd();
            }

            Assert.Equal("application/json", context.Response.ContentType);
            Assert.Equal(StatusCodes.Status500InternalServerError, context.Response.StatusCode);
            Assert.Equal(expectedMessage, responseMessage);
        }
Esempio n. 5
0
        public async Task ErrorHandlingMiddleware_ExceptionRaised_ReturnsInternalServerError()
        {
            var mockLogger = Substitute.For <ILoggerFactory>();

            // Arrange
            var middleware = new ErrorHandlingMiddleware(next: (innerHttpContext) =>
            {
                throw new Exception("Something went wrong");
            }
                                                         , mockLogger);


            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            //Act
            await middleware.Invoke(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);

            string objResponse;

            using (var reader = new StreamReader(context.Response.Body))
            {
                objResponse = reader.ReadToEnd();
            }

            //Assert
            Assert.That(objResponse, Does.Contain("Something went wrong"));
            Assert.That(context.Response.StatusCode, Is.EqualTo((int)HttpStatusCode.InternalServerError));
        }
Esempio n. 6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger <IFhirService> logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseExceptionHandler(a => a.Run(async context =>
            {
                var feature = context.Features.Get <IExceptionHandlerPathFeature>();
                if (feature?.Error != null)
                {
                    var exception = feature.Error;

                    var operationOutcome         = ErrorHandlingMiddleware.GetOperationOutCome(exception, true);
                    var fhirJsonConverter        = new FhirJsonSerializer();
                    var result                   = fhirJsonConverter.SerializeToString(operationOutcome);
                    context.Response.ContentType = "application/json";
                    await context.Response.WriteAsync(result);
                }
            }));

            app.ConfigureExceptionHandler(logger);
            app.UseMvc();
        }
Esempio n. 7
0
        public async Task ErrorHandlingMiddleware_NotFoundExceptionRaised_ReturnsNotFoundtWithId()
        {
            var mockLogger = Substitute.For <ILoggerFactory>();

            // Arrange
            var middleware = new ErrorHandlingMiddleware(next: (innerHttpContext) =>
            {
                throw new NotFoundException("Patient", 1);
            }
                                                         , mockLogger);


            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            //Act
            await middleware.Invoke(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);

            string objResponse;

            using (var reader = new StreamReader(context.Response.Body))
            {
                objResponse = reader.ReadToEnd();
            }

            //Assert
            Assert.That(objResponse, Does.Contain("(1) was not found."));
            Assert.That(context.Response.StatusCode, Is.EqualTo((int)HttpStatusCode.NotFound));
        }
        public async Task WhenAnUnExpectedExceptionIsRaised_ErrorHandlingMiddlewareShouldHandleItToCustomErrorResponseAndCorrectHttpStatus()
        {
            // Arrange
            var middleware = new ErrorHandlingMiddleware((innerHttpContext) =>
            {
                throw new NullReferenceException("Test");
            },
                                                         new NullLoggerFactory());

            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            //Act
            await middleware.Invoke(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);
            var reader  = new StreamReader(context.Response.Body);
            var message = reader.ReadToEnd();

            //Assert
            message
            .Should()
            .BeEquivalentTo("Ops, something bad happened");

            context.Response.StatusCode
            .Should()
            .Be((int)HttpStatusCode.BadRequest);
        }
Esempio n. 9
0
        public async Task TestMiddleware_StandardBehavior()
        {
            // Arrange
            var logger     = Mock.Of <ILogger <ErrorHandlingMiddleware> >();
            var middleware = new ErrorHandlingMiddleware((innerHttpContext) =>
            {
                throw new System.Exception("Error", new System.Exception("inner"));
            }, logger);

            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            // Act
            await middleware.Invoke(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);
            var reader     = new StreamReader(context.Response.Body);
            var streamText = reader.ReadToEnd();
            var pd         = JsonSerializer.Deserialize <ProblemDetails>(streamText);

            // Assert
            pd.Type.Should().Be("about:blank");
            pd.Title.Should().StartWith("error during request: ");
            pd.Status.Should().Be(500);
            pd.Detail.Should().Be("Error, inner");

            context.Response.StatusCode
            .Should()
            .Be((int)HttpStatusCode.InternalServerError);
        }
        public async Task InvokeAsync_ShouldCatchExceptionAndReturnStandardErrorWhenDelegateThrows()
        {
            Task next(HttpContext innerHttpContext)
            => throw new Exception("This message must not be shown");

            _context.Response.Body = new MemoryStream();

            var middleware = new ErrorHandlingMiddleware(next, _logger.Object);

            await middleware.InvokeAsync(_context);

            _context.Response.Body.Seek(0, SeekOrigin.Begin);
            var reader     = new StreamReader(_context.Response.Body);
            var streamText = reader.ReadToEnd();

            var result = JsonConvert.DeserializeObject <ErrorDetails>(streamText);

            var expected = new ErrorDetails
            {
                StatusCode = 500,
                Message    = "Oooops! Something went wrong. Call Alessandro :)"
            };

            result
            .Should()
            .BeEquivalentTo(expected);

            _logger.Verify(l => l.LogError(It.IsAny <Exception>(), It.IsAny <string>()), Times.Once());
        }
 public ErrorHandlingMiddlewareTest()
 {
     _next = Moq.Mock.Of <RequestDelegate>();
     _statusCodeOptions = Moq.Mock.Of <IOptionsSnapshot <MockacoOptions> >(o => o.Value == new MockacoOptions());
     _mockProvider      = Moq.Mock.Of <IMockProvider>();
     _logger            = Moq.Mock.Of <ILogger <ErrorHandlingMiddleware> >();
     _middleware        = new ErrorHandlingMiddleware(_next);
 }
Esempio n. 12
0
        public async Task ErrorInDeDelegateMustBeConvertedToResponseError()
        {
            Task ReqDelegate(HttpContext context)
            {
                throw new Exception("Unhandled");
            }

            DefaultHttpContext      defaultHttpContext      = new DefaultHttpContext();
            ErrorHandlingMiddleware errorHandlingMiddleware = new ErrorHandlingMiddleware(ReqDelegate);
            await errorHandlingMiddleware.Invoke(defaultHttpContext);

            Assert.IsTrue(defaultHttpContext.Response.StatusCode == (int)HttpStatusCode.InternalServerError);
        }
Esempio n. 13
0
        public async Task Error_Handling_Middleware_Success()
        {
            var errorHandlingMiddleware = new ErrorHandlingMiddleware(
                async(innerHttpContext) =>
            {
                await innerHttpContext.Response.WriteAsync("test response body");
            }, _mockLoggerFactory.Object);

            var context = new DefaultHttpContext();
            await errorHandlingMiddleware.Invoke(context);

            context.Response.StatusCode.Should().Be((int)HttpStatusCode.OK);
        }
        public void Should_catch_errors()
        {
            //arrange
            var nextProcessor       = new Mock <IMessageProcessor>();
            var messageStateHandler = new Mock <IMessageStateHandler <TestCommand> >();

            nextProcessor.Setup(x => x.ProcessAsync(messageStateHandler.Object, CancellationToken.None))
            .Throws <Exception>();
            var logger     = new Mock <ILog>();
            var middleware = new ErrorHandlingMiddleware(logger.Object);

            //act & assert
            middleware.Invoking(async x => await x.ProcessAsync(messageStateHandler.Object, Mock.Of <IPipelineInformation>(), nextProcessor.Object, CancellationToken.None)).Should().NotThrow();
        }
Esempio n. 15
0
        public async Task ErrorHandlingMiddlewareMustCallNextDelegate()
        {
            var delegateWasExecuted = false;

            Task ReqDelegate(HttpContext context)
            {
                delegateWasExecuted = true;
                return(Task.CompletedTask);
            }

            ErrorHandlingMiddleware errorHandlingMiddleware = new ErrorHandlingMiddleware(ReqDelegate);
            await errorHandlingMiddleware.Invoke(new DefaultHttpContext());

            Assert.IsTrue(delegateWasExecuted);
        }
        public async Task Should_log_errors()
        {
            //arrange
            var nextProcessor       = new Mock <IMessageProcessor>();
            var messageStateHandler = new Mock <IMessageStateHandler <TestCommand> >();

            nextProcessor.Setup(x => x.ProcessAsync(messageStateHandler.Object, CancellationToken.None))
            .Throws <Exception>();
            var logger     = new Mock <ILog>();
            var middleware = new ErrorHandlingMiddleware(logger.Object);
            //act
            await middleware.ProcessAsync(messageStateHandler.Object, nextProcessor.Object, CancellationToken.None);

            //assert
            logger.Verify(x => x.Error(It.IsAny <Exception>(), "Error processing message {@TestCommand}", It.IsAny <TestCommand>()), Times.Once);
        }
        public async Task Should_abandon_message_on_errors()
        {
            //arrange
            var nextProcessor       = new Mock <IMessageProcessor>();
            var messageStateHandler = new Mock <IMessageStateHandler <TestCommand> >();

            nextProcessor.Setup(x => x.ProcessAsync(messageStateHandler.Object, CancellationToken.None))
            .Throws <Exception>();
            var logger     = new Mock <ILog>();
            var middleware = new ErrorHandlingMiddleware(logger.Object);
            //act
            await middleware.ProcessAsync(messageStateHandler.Object, Mock.Of <IPipelineInformation>(), nextProcessor.Object, CancellationToken.None);

            //assert
            messageStateHandler.Verify(x => x.AbandonByErrorAsync(It.IsAny <Exception>()), Times.Once);
        }
        public void Should_not_throw_when_abandon_message_on_errors_fails()
        {
            //arrange
            var nextProcessor       = new Mock <IMessageProcessor>();
            var messageStateHandler = new Mock <IMessageStateHandler <TestCommand> >();

            messageStateHandler.Setup(x => x.AbandonByErrorAsync(It.IsAny <Exception>())).Throws <Exception>();
            nextProcessor.Setup(x => x.ProcessAsync(messageStateHandler.Object, CancellationToken.None))
            .Throws <Exception>();
            var logger     = new Mock <ILog>();
            var middleware = new ErrorHandlingMiddleware(logger.Object);

            //act
            middleware.Invoking(async x => await x.ProcessAsync(messageStateHandler.Object, Mock.Of <IPipelineInformation>(), nextProcessor.Object, CancellationToken.None)).Should().NotThrow();
            //assert
            logger.Verify(x => x.Error(It.IsAny <Exception>(), "Failed to abandon message {@TestCommand}", It.IsAny <TestCommand>()), Times.Once);
        }
Esempio n. 19
0
        public void ChangeSuccessStatusCodeTo500AndRethrowException(int requestStatusCode, int responseStatusCode)
        {
            // Arrange
            var context    = new DefaultHttpContext();
            var middleware = new ErrorHandlingMiddleware(innerHttpContext =>
            {
                innerHttpContext.Response.StatusCode = requestStatusCode;
                throw new Exception("Exception");
            }, Substitute.For <ILogger <ErrorHandlingMiddleware> >());

            // Act
            Func <Task> action = async() => await middleware.Invoke(context);

            // Assert
            action.Should().Throw <Exception>().WithMessage("Exception");
            context.Response.StatusCode.Should().Be(responseStatusCode);
        }
        public async void Invoke_ShouldDoNothing_WhenNextThrowsNoExceptions()
        {
            var httpContext  = new Mock <HttpContext>();
            var httpResponse = new Mock <HttpResponse>();

            httpContext.Setup(a => a.Response).Returns(httpResponse.Object);

            RequestDelegate next = (a) =>
            {
                return(Task.Run(() => { }));
            };

            var classUnderTest = new ErrorHandlingMiddleware(next);

            await classUnderTest.Invoke(httpContext.Object);

            VerifyHttpResponse(httpResponse, It.IsAny <string>(), It.IsAny <int>(), Times.Never());
        }
Esempio n. 21
0
        public async Task Return404StatusCodeForNotFoundException()
        {
            // Arrange
            var context = new DefaultHttpContext();

            context.Response.StatusCode = StatusCodes.Status200OK;

            var middleware = new ErrorHandlingMiddleware(innerHttpContext =>
            {
                throw new NotFoundException();
            }, Substitute.For <ILogger <ErrorHandlingMiddleware> >());

            // Act
            await middleware.Invoke(context);

            // Assert
            context.Response.StatusCode.Should().Be(StatusCodes.Status404NotFound);
        }
Esempio n. 22
0
        public async Task TestMiddleware_LoginChallengeException()
        {
            // Arrange
            var logger     = Mock.Of <ILogger <ErrorHandlingMiddleware> >();
            var middleware = new ErrorHandlingMiddleware((innerHttpContext) =>
            {
                throw new LoginChallengeException("login");
            }, logger);

            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            // Act && Assert
            await Assert.ThrowsAsync <LoginChallengeException>(() => {
                return(middleware.Invoke(context));
            });
        }
        private async Task VerifyErrorHandling(Exception exception, string expectedErrorMessage, HttpStatusCode expectedResponseCode, ApiErrorCode expectedApiErrorCode)
        {
            // Arrange
            RequestDelegate next         = (innerHttpContext) => Task.FromException <Exception>(exception);
            var             loggerMock   = new Mock <ILogger <ErrorHandlingMiddleware> >();
            var             contextMock  = new Mock <HttpContext>();
            var             responseMock = new Mock <HttpResponse>();
            var             body         = new MemoryStream();
            int             responseCode = 0;

            loggerMock.Setup(m => m.Log(
                                 LogLevel.Warning,
                                 It.IsAny <EventId>(),
                                 It.Is <FormattedLogValues>(v => v.ToString().Contains(expectedErrorMessage)),
                                 It.IsAny <Exception>(),
                                 It.IsAny <Func <object, Exception, string> >()
                                 ));
            contextMock.SetupGet(x => x.Response).Returns(responseMock.Object);
            responseMock.SetupGet(x => x.Body).Returns(body);
            responseMock.SetupSet(x => x.StatusCode = It.IsAny <int>()).Callback <int>(y => responseCode = y);

            var middleware = new ErrorHandlingMiddleware(next: next, logger: loggerMock.Object);

            // Act
            await middleware.Invoke(contextMock.Object);

            body.Position = 0;
            var serializedResult = Encoding.UTF8.GetString(body.ToArray());

            body.Dispose();

            // Assert
            loggerMock.VerifyAll();
            contextMock.VerifyAll();
            responseMock.VerifyAll();
            Assert.That(responseCode, Is.EqualTo((int)expectedResponseCode));
            Assert.That(serializedResult, Is.Not.Null);
            dynamic      myobject     = JsonConvert.DeserializeObject(serializedResult);
            string       errorMessage = myobject.Error;
            ApiErrorCode apiErrorCode = myobject.ApiErrorCode;

            Assert.That(errorMessage, Is.EqualTo(expectedErrorMessage));
            Assert.That(apiErrorCode, Is.EqualTo(expectedApiErrorCode));
        }
Esempio n. 24
0
        public async void ProperInformationMustBeLoggedWhenNotHandledExceptionIsRaised()
        {
            var context    = new DefaultHttpContext();
            var loggerMock = new Mock <ILogger <ErrorHandlingMiddleware> >();
            var errorHandlingMiddleware = new ErrorHandlingMiddleware(
                next: (innerHttpContext) =>
            {
                throw new Exception("Something bad is happening here!");
            },
                logger: loggerMock.Object);

            await errorHandlingMiddleware.Invoke(context);

            loggerMock.Verify(exp => exp.Log(It.Is <LogLevel>(x => x == LogLevel.Error),
                                             It.IsAny <EventId>(),
                                             It.IsAny <Object>(),
                                             It.Is <Exception>(y => y.Message == "Something bad is happening here!"),
                                             It.IsAny <Func <object, Exception, string> >()));
        }
        public async void Invoke_ShouldAssembleAnErrorResponse_WhenNextThrowsAnException(Exception ex, int statusCode)
        {
            var httpContext  = new Mock <HttpContext>();
            var httpResponse = new Mock <HttpResponse>();

            httpContext.Setup(a => a.Response).Returns(httpResponse.Object);
            httpResponse.Setup(a => a.Body).Returns(new MemoryStream());

            RequestDelegate next = (a) =>
            {
                return(Task.FromException(ex));
            };

            var classUnderTest = new ErrorHandlingMiddleware(next);

            await classUnderTest.Invoke(httpContext.Object);

            VerifyHttpResponse(httpResponse, "application/json", statusCode, Times.Once());
        }
Esempio n. 26
0
        public void TestMethod1()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            var context     = new ActionExecutingContext(
                new ActionContext
            {
                HttpContext      = httpContext,
                RouteData        = new RouteData(),
                ActionDescriptor = new ActionDescriptor(),
            },
                new List <IFilterMetadata>(),
                new Dictionary <string, object>(),
                new Mock <Controller>().Object);

            // Act
            ErrorHandlingMiddleware errorHandlingMiddleware = this.CreateErrorHandlingMiddleware();
            //errorHandlingMiddleware.Invoke(context);


            // Assert
        }
Esempio n. 27
0
        public async Task ErrorHandlingMiddleware_ValidationExceptionRaised_ReturnsBadRquestWithValidationErrors()
        {
            var mockLogger = Substitute.For <ILoggerFactory>();

            // Arrange
            var middleware = new ErrorHandlingMiddleware(next: (innerHttpContext) =>
            {
                throw new ValidationException(
                    new List <ValidationFailure> {
                    new ValidationFailure("Error", "Big error")
                });
            }
                                                         , mockLogger);


            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            //Act
            await middleware.Invoke(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);

            Dictionary <string, string[]> objResponse;

            using (var reader = new StreamReader(context.Response.Body))
            {
                var streamText = reader.ReadToEnd();
                objResponse = JsonConvert.DeserializeObject <Dictionary <string, string[]> >(streamText);
            }

            //Assert
            var firstError = objResponse.TryGetValue("Error", out string[] errors);

            Assert.That(errors[0], Is.EqualTo("Big error"));
            Assert.That(context.Response.StatusCode, Is.EqualTo((int)HttpStatusCode.BadRequest));
        }
        public async Task ExceptionTests()
        {
            // Arrange
            var statusCode   = 200;
            var contentType  = "";
            var stream       = new MemoryStream();
            var fakeResponse = new Mock <HttpResponse>();

            fakeResponse
            .SetupSet(x => x.StatusCode)
            .Callback(val => statusCode = val);
            fakeResponse
            .SetupSet(x => x.ContentType)
            .Callback(val => contentType = val);
            fakeResponse
            .SetupGet(x => x.BodyPipe)
            .Returns(new StreamPipeWriter(stream));
            fakeResponse
            .SetupGet(x => x.Body)
            .Returns(stream);
            var fakeHttpContext = new Mock <HttpContext>();

            fakeHttpContext
            .SetupGet(x => x.Response)
            .Returns(fakeResponse.Object);
            var handler = new ErrorHandlingMiddleware((ctx =>
            {
                throw new Exception("Test Exception");
            }));

            // Act
            await handler.Invoke(fakeHttpContext.Object);

            // Assert
            Assert.Equal(500, statusCode);
            Assert.Equal("application/json", contentType);
        }
Esempio n. 29
0
 public ErrorHandlingMiddlewareTests()
 {
     _sut = new ErrorHandlingMiddleware(_next);
 }
        private async Task <(ErrorResponse errorResponse, int statusCode)> GetResponseFromContext(ErrorHandlingMiddleware mw)
        {
            var context = new DefaultHttpContext();

            using var memoryStream = new MemoryStream();
            context.Response.Body  = memoryStream;

            await mw.Invoke(context);

            memoryStream.Position = 0;

            using var reader = new StreamReader(memoryStream);
            var content  = reader.ReadToEnd();
            var response = JsonConvert.DeserializeObject <ErrorResponse>(content);

            return(response, context.Response.StatusCode);
        }