Exemplo n.º 1
0
        public async void GivenValidHttpContext_WhenInvoke_ThenInvokeSuccessful()
        {
            //?Given
            var context = new DefaultHttpContext();

            //?When
            await _exceptionMiddleware.Invoke(context);

            //?Then
            _next.Verify(n => n.Invoke(context), Times.Once);
        }
        public async Task WhenAnUnexpectedExceptionIsRaised_AnExceptionErrorWillBeReturned_WithInternalServerErrorHttpStatus()
        {
            // Arrange
            var            thrownException  = new Exception("Exception with a parameter: {Param1}");
            ExceptionError expectedResponse = new ExceptionError(System.Net.HttpStatusCode.InternalServerError, thrownException, string.Empty);
            var            middleware       = new ExceptionHandlerMiddleware((innerHttpContext) =>
            {
                throw thrownException;
            }, _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 actualResponse = JsonConvert.DeserializeObject <ExceptionError>(streamText);

            //Assert
            Assert.Equal(expectedResponse.StatusCode, actualResponse.StatusCode);
            Assert.Equal(expectedResponse.StatusCode, context.Response.StatusCode);
            Assert.Equal(expectedResponse.StatusMessage, actualResponse.StatusMessage);
            Assert.Equal(expectedResponse.ErrorMessage, actualResponse.ErrorMessage);
        }
        public async Task WhenAnApiBaseExceptionIsRaised_AExceptionErrorWillBeReturned_WithAProvidedHttpStatus()
        {
            // Arrange
            ApiBaseException thrownException  = new ApiBaseException(System.Net.HttpStatusCode.GatewayTimeout, "A Test Exception");
            ExceptionError   expectedResponse = new ExceptionError(System.Net.HttpStatusCode.GatewayTimeout, thrownException, string.Empty);

            var middleware = new ExceptionHandlerMiddleware((innerHttpContext) =>
            {
                throw thrownException;
            }, _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 actualResponse = JsonConvert.DeserializeObject <ExceptionError>(streamText);

            //Assert
            Assert.Equal(expectedResponse.StatusCode, actualResponse.StatusCode);
            Assert.Equal(expectedResponse.StatusCode, context.Response.StatusCode);
            Assert.Equal(expectedResponse.StatusMessage, actualResponse.StatusMessage);
            Assert.Equal(expectedResponse.ErrorMessage, actualResponse.ErrorMessage);
        }
        public async Task OnlyLogsOnce()
        {
            var uuid              = string.Empty;
            var optionsMock       = new Mock <IOptions <RollbarOptions> >();
            var rollbarClientMock = new Mock <RollbarClient>(optionsMock.Object);

            rollbarClientMock.SetupSequence(m => m.Send(It.IsAny <Payloads.Payload>()))
            .Returns(() => ReturnItem("test"))
            .Returns(() => ReturnItem("fail"));
            var httpContextMock = new Mock <HttpContext>();

            httpContextMock
            .Setup(h => h.Features.Set(It.IsAny <IRollbarResponseFeature>()));
            var rollbar    = new Rollbar(new IBuilder[] { }, new IExceptionBuilder[] { }, rollbarClientMock.Object);
            var middleware = new ExceptionHandlerMiddleware(context =>
            {
                try
                {
                    throw new Exception("Middleware tests");
                }
                catch (Exception exception)
                {
                    rollbar.SendException(exception).Wait();
                    throw;
                }
            });
            await Assert.ThrowsAsync <Exception>(async() => await middleware.Invoke(httpContextMock.Object, rollbar));

            rollbarClientMock.Verify(m => m.Send(It.IsAny <Payloads.Payload>()), Times.Once());
            httpContextMock.Verify(m => m.Features.Set(It.Is <IRollbarResponseFeature>(f => f.Uuid == "test")));
        }
Exemplo n.º 5
0
        public async Task Invoke_should_execute_NotFound_result_if_catches_NotFoundException()
        {
            // Arrange
            A.CallTo(() => _next(A <HttpContext> .Ignored)).Throws(new NotFoundException("Test"));
            var fakeContext = A.Fake <HttpContext>();

            // Act
            await _middleware.Invoke(fakeContext);

            // Assert
            A.CallTo(() => _executor.ExecuteAsync(
                         A <ActionContext> .Ignored,
                         A <ObjectResult> .That
                         .Matches(x => x.StatusCode == (int)HttpStatusCode.NotFound)))
            .MustHaveHappenedOnceExactly();
        }
        public async Task WhenInfrastrucureExceptionIsRaised_ExceptionHandlerMiddlewareShouldHandleItToCustomErrorResponseAndBadRequestHttpStatus()
        {
            // Arrange
            var middleware = new ExceptionHandlerMiddleware((innerHttpContext) =>
            {
                throw new InfrastructureException("Test", "Test");
            });

            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();


            //Act
            await middleware.Invoke(context, _fixture.CurrentEnvironment);

            context.Response.Body.Seek(0, SeekOrigin.Begin);
            var reader     = new StreamReader(context.Response.Body);
            var streamText = reader.ReadToEnd();
            var response   = JsonConvert.DeserializeObject <ErrorResponse>(streamText);

            //Assert
            response.ShouldNotBe(null);
            response.ShouldBeOfType <ErrorResponse>();
            response.Code.ShouldBe("Test");
            response.Message.ShouldBe("Test");
            context.Response.StatusCode.ShouldBe((int)HttpStatusCode.BadRequest);
        }
        public async Task ExceptionHandler_returns_ExceptionResultMessage()
        {
            // Arrange
            var expectedException = new Exception("Any exception...");
            var logger            = new Mock <ILogger <ExceptionHandlerMiddleware> >();
            var exceptionHandler  = new ExceptionHandlerMiddleware(
                (innerHttpContext) => { throw expectedException; },
                logger.Object
                );

            var context = GetContext();

            // Act
            await exceptionHandler.Invoke(context);

            var resultMessage = GetResultMessage(context);

            // Assert
            Assert.NotNull(resultMessage);
            Assert.NotEqual(Guid.Empty, resultMessage.ErrorId);
            Assert.Equal(
                "An error occurred and your message couldn't be processed. If the error persists, contact the admin informing the error id provided.",
                resultMessage.Message
                );
        }
        public async Task ExceptionHandler_logs_and_returns_errorId()
        {
            // Arrange
            var expectedException = new Exception("Any exception...");
            var logger            = new Mock <ILogger <ExceptionHandlerMiddleware> >();
            var exceptionHandler  = new ExceptionHandlerMiddleware(
                (innerHttpContext) => { throw expectedException; },
                logger.Object
                );

            var context = GetContext();

            // Act
            await exceptionHandler.Invoke(context);

            var resultMessage = GetResultMessage(context);

            // Assert
            Assert.NotEqual(Guid.Empty, resultMessage.ErrorId);
            logger.Verify(l =>
                          l.Log(
                              LogLevel.Error,
                              0,
                              It.Is <FormattedLogValues>(v => v.ToString() == $"[ErrorId={resultMessage.ErrorId}] {context.Request.Method} {context.Request.Path}"),
                              It.Is <Exception>(e => e == expectedException),
                              It.IsAny <Func <object, Exception, string> >())
                          );
        }
        public async Task WhenAModelStateValidationExceptionIsRaised_AValidationErrorWillBeReturned_WithBadRequestHttpStatus()
        {
            // Arrange
            var requestDTO = new RequestModelBasic()
            {
                Id = 0, Message = string.Empty, CreatedOn = DateTime.Now
            };

            // Perform a validation using ModelState
            var modelState = new ModelStateDictionary();

            modelState.AddModelError("Error_1", "Input string '1.3' is not a valid integer. Path 'userId', line 2, position 17.");
            modelState["Error_1"].RawValue = "1.3";
            modelState.AddModelError("Error_2", "Could not convert string to DateTime: 2018:10. Path 'momentsDate', line 4, position 28.");
            ValidationException thrownException = new ValidationException("bad_request", modelState, string.Empty);

            ValidationError expectedResponse = new ValidationError(thrownException.ValidationFailures, string.Empty);

            var middleware = new ExceptionHandlerMiddleware((innerHttpContext) =>
            {
                throw thrownException;
            }, _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 actualResponse = JsonConvert.DeserializeObject <ValidationError>(streamText);

            //Assert
            Assert.Equal(expectedResponse.StatusCode, actualResponse.StatusCode);
            Assert.Equal(expectedResponse.StatusCode, context.Response.StatusCode);
            Assert.Equal(expectedResponse.StatusMessage, actualResponse.StatusMessage);
            Assert.NotNull(actualResponse.Errors);
            Assert.Equal(expectedResponse.Errors.Count, actualResponse.Errors.Count);

            for (int i = 0; i < actualResponse.Errors.Count; i++)
            {
                Assert.Equal(expectedResponse.Errors[i].Code, actualResponse.Errors[i].Code);
                Assert.Equal(expectedResponse.Errors[i].Message, actualResponse.Errors[i].Message);
                Assert.Equal(expectedResponse.Errors[i].AttemptedValue, actualResponse.Errors[i].AttemptedValue);
                Assert.Equal(expectedResponse.Errors[i].Field, actualResponse.Errors[i].Field);
            }
        }
        public async Task WhenAFluentValidationExceptionIsRaised_AValidationErrorWillBeReturned_WithBadRequestHttpStatus()
        {
            // Arrange
            var requestDTO = new RequestModelBasic()
            {
                Id = 0, Message = string.Empty, CreatedOn = DateTime.Now
            };

            // Perform a validation using a FluentValidator
            var validator = new RequestModelBasicValidator();

            FluentValidation.Results.ValidationResult validationResult = validator.Validate(requestDTO);
            ValidationException thrownException = new ValidationException(validationResult.Errors, string.Empty);

            ValidationError expectedResponse = new ValidationError(validationResult.Errors, string.Empty);

            var middleware = new ExceptionHandlerMiddleware((innerHttpContext) =>
            {
                throw thrownException;
            }, _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 actualResponse = JsonConvert.DeserializeObject <ValidationError>(streamText);

            //Assert
            Assert.Equal(expectedResponse.StatusCode, actualResponse.StatusCode);
            Assert.Equal(expectedResponse.StatusCode, context.Response.StatusCode);
            Assert.Equal(expectedResponse.StatusMessage, actualResponse.StatusMessage);
            Assert.NotNull(actualResponse.Errors);
            Assert.Equal(expectedResponse.Errors.Count, actualResponse.Errors.Count);

            for (int i = 0; i < actualResponse.Errors.Count; i++)
            {
                Assert.Equal(expectedResponse.Errors[i].Code, actualResponse.Errors[i].Code);
                Assert.Equal(expectedResponse.Errors[i].Message, actualResponse.Errors[i].Message);
                Assert.Equal(expectedResponse.Errors[i].AttemptedValue.ToString(), actualResponse.Errors[i].AttemptedValue.ToString());
                Assert.Equal(expectedResponse.Errors[i].Field, actualResponse.Errors[i].Field);
            }
        }
        public async Task WhenAnUnExpectedExceptionIsRaised_CustomExceptionMiddlewareShouldHandleItToInternalServerErrorHttpStatus()
        {
            // Arrange
            var middleware = new ExceptionHandlerMiddleware(next: (innerHttpContext) =>
            {
                throw new Exception();
            });

            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            //Act
            await middleware.Invoke(context, _fixture.CurrentEnvironment);

            //Assert
            context.Response.StatusCode.ShouldBe((int)HttpStatusCode.InternalServerError);
        }
        public async Task WhenUnauthorizedExceptionIsRaised_ExceptionHandlerMiddlewareShouldHandleItToUnauthorizedHttpStatus()
        {
            // Arrange
            var middleware = new ExceptionHandlerMiddleware((innerHttpContext) =>
            {
                throw new UnauthorizedAccessException();
            });

            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            //Act
            await middleware.Invoke(context, _fixture.CurrentEnvironment);

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

            //Assert
            context.Response.StatusCode.ShouldBe((int)HttpStatusCode.Unauthorized);
        }
Exemplo n.º 13
0
        public async Task ExceptionHandlerMiddleware_CatchException()
        {
            // Arrange
            var    exHandler               = new Mock <IExceptionHandler>();
            int    expectedStatusCode      = 500;
            string expectedResponseContent = "test";

            exHandler.Setup(x => x.CreateResponseContent()).Returns(expectedResponseContent);
            exHandler.Setup(x => x.GetHttpStatusCode()).Returns(expectedStatusCode);

            var exHandlerFactory = new Mock <IExceptionHandlerFactory>();

            Exception ex = new Exception();

            exHandlerFactory.Setup(x => x.GetExceptionHandler(ex)).Returns(exHandler.Object);

            var middleware = new ExceptionHandlerMiddleware(exHandlerFactory.Object, (innerHttpContext) =>
            {
                throw ex;
            });

            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            // Act
            await middleware.Invoke(context);

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

            responseContent.Should().BeEquivalentTo(expectedResponseContent);
            context.Response.StatusCode.Should().Be(expectedStatusCode);
        }
 public async Task Baseline()
 {
     await _middleware.Invoke(_httpContext);
 }
 public async Task Baseline()
 {
     await _middleware.Invoke(_downstreamContext);
 }
Exemplo n.º 16
0
 private void WhenICallTheMiddlewareWithTheRequestIdKey(string key, string value)
 {
     _downstreamContext.HttpContext.Request.Headers.Add(key, value);
     _middleware.Invoke(_downstreamContext).GetAwaiter().GetResult();
 }