Пример #1
0
        public async void Invoke_DoesNotLogWhenDisabledAndNotHandled()
        {
            // Arrange
            var isHandled = false;

            var sink = new TestSink(
                TestSink.EnableWithTypeName<RouterMiddleware>,
                TestSink.EnableWithTypeName<RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: false);

            var httpContext = new DefaultHttpContext();
            httpContext.ApplicationServices = new ServiceProvider();
            httpContext.RequestServices = httpContext.ApplicationServices;

            RequestDelegate next = (c) =>
            {
                return Task.FromResult<object>(null);
            };

            var router = new TestRouter(isHandled);
            var middleware = new RouterMiddleware(next, loggerFactory, router);

            // Act
            await middleware.Invoke(httpContext);

            // Assert
            Assert.Single(sink.Scopes);
            var scope = sink.Scopes[0];
            Assert.Equal(typeof(RouterMiddleware).FullName, scope.LoggerName);
            Assert.Equal("RouterMiddleware.Invoke", scope.Scope);

            Assert.Empty(sink.Writes);
        }
Пример #2
0
        private async Task<Tuple<TestSink, RouteContext>> SetUp(
            bool loggerEnabled,
            string routeName,
            string template,
            string requestPath,
            TestSink testSink = null)
        {
            if (testSink == null)
            {
                testSink = new TestSink(
                    TestSink.EnableWithTypeName<TemplateRoute>,
                    TestSink.EnableWithTypeName<TemplateRoute>);
            }

            var loggerFactory = new TestLoggerFactory(testSink, loggerEnabled);

            TemplateRoute route;
            if (!string.IsNullOrEmpty(routeName))
            {
                route = CreateRoute(routeName, template);
            }
            else
            {
                route = CreateRoute(template);
            }

            var context = CreateRouteContext(requestPath, loggerFactory);

            // Act
            await route.RouteAsync(context);

            return Tuple.Create(testSink, context);
        }
Пример #3
0
        public async void SelectAsync_AmbiguousActions_LogIsCorrect()
        {
            // Arrange
            var sink = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var actions = new ActionDescriptor[]
            {
                new ActionDescriptor() { DisplayName = "A1" },
                new ActionDescriptor() { DisplayName = "A2" },
            };
            var selector = CreateSelector(actions, loggerFactory);

            var routeContext = CreateRouteContext("POST");
            var actionNames = string.Join(Environment.NewLine, actions.Select(action => action.DisplayName));
            var expectedMessage = "Request matched multiple actions resulting in " +
                $"ambiguity. Matching actions: {actionNames}";

            // Act
            await Assert.ThrowsAsync<AmbiguousActionException>(async () =>
            {
                await selector.SelectAsync(routeContext);
            });

            // Assert
            Assert.Empty(sink.Scopes);
            Assert.Single(sink.Writes);
            Assert.Equal(expectedMessage, sink.Writes[0].State?.ToString());
        }
Пример #4
0
        public async Task RouteAsync_FailOnNoAction_LogsCorrectValues()
        {
            // Arrange
            var sink = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var mockActionSelector = new Mock<IActionSelector>();
            mockActionSelector.Setup(a => a.SelectAsync(It.IsAny<RouteContext>()))
                .Returns(Task.FromResult<ActionDescriptor>(null));

            var context = CreateRouteContext(
                actionSelector: mockActionSelector.Object,
                loggerFactory: loggerFactory);

            var handler = new MvcRouteHandler();
            var expectedMessage = "No actions matched the current request.";

            // Act
            await handler.RouteAsync(context);

            // Assert
            Assert.Empty(sink.Scopes);
            Assert.Single(sink.Writes);
            Assert.Equal(expectedMessage, sink.Writes[0].State?.ToString());
        }
