Exemplo n.º 1
0
        public async Task ShouldLogStartOfRequest()
        {
            SetOwinRequest("http://something.com/else/stuff");

            await _loggingMiddleware.Invoke(_context);

            Assert.Contains("Starting Request for: http://something.com/else/stuff", _loggerFake.InfoMessages);
        }
        public async Task Invoke_ShouldPassContextToNextDelegate()
        {
            // Arrange
            var context = new DefaultHttpContext();

            // Act
            await _sut.Invoke(context);

            // Assert
            var mock = Mock.Get(_next);

            mock.Verify(next => next(context), Times.Once);
        }
        public async Task Should_Redact_Dynamic_Multiple_Paths()
        {
            // Arrange
            var loggerMock = new Mock <ILogger <LoggingMiddleware> >();
            var options    = Options.Create(new LoggingSettings
            {
                PathsToRedact = new[] { "/api/v1/devices/{*}/activate/{*}" }
            });

            var middleware = new LoggingMiddleware(
                (innerHttpContext) => Task.CompletedTask,
                loggerMock.Object,
                options,
                new AppContextAccessorMock()
                );

            var context = CreateHttpContext();

            context.Request.Path = "/api/v1/devices/guid-identifier/activate/{another-guid}";

            //Act
            await middleware.Invoke(context);

            //Assert
            loggerMock.Verify(l => l.BeginScope(It.IsAny <It.IsAnyType>()), Times.Exactly(1));

            loggerMock.Verify(l => l.Log(
                                  LogLevel.Information,
                                  0,
                                  It.Is <It.IsAnyType>((v, _) => (v.ToString() ?? string.Empty).Contains("[redacted]")),
                                  It.IsAny <Exception>(),
                                  (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()),
                              Times.Once
                              );
        }
        public async Task Should_Ignore_Authorization_Header()
        {
            // Arrange
            var loggerMock = new Mock <ILogger <LoggingMiddleware> >();

            var options    = Options.Create(new LoggingSettings());
            var middleware = new LoggingMiddleware(
                (innerHttpContext) => Task.CompletedTask,
                loggerMock.Object,
                options,
                new AppContextAccessorMock()
                );

            var context = CreateHttpContext();

            context.Request.Path = "/api/v1/tests";
            context.Request.Body = new MemoryStream();
            context.Request.Headers.Add("Authorization", "JWT_TOKEN");
            context.Request.Headers.Add("User-Agent", "android");

            //Act
            await middleware.Invoke(context);

            //Assert
            loggerMock.Verify(l => l.Log(
                                  LogLevel.Information,
                                  0,
                                  It.Is <It.IsAnyType>((v, _) => !(v.ToString() ?? string.Empty).Contains("Authorization")
                                                       ),
                                  It.IsAny <Exception>(),
                                  (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()),
                              Times.Exactly(2)
                              );
        }
        public async Task LoggingMiddleware_IgnoresLog_ForSwagger(string scheme, string host, string path,
                                                                  string queryString, string method, int statusCode)
        {
            // Arrange
            RequestDelegate next        = (innerHttpContext) => Task.FromResult(0);
            var             loggerMock  = new Mock <ILogger <LoggingMiddleware> >();
            var             contextMock = new Mock <HttpContext>();
            var             requestMock = new Mock <HttpRequest>();

            contextMock.SetupGet(x => x.Request).Returns(requestMock.Object);
            MockRequestGetDispayedUrl(requestMock, scheme, host, path, method, queryString);

            var logRequestMiddleware = new LoggingMiddleware(next: next, logger: loggerMock.Object);

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

            // Assert
            loggerMock.VerifyAll();
            contextMock.VerifyAll();
            requestMock.VerifyAll();
            loggerMock.Verify(m =>
                              m.Log(It.IsAny <LogLevel>(), It.IsAny <EventId>(), It.IsAny <FormattedLogValues>(), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >()),
                              Times.Never);
        }
        public async Task Should_Log_Error_Response()
        {
            // Arrange
            var loggerMock = new Mock <ILogger <LoggingMiddleware> >();

            var options    = Options.Create(new LoggingSettings());
            var middleware = new LoggingMiddleware(
                (innerHttpContext) => Task.CompletedTask,
                loggerMock.Object,
                options,
                new AppContextAccessorMock()
                );

            var context = CreateHttpContext();

            context.Request.Path        = "/api/v1/tests";
            context.Request.Body        = new MemoryStream();
            context.Request.Scheme      = "https";
            context.Response.StatusCode = 500;

            //Act
            await middleware.Invoke(context);

            //Assert
            loggerMock.Verify(l => l.BeginScope(It.IsAny <It.IsAnyType>()), Times.Exactly(1));

            loggerMock.Verify(l => l.Log(
                                  LogLevel.Information,
                                  0,
                                  It.Is <It.IsAnyType>((v, _) => (v.ToString() ?? string.Empty).StartsWith("Request")),
                                  It.IsAny <Exception>(),
                                  (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()),
                              Times.Once
                              );

            loggerMock.Verify(l => l.Log(
                                  LogLevel.Information,
                                  0,
                                  It.Is <It.IsAnyType>((v, _) => (v.ToString() ?? string.Empty).StartsWith("Response")),
                                  It.IsAny <Exception>(),
                                  (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()),
                              Times.Once
                              );
        }
        public async Task Should_Ignore_Paths()
        {
            // Arrange
            var loggerMock = new Mock <ILogger <LoggingMiddleware> >();

            var options    = Options.Create(new LoggingSettings());
            var middleware = new LoggingMiddleware(
                (innerHttpContext) => Task.CompletedTask,
                loggerMock.Object,
                options,
                new AppContextAccessorMock()
                );

            var context = CreateHttpContext();

            context.Request.Path = "/health";

            //Act
            await middleware.Invoke(context);

            //Assert
            loggerMock.Verify(l => l.BeginScope(It.IsAny <It.IsAnyType>()), Times.Never());
        }
        public async Task LoggingMiddleware_LogsContextInfo(string scheme, string host, string path,
                                                            string queryString, string method, int statusCode)
        {
            // Arrange
            RequestDelegate next         = (innerHttpContext) => Task.FromResult(0);
            var             loggerMock   = new Mock <ILogger <LoggingMiddleware> >();
            var             contextMock  = new Mock <HttpContext>();
            var             requestMock  = new Mock <HttpRequest>();
            var             responseMock = new Mock <HttpResponse>();

            contextMock.SetupGet(x => x.Request).Returns(requestMock.Object);
            MockRequestGetDispayedUrl(requestMock, scheme, host, path, method, queryString);
            requestMock.Setup(x => x.Method).Returns(method);
            contextMock.SetupGet(x => x.Response).Returns(responseMock.Object);
            responseMock.SetupGet(x => x.StatusCode).Returns(statusCode);
            var allParts = new[] { scheme, host, path, queryString, method, statusCode.ToString() };

            // Mock logger.LogDebug
            loggerMock.Setup(m => m.Log(
                                 LogLevel.Debug,
                                 It.IsAny <EventId>(),
                                 It.Is <FormattedLogValues>(v => allParts.All(x => v.ToString().Contains(x))),
                                 It.IsAny <Exception>(),
                                 It.IsAny <Func <object, Exception, string> >()
                                 ));

            var logRequestMiddleware = new LoggingMiddleware(next: next, logger: loggerMock.Object);

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

            // Assert
            loggerMock.VerifyAll();
            contextMock.VerifyAll();
            requestMock.VerifyAll();
            responseMock.VerifyAll();
        }