Пример #5
0
        public async void Invoke_DoesNotLog_WhenHandled()
        {
            // Arrange
            var isHandled = true;

            var sink = new TestSink(
                TestSink.EnableWithTypeName<RouterMiddleware>,
                TestSink.EnableWithTypeName<RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var httpContext = new DefaultHttpContext();
            httpContext.ApplicationServices = new ServiceProvider();
            httpContext.RequestServices = httpContext.ApplicationServices;

            RequestDelegate next = (c) =>
            {
                return Task.FromResult<object>(null);
            };

            var router = new TestRouter(isHandled);
            var middleware = new RouterMiddleware(next, loggerFactory, router);

            // Act
            await middleware.Invoke(httpContext);

            // Assert
            Assert.Empty(sink.Scopes);
            Assert.Empty(sink.Writes);
        }
Пример #6
0
        public async void Invoke_LogsCorrectValues_WhenNotHandled()
        {
            // Arrange
            var expectedMessage = "Request did not match any routes.";
            var isHandled = false;

            var sink = new TestSink(
                TestSink.EnableWithTypeName<RouterMiddleware>,
                TestSink.EnableWithTypeName<RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var httpContext = new DefaultHttpContext();
            httpContext.ApplicationServices = new ServiceProvider();
            httpContext.RequestServices = httpContext.ApplicationServices;

            RequestDelegate next = (c) =>
            {
                return Task.FromResult<object>(null);
            };

            var router = new TestRouter(isHandled);
            var middleware = new RouterMiddleware(next, loggerFactory, router);

            // Act
            await middleware.Invoke(httpContext);

            // Assert
            Assert.Empty(sink.Scopes);
            Assert.Single(sink.Writes);
            Assert.Equal(expectedMessage, sink.Writes[0].State?.ToString());
        }
Пример #7
0
        private async Task<Tuple<TestSink, RouteContext>> SetUp(bool enabled, string template, string requestPath)
        {
            var sink = new TestSink(
                TestSink.EnableWithTypeName<TemplateRoute>,
                TestSink.EnableWithTypeName<TemplateRoute>);
            var loggerFactory = new TestLoggerFactory(sink, enabled);

            var route = CreateRoute(template);
            var context = CreateRouteContext(requestPath, loggerFactory);

            // Act
            await route.RouteAsync(context);

            return Tuple.Create(sink, context);
        }
Пример #8
0
        public async Task RouteAsync_Success_LogsCorrectValues()
        {
            // Arrange
            var sink = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);
            var displayName = "A.B.C";
            var actionDescriptor = new Mock<ActionDescriptor>();
            actionDescriptor.SetupGet(ad => ad.DisplayName)
                            .Returns(displayName);
            var context = CreateRouteContext(actionDescriptor: actionDescriptor.Object, loggerFactory: loggerFactory);
            var handler = new MvcRouteHandler();
            var expectedMessage = $"Executing action {displayName}";

            // Act
            await handler.RouteAsync(context);

            // Assert
            Assert.Single(sink.Scopes);
            Assert.StartsWith("ActionId: ", sink.Scopes[0].Scope?.ToString());
            Assert.Single(sink.Writes);
            Assert.Equal(expectedMessage, sink.Writes[0].State?.ToString());
        }
Пример #9
0
        private static async Task<TestSink> SetUp(bool enabled, bool handled)
        {
            // Arrange
            var sink = new TestSink(
                TestSink.EnableWithTypeName<RouteCollection>,
                TestSink.EnableWithTypeName<RouteCollection>);
            var loggerFactory = new TestLoggerFactory(sink, enabled);

            var routes = new RouteCollection();
            var route = CreateRoute(accept: handled);
            routes.Add(route.Object);

            var context = CreateRouteContext("/Cool", loggerFactory);

            // Act
            await routes.RouteAsync(context);

            return sink;
        }
Пример #10
0
        public async Task ExpiredSession_LogsWarning()
        {
            var sink = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);
            using (var server = TestServer.Create(app =>
            {
                app.UseSession();
                app.Run(context =>
                {
                    int? value = context.Session.GetInt32("Key");
                    if (context.Request.Path == new PathString("/first"))
                    {
                        Assert.False(value.HasValue);
                        value = 1;
                        context.Session.SetInt32("Key", 1);
                    }
                    else if (context.Request.Path == new PathString("/second"))
                    {
                        Assert.False(value.HasValue);
                        value = 2;
                    }
                    return context.Response.WriteAsync(value.Value.ToString());
                });
            },
            services =>
            {
                services.AddInstance(typeof(ILoggerFactory), loggerFactory);
                services.AddCaching();
                services.AddSession();
                services.ConfigureSession(o => o.IdleTimeout = TimeSpan.FromMilliseconds(30));
            }))
            {
                var client = server.CreateClient();
                var response = await client.GetAsync("first");
                response.EnsureSuccessStatusCode();

                client = server.CreateClient();
                var cookie = SetCookieHeaderValue.ParseList(response.Headers.GetValues("Set-Cookie").ToList()).First();
                client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
                Thread.Sleep(50);
                Assert.Equal("2", await client.GetStringAsync("/second"));
                Assert.Equal(2, sink.Writes.Count);
                Assert.Contains("started", sink.Writes[0].State.ToString());
                Assert.Contains("expired", sink.Writes[1].State.ToString());
                Assert.Equal(LogLevel.Information, sink.Writes[0].LogLevel);
                Assert.Equal(LogLevel.Warning, sink.Writes[1].LogLevel);
            }
        }
Пример #11
0
 public async Task SessionStart_LogsInformation()
 {
     var sink = new TestSink();
     var loggerFactory = new TestLoggerFactory(sink, enabled: true);
     using (var server = TestServer.Create(app =>
     {
         app.UseSession();
         app.Run(context =>
         {
             context.Session.SetString("Key", "Value");
             return Task.FromResult(0);
         });
     },
     services =>
     {
         services.AddInstance(typeof(ILoggerFactory), loggerFactory);
         services.AddCaching();
         services.AddSession();
     }))
     {
         var client = server.CreateClient();
         var response = await client.GetAsync(string.Empty);
         response.EnsureSuccessStatusCode();
         Assert.Single(sink.Writes);
         Assert.Contains("started", sink.Writes[0].State.ToString());
         Assert.Equal(LogLevel.Information, sink.Writes[0].LogLevel);
     }
 }
Пример #12
0
        public async void Invoke_LogsCorrectValuesWhenHandled()
        {
            // Arrange
            var isHandled = true;

            var sink = new TestSink(
                TestSink.EnableWithTypeName<RouterMiddleware>,
                TestSink.EnableWithTypeName<RouterMiddleware>);
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var httpContext = new DefaultHttpContext();
            httpContext.ApplicationServices = new ServiceProvider();
            httpContext.RequestServices = httpContext.ApplicationServices;

            RequestDelegate next = (c) =>
            {
                return Task.FromResult<object>(null);
            };

            var router = new TestRouter(isHandled);

            var middleware = new RouterMiddleware(next, loggerFactory, router);

            // Act
            await middleware.Invoke(httpContext);

            // Assert
            // exists a BeginScope, verify contents
            Assert.Single(sink.Scopes);
            var scope = sink.Scopes[0];
            Assert.Equal(typeof(RouterMiddleware).FullName, scope.LoggerName);
            Assert.Equal("RouterMiddleware.Invoke", scope.Scope);

            Assert.Single(sink.Writes);

            var write = sink.Writes[0];
            Assert.Equal(typeof(RouterMiddleware).FullName, write.LoggerName);
            Assert.Equal("RouterMiddleware.Invoke", write.Scope);
            Assert.Equal(typeof(RouterMiddlewareInvokeValues), write.State.GetType());
            var values = (RouterMiddlewareInvokeValues)write.State;
            Assert.Equal("RouterMiddleware.Invoke", values.Name);
            Assert.Equal(true, values.Handled);
        }