public void FindView_WritesDiagnostic_ViewFound()
        {
            // Arrange
            var diagnosticSource = new DiagnosticListener("Test");
            var listener = new TestDiagnosticListener();
            diagnosticSource.SubscribeWithAdapter(listener);

            var context = GetActionContext();
            var executor = GetViewExecutor(diagnosticSource);

            var viewName = "myview";
            var viewResult = new PartialViewResult
            {
                ViewName = viewName,
                ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
                TempData = Mock.Of<ITempDataDictionary>(),
            };

            // Act
            var viewEngineResult = executor.FindView(context, viewResult);

            // Assert
            Assert.Equal(viewName, viewEngineResult.ViewName);

            Assert.NotNull(listener.ViewFound);
            Assert.NotNull(listener.ViewFound.ActionContext);
            Assert.NotNull(listener.ViewFound.Result);
            Assert.NotNull(listener.ViewFound.View);
            Assert.True(listener.ViewFound.IsPartial);
            Assert.Equal("myview", listener.ViewFound.ViewName);
        }
示例#2
0
        public async Task ExecuteAsync_WritesDiagnostic()
        {
            // Arrange
            var view = CreateView(async(v) =>
            {
                await v.Writer.WriteAsync("abcd");
            });

            var context      = new DefaultHttpContext();
            var memoryStream = new MemoryStream();

            context.Response.Body = memoryStream;

            var actionContext = new ActionContext(
                context,
                new RouteData(),
                new ActionDescriptor());
            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());

            var adapter = new TestDiagnosticListener();

            var diagnosticSource = new DiagnosticListener("Test");

            diagnosticSource.SubscribeWithAdapter(adapter);

            var viewExecutor = CreateViewExecutor(diagnosticSource);

            // Act
            await viewExecutor.ExecuteAsync(
                actionContext,
                view,
                viewData,
                Mock.Of <ITempDataDictionary>(),
                contentType : null,
                statusCode : null);

            // Assert
            Assert.Equal("abcd", Encoding.UTF8.GetString(memoryStream.ToArray()));

            Assert.NotNull(adapter.BeforeView?.View);
            Assert.NotNull(adapter.BeforeView?.ViewContext);
            Assert.NotNull(adapter.AfterView?.View);
            Assert.NotNull(adapter.AfterView?.ViewContext);
        }
示例#3
0
    public void Execute_ResolvesView_AndWritesDiagnosticListener()
    {
        // Arrange
        var view = new Mock <IView>(MockBehavior.Strict);

        view.Setup(v => v.RenderAsync(It.IsAny <ViewContext>()))
        .Returns(Task.FromResult(result: true))
        .Verifiable();

        var viewEngine = new Mock <IViewEngine>(MockBehavior.Strict);

        viewEngine
        .Setup(v => v.FindView(It.IsAny <ActionContext>(), "Components/Invoke/Default", /*isMainPage*/ false))
        .Returns(ViewEngineResult.Found("Components/Invoke/Default", view.Object))
        .Verifiable();

        var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());

        var result = new ViewViewComponentResult
        {
            ViewEngine = viewEngine.Object,
            ViewData   = viewData,
            TempData   = _tempDataDictionary,
        };

        var adapter = new TestDiagnosticListener();

        var viewComponentContext = GetViewComponentContext(view.Object, viewData, adapter);

        // Act
        result.Execute(viewComponentContext);

        // Assert
        viewEngine.Verify();
        view.Verify();

        Assert.NotNull(adapter.ViewComponentBeforeViewExecute?.ActionDescriptor);
        Assert.NotNull(adapter.ViewComponentBeforeViewExecute?.ViewComponentContext);
        Assert.NotNull(adapter.ViewComponentBeforeViewExecute?.View);
        Assert.NotNull(adapter.ViewComponentAfterViewExecute?.ActionDescriptor);
        Assert.NotNull(adapter.ViewComponentAfterViewExecute?.ViewComponentContext);
        Assert.NotNull(adapter.ViewComponentAfterViewExecute?.View);
    }
示例#4
0
    public async Task ExceptionWrittenToDiagnostics()
    {
        DiagnosticListener diagnosticListener = null;

        using var host = new HostBuilder()
                         .ConfigureWebHost(webHostBuilder =>
        {
            webHostBuilder
            .UseTestServer()
            .Configure(app =>
            {
                diagnosticListener = app.ApplicationServices.GetRequiredService <DiagnosticListener>();

                app.UseDeveloperExceptionPage();
                app.Run(context =>
                {
                    throw new Exception("Test exception");
                });
            })
            .ConfigureServices(services => services.AddMiddlewareAnalysis());
        }).Build();

        await host.StartAsync();

        var server = host.GetTestServer();

        var listener = new TestDiagnosticListener();

        diagnosticListener.SubscribeWithAdapter(listener);

        await server.CreateClient().GetAsync(string.Empty);

        // "Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware",
        // "Microsoft.AspNetCore.MiddlewareAnalysis.MiddlewareAnalysisTests.+<>c"
        Assert.Equal(2, listener.MiddlewareStarting.Count);
        Assert.Equal("Microsoft.AspNetCore.MiddlewareAnalysis.MiddlewareAnalysisTests+<>c", listener.MiddlewareStarting[1]);
        // reversed "RunInlineMiddleware"
        Assert.Equal(1, listener.MiddlewareException.Count);
        Assert.Equal("Microsoft.AspNetCore.MiddlewareAnalysis.MiddlewareAnalysisTests+<>c", listener.MiddlewareException[0]);
        // reversed "Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware"
        Assert.Equal(1, listener.MiddlewareFinished.Count);
        Assert.Equal("Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware", listener.MiddlewareFinished[0]);
    }
示例#5
0
        public void FindView_WritesDiagnostic_ViewNotFound()
        {
            // Arrange
            var diagnosticSource = new DiagnosticListener("Test");
            var listener         = new TestDiagnosticListener();

            diagnosticSource.SubscribeWithAdapter(listener);

            var context  = GetActionContext();
            var executor = GetViewExecutor(diagnosticSource);

            var viewName   = "myview";
            var viewEngine = new Mock <IViewEngine>(MockBehavior.Strict);

            viewEngine
            .Setup(e => e.GetView(/*executingFilePath*/ null, "myview", /*isMainPage*/ false))
            .Returns(ViewEngineResult.NotFound("myview", Enumerable.Empty <string>()))
            .Verifiable();
            viewEngine
            .Setup(e => e.FindView(context, "myview", /*isMainPage*/ false))
            .Returns(ViewEngineResult.NotFound("myview", new string[] { "location/myview" }));

            var viewResult = new PartialViewResult
            {
                ViewName   = viewName,
                ViewEngine = viewEngine.Object,
                ViewData   = new ViewDataDictionary(new EmptyModelMetadataProvider()),
                TempData   = Mock.Of <ITempDataDictionary>(),
            };

            // Act
            var viewEngineResult = executor.FindView(context, viewResult);

            // Assert
            Assert.False(viewEngineResult.Success);

            Assert.NotNull(listener.ViewNotFound);
            Assert.NotNull(listener.ViewNotFound.ActionContext);
            Assert.NotNull(listener.ViewNotFound.Result);
            Assert.Equal(new string[] { "location/myview" }, listener.ViewNotFound.SearchedLocations);
            Assert.Equal("myview", listener.ViewNotFound.ViewName);
        }
示例#6
0
        public async Task BeginEndDiagnosticAvailable()
        {
            DiagnosticListener diagnosticListener = null;
            var server = TestServer.Create(app =>
            {
                diagnosticListener = app.ApplicationServices.GetRequiredService <DiagnosticListener>();
                app.Run(context =>
                {
                    return(context.Response.WriteAsync("Hello World"));
                });
            });
            var listener = new TestDiagnosticListener();

            diagnosticListener.SubscribeWithAdapter(listener);
            var result = await server.CreateClient().GetStringAsync("/path");

            Assert.Equal("Hello World", result);
            Assert.NotNull(listener.BeginRequest?.HttpContext);
            Assert.NotNull(listener.EndRequest?.HttpContext);
            Assert.Null(listener.UnhandledException);
        }
示例#7
0
        public async Task ExceptionDiagnosticAvailable()
        {
            DiagnosticListener diagnosticListener = null;
            var server = TestServer.Create(app =>
            {
                diagnosticListener = app.ApplicationServices.GetRequiredService <DiagnosticListener>();
                app.Run(context =>
                {
                    throw new Exception("Test exception");
                });
            });
            var listener = new TestDiagnosticListener();

            diagnosticListener.SubscribeWithAdapter(listener);
            await Assert.ThrowsAsync <Exception>(() => server.CreateClient().GetAsync("/path"));

            Assert.NotNull(listener.BeginRequest?.HttpContext);
            Assert.Null(listener.EndRequest?.HttpContext);
            Assert.NotNull(listener.UnhandledException?.HttpContext);
            Assert.NotNull(listener.UnhandledException?.Exception);
        }
示例#8
0
    public async Task ExecuteResultAsync_ExecutesViewComponent_AndWritesDiagnosticListener()
    {
        // Arrange
        var methodInfo = typeof(TextViewComponent).GetMethod(nameof(TextViewComponent.Invoke));
        var descriptor = new ViewComponentDescriptor()
        {
            FullName   = "Full.Name.Text",
            ShortName  = "Text",
            TypeInfo   = typeof(TextViewComponent).GetTypeInfo(),
            MethodInfo = methodInfo,
            Parameters = methodInfo.GetParameters(),
        };

        var adapter = new TestDiagnosticListener();

        var actionContext = CreateActionContext(adapter, descriptor);

        var viewComponentResult = new ViewComponentResult()
        {
            Arguments         = new { name = "World!" },
            ViewComponentName = "Text",
            TempData          = _tempDataDictionary,
        };

        // Act
        await viewComponentResult.ExecuteResultAsync(actionContext);

        // Assert
        var body = ReadBody(actionContext.HttpContext.Response);

        Assert.Equal("Hello, World!", body);

        Assert.NotNull(adapter.BeforeViewComponent?.ActionDescriptor);
        Assert.NotNull(adapter.BeforeViewComponent?.ViewComponentContext);
        Assert.NotNull(adapter.BeforeViewComponent?.ViewComponent);
        Assert.NotNull(adapter.AfterViewComponent?.ActionDescriptor);
        Assert.NotNull(adapter.AfterViewComponent?.ViewComponentContext);
        Assert.NotNull(adapter.AfterViewComponent?.ViewComponentResult);
        Assert.NotNull(adapter.AfterViewComponent?.ViewComponent);
    }
        public async Task ResolverEvents()
        {
            // arrange
            var listener = new TestDiagnosticListener();

            using (DiagnosticListener.AllListeners.Subscribe(
                       new DiagnosticObserver(listener)))
            {
                ISchema schema = CreateSchema();

                // act
                await schema.ExecuteAsync("{ foo }");

                // assert
                Assert.True(listener.ResolveFieldStart);
                Assert.True(listener.ResolveFieldStop);
                Assert.Equal("foo", listener.FieldSelection.Name.Value);
                Assert.InRange(listener.Duration,
                               TimeSpan.FromMilliseconds(50),
                               TimeSpan.FromMilliseconds(2000));
            }
        }
示例#10
0
    public async Task NullInfoInCompilationException_ShouldNotThrowExceptionGeneratingExceptionPage(
        List <CompilationFailure> failures)
    {
        // Arrange
        DiagnosticListener diagnosticListener = null;

        using var host = new HostBuilder()
                         .ConfigureWebHost(webHostBuilder =>
        {
            webHostBuilder
            .UseTestServer()
            .Configure(app =>
            {
                diagnosticListener = app.ApplicationServices.GetRequiredService <DiagnosticListener>();
                app.UseDeveloperExceptionPage();
                app.Run(context =>
                {
                    throw new CustomCompilationException(failures);
                });
            });
        }).Build();

        await host.StartAsync();

        var server   = host.GetTestServer();
        var listener = new TestDiagnosticListener();

        diagnosticListener.SubscribeWithAdapter(listener);

        // Act
        await server.CreateClient().GetAsync("/path");

        // Assert
        Assert.NotNull(listener.DiagnosticUnhandledException?.HttpContext);
        Assert.NotNull(listener.DiagnosticUnhandledException?.Exception);
        Assert.Null(listener.DiagnosticHandledException?.HttpContext);
        Assert.Null(listener.DiagnosticHandledException?.Exception);
    }
示例#11
0
    public async Task UnhandledErrorsWriteToDiagnosticWhenUsingExceptionPage()
    {
        // Arrange
        DiagnosticListener diagnosticListener = null;

        using var host = new HostBuilder()
                         .ConfigureWebHost(webHostBuilder =>
        {
            webHostBuilder
            .UseTestServer()
            .Configure(app =>
            {
                diagnosticListener = app.ApplicationServices.GetRequiredService <DiagnosticListener>();
                app.UseDeveloperExceptionPage();
                app.Run(context =>
                {
                    throw new Exception("Test exception");
                });
            });
        }).Build();

        await host.StartAsync();

        var server   = host.GetTestServer();
        var listener = new TestDiagnosticListener();

        diagnosticListener.SubscribeWithAdapter(listener);

        // Act
        await server.CreateClient().GetAsync("/path");

        // Assert
        Assert.NotNull(listener.DiagnosticUnhandledException?.HttpContext);
        Assert.NotNull(listener.DiagnosticUnhandledException?.Exception);
        Assert.Null(listener.DiagnosticHandledException?.HttpContext);
        Assert.Null(listener.DiagnosticHandledException?.Exception);
    }
示例#12
0
        public void Configure(
            IApplicationBuilder app,
            IWebHostEnvironment env,
            ILoggerFactory loggerFactory,
            DiagnosticListener diagnosticListener)
        {
            // Listen for middleware events and log them to the console.
            var listener = new TestDiagnosticListener("/", loggerFactory);

            diagnosticListener.SubscribeWithAdapter(listener);

            app.UseProxySupportIfNecessary(ProxyConfiguration);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapApplicationHealthChecks();
            });
        }
示例#13
0
        public void Intercept(IInvocation invocation)
        {
            var methodName = invocation.Method.Name;

            if (methodName.EndsWith("Async"))
            {
                Type declaringType       = invocation.Method.DeclaringType;
                var  ns                  = declaringType.Namespace;
                var  expectedEventPrefix = declaringType.FullName + "." + methodName.Substring(0, methodName.Length - 5);
                var  expectedEvents      = new List <string>
                {
                    expectedEventPrefix + ".Start"
                };

                using TestDiagnosticListener diagnosticListener = new TestDiagnosticListener(s => s.Name.StartsWith("Azure."));
                invocation.Proceed();

                bool strict = !invocation.Method.GetCustomAttributes(true).Any(a => a.GetType().FullName == "Azure.Core.ForwardsClientCallsAttribute");
                if (invocation.Method.ReturnType.Name.Contains("Pageable") ||
                    invocation.Method.ReturnType.Name.Contains("IAsyncEnumerable"))
                {
                    return;
                }

                try
                {
                    object returnValue = invocation.ReturnValue;
                    if (returnValue is Task t)
                    {
                        t.GetAwaiter().GetResult();
                    }
                    else
                    {
                        // Await ValueTask
                        Type       returnType       = returnValue.GetType();
                        MethodInfo getAwaiterMethod = returnType.GetMethod("GetAwaiter", BindingFlags.Instance | BindingFlags.Public);
                        MethodInfo getResultMethod  = getAwaiterMethod.ReturnType.GetMethod("GetResult", BindingFlags.Instance | BindingFlags.Public);

                        getResultMethod.Invoke(
                            getAwaiterMethod.Invoke(returnValue, Array.Empty <object>()),
                            Array.Empty <object>());
                    }

                    expectedEvents.Add(expectedEventPrefix + ".Stop");
                }
                catch (Exception ex)
                {
                    expectedEvents.Add(expectedEventPrefix + ".Exception");

                    if (ex is ArgumentException)
                    {
                        // Don't expect scope for argument validation failures
                        expectedEvents.Clear();
                    }
                }
                finally
                {
                    // Remove subscribers before enumerating events.
                    diagnosticListener.Dispose();

                    if (strict)
                    {
                        foreach (var expectedEvent in expectedEvents)
                        {
                            (string Key, object Value, DiagnosticListener Listener)e = diagnosticListener.Events.FirstOrDefault(e => e.Key == expectedEvent);

                            if (e == default)
                            {
                                throw new InvalidOperationException($"Expected diagnostic event not fired {expectedEvent} {Environment.NewLine}    fired events {string.Join(", ", diagnosticListener.Events)} {Environment.NewLine}    You may have forgotten to set your operationId to {expectedEvent} in {methodName} or applied the Azure.Core.ForwardsClientCallsAttribute to {methodName}.");
                            }

                            if (!ns.StartsWith(e.Listener.Name))
                            {
                                throw new InvalidOperationException($"{e.Key} event was written into wrong DiagnosticSource {e.Listener.Name}, expected: {ns}");
                            }
                        }
                    }
                    else
                    {
                        if (!diagnosticListener.Events.Any())
                        {
                            throw new InvalidOperationException($"Expected some diagnostic event to fire found none");
                        }
                    }
                }
            }
            else
            {
                invocation.Proceed();
            }
        }
示例#14
0
        public async Task RouteHandler_WritesDiagnostic_ActionInvoked()
        {
            // Arrange
            var listener = new TestDiagnosticListener();

            var context = CreateRouteContext(diagnosticListener: listener);

            var handler = new MvcRouteHandler();
            await handler.RouteAsync(context);

            // Act
            await context.Handler(context.HttpContext);

            // Assert
            Assert.NotNull(listener.AfterAction?.ActionDescriptor);
            Assert.NotNull(listener.AfterAction?.HttpContext);
        }
示例#15
0
        public async Task RouteHandler_WritesDiagnostic_ActionSelected()
        {
            // Arrange
            var listener = new TestDiagnosticListener();

            var context = CreateRouteContext(diagnosticListener: listener);
            context.RouteData.Values.Add("tag", "value");

            var handler = new MvcRouteHandler();
            await handler.RouteAsync(context);

            // Act
            await context.Handler(context.HttpContext);

            // Assert
            Assert.NotNull(listener.BeforeAction?.ActionDescriptor);
            Assert.NotNull(listener.BeforeAction?.HttpContext);

            var routeValues = listener.BeforeAction?.RouteData?.Values;
            Assert.NotNull(routeValues);

            Assert.Equal(1, routeValues.Count);
            Assert.Contains(routeValues, kvp => kvp.Key == "tag" && string.Equals(kvp.Value, "value"));
        }
示例#16
0
        public async Task ExceptionDiagnosticAvailable()
        {
            DiagnosticListener diagnosticListener = null;
            var server = TestServer.Create(app =>
            {
                diagnosticListener = app.ApplicationServices.GetRequiredService<DiagnosticListener>();
                app.Run(context =>
                {
                    throw new Exception("Test exception");
                });
            });
            var listener = new TestDiagnosticListener();
            diagnosticListener.SubscribeWithAdapter(listener);
            await Assert.ThrowsAsync<Exception>(() => server.CreateClient().GetAsync("/path"));

            Assert.NotNull(listener.BeginRequest?.HttpContext);
            Assert.Null(listener.EndRequest?.HttpContext);
            Assert.NotNull(listener.UnhandledException?.HttpContext);
            Assert.NotNull(listener.UnhandledException?.Exception);
        }
示例#17
0
        public async Task BeginEndDiagnosticAvailable()
        {
            DiagnosticListener diagnosticListener = null;
            var server = TestServer.Create(app =>
            {
                diagnosticListener = app.ApplicationServices.GetRequiredService<DiagnosticListener>();
                app.Run(context =>
                {
                    return context.Response.WriteAsync("Hello World");
                });
            });
            var listener = new TestDiagnosticListener();
            diagnosticListener.SubscribeWithAdapter(listener);
            var result = await server.CreateClient().GetStringAsync("/path");

            Assert.Equal("Hello World", result);
            Assert.NotNull(listener.BeginRequest?.HttpContext);
            Assert.NotNull(listener.EndRequest?.HttpContext);
            Assert.Null(listener.UnhandledException);
        }
示例#18
0
        public async Task ExecuteAsync_WritesDiagnostic()
        {
            // Arrange
            var view = CreateView(async (v) =>
            {
                await v.Writer.WriteAsync("abcd");
            });

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

            var actionContext = new ActionContext(
                context,
                new RouteData(),
                new ActionDescriptor());
            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());

            var adapter = new TestDiagnosticListener();

            var diagnosticSource = new DiagnosticListener("Test");
            diagnosticSource.SubscribeWithAdapter(adapter);

            var viewExecutor = CreateViewExecutor(diagnosticSource);

            // Act
            await viewExecutor.ExecuteAsync(
                actionContext,
                view,
                viewData,
                Mock.Of<ITempDataDictionary>(),
                contentType: null,
                statusCode: null);

            // Assert
            Assert.Equal("abcd", Encoding.UTF8.GetString(memoryStream.ToArray()));

            Assert.NotNull(adapter.BeforeView?.View);
            Assert.NotNull(adapter.BeforeView?.ViewContext);
            Assert.NotNull(adapter.AfterView?.View);
            Assert.NotNull(adapter.AfterView?.ViewContext);
        }
        public void FindView_WritesDiagnostic_ViewNotFound()
        {
            // Arrange
            var diagnosticSource = new DiagnosticListener("Test");
            var listener = new TestDiagnosticListener();
            diagnosticSource.SubscribeWithAdapter(listener);

            var context = GetActionContext();
            var executor = GetViewExecutor(diagnosticSource);

            var viewName = "myview";
            var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);
            viewEngine
                .Setup(e => e.FindPartialView(context, "myview"))
                .Returns(ViewEngineResult.NotFound("myview", new string[] { "location/myview" }));

            var viewResult = new PartialViewResult
            {
                ViewName = viewName,
                ViewEngine = viewEngine.Object,
                ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
                TempData = Mock.Of<ITempDataDictionary>(),
            };

            // Act
            var viewEngineResult = executor.FindView(context, viewResult);

            // Assert
            Assert.False(viewEngineResult.Success);

            Assert.NotNull(listener.ViewNotFound);
            Assert.NotNull(listener.ViewNotFound.ActionContext);
            Assert.NotNull(listener.ViewNotFound.Result);
            Assert.Equal(new string[] { "location/myview" }, listener.ViewNotFound.SearchedLocations);
            Assert.Equal("myview", listener.ViewNotFound.ViewName);
        }
        public void Intercept(IInvocation invocation)
        {
            var methodName = invocation.Method.Name;

            if (methodName.EndsWith("Async"))
            {
                var expectedEventPrefix = invocation.Method.DeclaringType.FullName + "." + methodName.Substring(0, methodName.Length - 5);
                var expectedEvents      = new List <string>();
                expectedEvents.Add(expectedEventPrefix + ".Start");

                TestDiagnosticListener diagnosticListener = new TestDiagnosticListener("Azure.Clients");
                invocation.Proceed();

                bool strict = !invocation.Method.GetCustomAttributes(true).Any(a => a.GetType().FullName == "Azure.Core.ConvenienceMethodAttribute");
                if (invocation.Method.ReturnType.Name.Contains("AsyncCollection") ||
                    invocation.Method.ReturnType.Name.Contains("IAsyncEnumerable"))
                {
                    return;
                }

                var result = (Task)invocation.ReturnValue;
                try
                {
                    result.GetAwaiter().GetResult();
                    expectedEvents.Add(expectedEventPrefix + ".Stop");
                }
                catch (Exception ex)
                {
                    expectedEvents.Add(expectedEventPrefix + ".Exception");

                    if (ex is ArgumentException)
                    {
                        // Don't expect scope for argument validation failures
                        expectedEvents.Clear();
                    }
                }
                finally
                {
                    diagnosticListener.Dispose();
                    if (strict)
                    {
                        foreach (var expectedEvent in expectedEvents)
                        {
                            if (!diagnosticListener.Events.Any(e => e.Key == expectedEvent))
                            {
                                throw new InvalidOperationException($"Expected diagnostic event not fired {expectedEvent} {Environment.NewLine}    fired events {string.Join(", ", diagnosticListener.Events)}");
                            }
                        }
                    }
                    else
                    {
                        if (!diagnosticListener.Events.Any())
                        {
                            throw new InvalidOperationException($"Expected some diagnostic event to fire found none");
                        }
                    }
                }
            }
            else
            {
                invocation.Proceed();
            }
        }
        private Activity[] AssertSendActivities(bool useSessions, ServiceBusSender sender, IEnumerable <ServiceBusMessage> msgs, TestDiagnosticListener listener)
        {
            IList <Activity> messageActivities = new List <Activity>();

            foreach (var msg in msgs)
            {
                Assert.IsNotNull(msg.Properties[DiagnosticProperty.DiagnosticIdAttribute]);
                (string Key, object Value, DiagnosticListener)startMessage = listener.Events.Dequeue();
                messageActivities.Add((Activity)startMessage.Value);
                AssertCommonTags((Activity)startMessage.Value, sender.EntityPath, sender.FullyQualifiedNamespace);
                Assert.AreEqual(DiagnosticProperty.MessageActivityName + ".Start", startMessage.Key);

                (string Key, object Value, DiagnosticListener)stopMessage = listener.Events.Dequeue();
                Assert.AreEqual(DiagnosticProperty.MessageActivityName + ".Stop", stopMessage.Key);
            }

            (string Key, object Value, DiagnosticListener)startSend = listener.Events.Dequeue();
            Assert.AreEqual(DiagnosticProperty.SendActivityName + ".Start", startSend.Key);
            Activity sendActivity = (Activity)startSend.Value;

            AssertCommonTags(sendActivity, sender.EntityPath, sender.FullyQualifiedNamespace);
            CollectionAssert.Contains(
                sendActivity.Tags,
                new KeyValuePair <string, string>(
                    DiagnosticProperty.MessageIdAttribute,
                    string.Join(",", msgs.Select(m => m.MessageId).ToArray())));
            if (useSessions)
            {
                CollectionAssert.Contains(
                    sendActivity.Tags,
                    new KeyValuePair <string, string>(
                        DiagnosticProperty.SessionIdAttribute,
                        string.Join(",", msgs.Select(m => m.SessionId).Distinct().ToArray())));
            }

            (string Key, object Value, DiagnosticListener)stopSend = listener.Events.Dequeue();
            Assert.AreEqual(DiagnosticProperty.SendActivityName + ".Stop", stopSend.Key);

            var sendLinkedActivities = ((IEnumerable <Activity>)startSend.Value.GetType().GetProperty("Links").GetValue(startSend.Value)).ToArray();

            for (int i = 0; i < sendLinkedActivities.Length; i++)
            {
                Assert.AreEqual(messageActivities[i].Id, sendLinkedActivities[i].ParentId);
            }
            return(sendLinkedActivities);
        }
        public async Task SenderReceiverActivities(bool useSessions)
        {
            await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: useSessions))
            {
                using var listener = new TestDiagnosticListener(EntityScopeFactory.DiagnosticNamespace);
                var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
                ServiceBusSender sender    = client.CreateSender(scope.QueueName);
                string           sessionId = null;
                if (useSessions)
                {
                    sessionId = "sessionId";
                }
                int numMessages = 5;
                var msgs        = GetMessages(numMessages, sessionId);
                await sender.SendMessagesAsync(msgs);

                Activity[] sendActivities = AssertSendActivities(useSessions, sender, msgs, listener);

                ServiceBusReceiver receiver = null;
                if (useSessions)
                {
                    receiver = await client.CreateSessionReceiverAsync(scope.QueueName);
                }
                else
                {
                    receiver = client.CreateReceiver(scope.QueueName);
                }

                var remaining = numMessages;
                List <ServiceBusReceivedMessage> receivedMsgs = new List <ServiceBusReceivedMessage>();
                while (remaining > 0)
                {
                    // loop in case we don't receive all messages in one attempt
                    var received = await receiver.ReceiveMessagesAsync(remaining);

                    receivedMsgs.AddRange(received);
                    (string Key, object Value, DiagnosticListener)receiveStart = listener.Events.Dequeue();
                    Assert.AreEqual(DiagnosticProperty.ReceiveActivityName + ".Start", receiveStart.Key);

                    Activity receiveActivity = (Activity)receiveStart.Value;
                    AssertCommonTags(receiveActivity, receiver.EntityPath, receiver.FullyQualifiedNamespace);
                    CollectionAssert.Contains(
                        receiveActivity.Tags,
                        new KeyValuePair <string, string>(
                            DiagnosticProperty.RequestedMessageCountAttribute,
                            remaining.ToString()));
                    CollectionAssert.Contains(
                        receiveActivity.Tags,
                        new KeyValuePair <string, string>(
                            DiagnosticProperty.MessageIdAttribute,
                            string.Join(",", received.Select(m => m.MessageId).ToArray())));
                    remaining -= received.Count;

                    if (useSessions)
                    {
                        CollectionAssert.Contains(
                            receiveActivity.Tags,
                            new KeyValuePair <string, string>(
                                DiagnosticProperty.SessionIdAttribute,
                                string.Join(",", msgs.Select(m => m.SessionId).Distinct().ToArray())));
                    }
                    var receiveLinkedActivities = ((IEnumerable <Activity>)receiveActivity.GetType().GetProperty("Links").GetValue(receiveActivity)).ToArray();
                    for (int i = 0; i < receiveLinkedActivities.Length; i++)
                    {
                        Assert.AreEqual(sendActivities[i].ParentId, receiveLinkedActivities[i].ParentId);
                    }
                    (string Key, object Value, DiagnosticListener)receiveStop = listener.Events.Dequeue();

                    Assert.AreEqual(DiagnosticProperty.ReceiveActivityName + ".Stop", receiveStop.Key);
                }

                var msgIndex = 0;

                var completed = receivedMsgs[msgIndex];
                await receiver.CompleteMessageAsync(completed);

                (string Key, object Value, DiagnosticListener)completeStart = listener.Events.Dequeue();
                Assert.AreEqual(DiagnosticProperty.CompleteActivityName + ".Start", completeStart.Key);
                Activity completeActivity = (Activity)completeStart.Value;
                AssertCommonTags(completeActivity, receiver.EntityPath, receiver.FullyQualifiedNamespace);
                AssertLockTokensTag(completeActivity, completed.LockToken);
                (string Key, object Value, DiagnosticListener)completeStop = listener.Events.Dequeue();
                Assert.AreEqual(DiagnosticProperty.CompleteActivityName + ".Stop", completeStop.Key);

                var deferred = receivedMsgs[++msgIndex];
                await receiver.DeferMessageAsync(deferred);

                (string Key, object Value, DiagnosticListener)deferStart = listener.Events.Dequeue();
                Assert.AreEqual(DiagnosticProperty.DeferActivityName + ".Start", deferStart.Key);
                Activity deferActivity = (Activity)deferStart.Value;
                AssertCommonTags(deferActivity, receiver.EntityPath, receiver.FullyQualifiedNamespace);
                AssertLockTokensTag(deferActivity, deferred.LockToken);
                (string Key, object Value, DiagnosticListener)deferStop = listener.Events.Dequeue();
                Assert.AreEqual(DiagnosticProperty.DeferActivityName + ".Stop", deferStop.Key);

                var deadLettered = receivedMsgs[++msgIndex];
                await receiver.DeadLetterMessageAsync(deadLettered);

                (string Key, object Value, DiagnosticListener)deadLetterStart = listener.Events.Dequeue();
                Assert.AreEqual(DiagnosticProperty.DeadLetterActivityName + ".Start", deadLetterStart.Key);
                Activity deadLetterActivity = (Activity)deadLetterStart.Value;
                AssertCommonTags(deadLetterActivity, receiver.EntityPath, receiver.FullyQualifiedNamespace);
                AssertLockTokensTag(deadLetterActivity, deadLettered.LockToken);
                (string Key, object Value, DiagnosticListener)deadletterStop = listener.Events.Dequeue();
                Assert.AreEqual(DiagnosticProperty.DeadLetterActivityName + ".Stop", deadletterStop.Key);

                var abandoned = receivedMsgs[++msgIndex];
                await receiver.AbandonMessageAsync(abandoned);

                (string Key, object Value, DiagnosticListener)abandonStart = listener.Events.Dequeue();
                Assert.AreEqual(DiagnosticProperty.AbandonActivityName + ".Start", abandonStart.Key);
                Activity abandonActivity = (Activity)abandonStart.Value;
                AssertCommonTags(abandonActivity, receiver.EntityPath, receiver.FullyQualifiedNamespace);
                AssertLockTokensTag(abandonActivity, abandoned.LockToken);
                (string Key, object Value, DiagnosticListener)abandonStop = listener.Events.Dequeue();
                Assert.AreEqual(DiagnosticProperty.AbandonActivityName + ".Stop", abandonStop.Key);

                var receiveDeferMsg = await receiver.ReceiveDeferredMessageAsync(deferred.SequenceNumber);

                (string Key, object Value, DiagnosticListener)receiveDeferStart = listener.Events.Dequeue();
                Assert.AreEqual(DiagnosticProperty.ReceiveDeferredActivityName + ".Start", receiveDeferStart.Key);
                Activity receiveDeferActivity = (Activity)receiveDeferStart.Value;
                AssertCommonTags(receiveDeferActivity, receiver.EntityPath, receiver.FullyQualifiedNamespace);
                CollectionAssert.Contains(
                    receiveDeferActivity.Tags,
                    new KeyValuePair <string, string>(
                        DiagnosticProperty.MessageIdAttribute,
                        deferred.MessageId));
                CollectionAssert.Contains(
                    receiveDeferActivity.Tags,
                    new KeyValuePair <string, string>(
                        DiagnosticProperty.SequenceNumbersAttribute,
                        deferred.SequenceNumber.ToString()));
                (string Key, object Value, DiagnosticListener)receiveDeferStop = listener.Events.Dequeue();
                Assert.AreEqual(DiagnosticProperty.ReceiveDeferredActivityName + ".Stop", receiveDeferStop.Key);

                // renew lock
                if (useSessions)
                {
                    var sessionReceiver = (ServiceBusSessionReceiver)receiver;
                    await sessionReceiver.RenewSessionLockAsync();

                    (string Key, object Value, DiagnosticListener)renewStart = listener.Events.Dequeue();
                    Assert.AreEqual(DiagnosticProperty.RenewSessionLockActivityName + ".Start", renewStart.Key);
                    Activity renewActivity = (Activity)renewStart.Value;
                    AssertCommonTags(renewActivity, receiver.EntityPath, receiver.FullyQualifiedNamespace);
                    CollectionAssert.Contains(
                        renewActivity.Tags,
                        new KeyValuePair <string, string>(
                            DiagnosticProperty.SessionIdAttribute,
                            "sessionId"));

                    (string Key, object Value, DiagnosticListener)renewStop = listener.Events.Dequeue();
                    Assert.AreEqual(DiagnosticProperty.RenewSessionLockActivityName + ".Stop", renewStop.Key);

                    // set state
                    var state = Encoding.UTF8.GetBytes("state");
                    await sessionReceiver.SetSessionStateAsync(state);

                    (string Key, object Value, DiagnosticListener)setStateStart = listener.Events.Dequeue();
                    Assert.AreEqual(DiagnosticProperty.SetSessionStateActivityName + ".Start", setStateStart.Key);
                    Activity setStateActivity = (Activity)setStateStart.Value;
                    AssertCommonTags(setStateActivity, sessionReceiver.EntityPath, sessionReceiver.FullyQualifiedNamespace);
                    CollectionAssert.Contains(
                        setStateActivity.Tags,
                        new KeyValuePair <string, string>(
                            DiagnosticProperty.SessionIdAttribute,
                            "sessionId"));

                    (string Key, object Value, DiagnosticListener)setStateStop = listener.Events.Dequeue();
                    Assert.AreEqual(DiagnosticProperty.SetSessionStateActivityName + ".Stop", setStateStop.Key);

                    // get state
                    var getState = await sessionReceiver.GetSessionStateAsync();

                    Assert.AreEqual(state, getState);
                    (string Key, object Value, DiagnosticListener)getStateStart = listener.Events.Dequeue();
                    Assert.AreEqual(DiagnosticProperty.GetSessionStateActivityName + ".Start", getStateStart.Key);
                    Activity getStateActivity = (Activity)getStateStart.Value;
                    AssertCommonTags(getStateActivity, sessionReceiver.EntityPath, sessionReceiver.FullyQualifiedNamespace);
                    CollectionAssert.Contains(
                        getStateActivity.Tags,
                        new KeyValuePair <string, string>(
                            DiagnosticProperty.SessionIdAttribute,
                            "sessionId"));

                    (string Key, object Value, DiagnosticListener)getStateStop = listener.Events.Dequeue();
                    Assert.AreEqual(DiagnosticProperty.GetSessionStateActivityName + ".Stop", getStateStop.Key);
                }
                else
                {
                    await receiver.RenewMessageLockAsync(receivedMsgs[4]);

                    (string Key, object Value, DiagnosticListener)renewStart = listener.Events.Dequeue();
                    Assert.AreEqual(DiagnosticProperty.RenewMessageLockActivityName + ".Start", renewStart.Key);
                    Activity renewActivity = (Activity)renewStart.Value;
                    AssertCommonTags(renewActivity, receiver.EntityPath, receiver.FullyQualifiedNamespace);
                    AssertLockTokensTag(renewActivity, receivedMsgs[4].LockToken);
                    CollectionAssert.Contains(
                        renewActivity.Tags,
                        new KeyValuePair <string, string>(
                            DiagnosticProperty.LockedUntilAttribute,
                            receivedMsgs[4].LockedUntil.ToString()));

                    (string Key, object Value, DiagnosticListener)renewStop = listener.Events.Dequeue();
                    Assert.AreEqual(DiagnosticProperty.RenewMessageLockActivityName + ".Stop", renewStop.Key);
                }

                // schedule
                msgs = GetMessages(numMessages, sessionId);

                foreach (var msg in msgs)
                {
                    var seq = await sender.ScheduleMessageAsync(msg, DateTimeOffset.UtcNow.AddMinutes(1));

                    Assert.IsNotNull(msg.Properties[DiagnosticProperty.DiagnosticIdAttribute]);

                    (string Key, object Value, DiagnosticListener)startMessage = listener.Events.Dequeue();
                    Activity messageActivity = (Activity)startMessage.Value;
                    AssertCommonTags(messageActivity, sender.EntityPath, sender.FullyQualifiedNamespace);
                    Assert.AreEqual(DiagnosticProperty.MessageActivityName + ".Start", startMessage.Key);

                    (string Key, object Value, DiagnosticListener)stopMessage = listener.Events.Dequeue();
                    Assert.AreEqual(DiagnosticProperty.MessageActivityName + ".Stop", stopMessage.Key);

                    (string Key, object Value, DiagnosticListener)startSchedule = listener.Events.Dequeue();
                    AssertCommonTags((Activity)startSchedule.Value, sender.EntityPath, sender.FullyQualifiedNamespace);

                    Assert.AreEqual(DiagnosticProperty.ScheduleActivityName + ".Start", startSchedule.Key);
                    (string Key, object Value, DiagnosticListener)stopSchedule = listener.Events.Dequeue();

                    Assert.AreEqual(DiagnosticProperty.ScheduleActivityName + ".Stop", stopSchedule.Key);
                    var linkedActivities = ((IEnumerable <Activity>)startSchedule.Value.GetType().GetProperty("Links").GetValue(startSchedule.Value)).ToArray();
                    Assert.AreEqual(1, linkedActivities.Length);
                    Assert.AreEqual(messageActivity.Id, linkedActivities[0].ParentId);

                    await sender.CancelScheduledMessageAsync(seq);

                    (string Key, object Value, DiagnosticListener)startCancel = listener.Events.Dequeue();
                    AssertCommonTags((Activity)startCancel.Value, sender.EntityPath, sender.FullyQualifiedNamespace);
                    Assert.AreEqual(DiagnosticProperty.CancelActivityName + ".Start", startCancel.Key);

                    (string Key, object Value, DiagnosticListener)stopCancel = listener.Events.Dequeue();
                    Assert.AreEqual(DiagnosticProperty.CancelActivityName + ".Stop", stopCancel.Key);
                }

                // send a batch
                var batch = await sender.CreateMessageBatchAsync();

                for (int i = 0; i < numMessages; i++)
                {
                    batch.TryAddMessage(GetMessage(sessionId));
                }
                await sender.SendMessagesAsync(batch);

                AssertSendActivities(useSessions, sender, batch.AsEnumerable <ServiceBusMessage>(), listener);
            };
        }
 public DiagnosticObserver(TestDiagnosticListener listener)
 {
     _listener = listener;
 }
示例#24
0
        public void Configure(IApplicationBuilder app, ILoggerFactory factory, DiagnosticListener diagnosticListener)
        {
            // Listen for middleware events and log them to the console.
            var listener = new TestDiagnosticListener();

            diagnosticListener.SubscribeWithAdapter(listener);

            // Build our application pipeline

            // Named via app.UseMiddleware<T>()
            app.UseDeveloperExceptionPage();

            // Anonymous method inline middleware
            app.Use((context, next) =>
            {
                // No-op
                return(next());
            });

            app.Map("/map", subApp =>
            {
                subApp.Run(context =>
                {
                    return(context.Response.WriteAsync("Hello World"));
                });
            });

            // Low level anonymous method inline middleware, named Diagnostics.Middleware.Analysis.Startup+<>c by default
            app.Use(next =>
            {
                return(context =>
                {
                    return next(context);
                });
            });

            app.Map("/throw", throwApp =>
            {
                throwApp.Run(context => { throw new Exception("Application Exception"); });
            });

            // The home page.
            app.Properties["analysis.NextMiddlewareName"] = "HomePage";
            app.Use(async(context, next) =>
            {
                if (context.Request.Path == "/")
                {
                    context.Response.ContentType = "text/html";
                    await context.Response.WriteAsync("<html><body>Welcome to the sample<br><br>\r\n");
                    await context.Response.WriteAsync("Click here to take a side branch: <a href=\"/map/foo\">Map</a><br>\r\n");
                    await context.Response.WriteAsync("Click here to throw an exception: <a href=\"/throw\">Throw</a><br>\r\n");
                    await context.Response.WriteAsync("Click here to for a 404: <a href=\"/404\">404</a><br>\r\n");
                    await context.Response.WriteAsync("</body></html>\r\n");
                    return;
                }
                else
                {
                    await next();
                }
            });

            // Note there's always a default 404 middleware at the end of the pipeline.
        }
示例#25
0
        public async Task BeginEndDiagnosticAvailable()
        {
            DiagnosticListener diagnosticListener = null;

            var builder = new WebHostBuilder()
                            .Configure(app =>
                            {
                                diagnosticListener = app.ApplicationServices.GetRequiredService<DiagnosticListener>();
                                app.Run(context =>
                                {
                                    return context.Response.WriteAsync("Hello World");
                                });
                            });
            var server = new TestServer(builder);

            var listener = new TestDiagnosticListener();
            diagnosticListener.SubscribeWithAdapter(listener);
            var result = await server.CreateClient().GetStringAsync("/path");

            // This ensures that all diagnostics are completely written to the diagnostic listener
            Thread.Sleep(1000);

            Assert.Equal("Hello World", result);
            Assert.NotNull(listener.BeginRequest?.HttpContext);
            Assert.NotNull(listener.EndRequest?.HttpContext);
            Assert.Null(listener.UnhandledException);
        }
示例#26
0
 public void Setup()
 {
     _listener = new TestDiagnosticListener(EntityScopeFactory.DiagnosticNamespace);
 }
示例#27
0
        public async Task WriteAttribute_WithBoolValue_WritesBeginAndEndEvents_ToDiagnosticSource()
        {
            // Arrange
            var path = "some-path";
            var page = CreatePage(p =>
            {
                p.HtmlEncoder = new HtmlTestEncoder();
                p.BeginWriteAttribute("href", "prefix", 0, "suffix", 10, 1);
                p.WriteAttributeValue("", 6, "true", 6, 4, false);
                p.EndWriteAttribute();
            });

            page.Path = path;
            var adapter            = new TestDiagnosticListener();
            var diagnosticListener = new DiagnosticListener("Microsoft.AspNet.Mvc.Razor");

            diagnosticListener.SubscribeWithAdapter(adapter);
            page.DiagnosticSource = diagnosticListener;

            // Act
            await page.ExecuteAsync();

            // Assert
            Func <object, TestDiagnosticListener.BeginPageInstrumentationData> assertStartEvent = data =>
            {
                var beginEvent = Assert.IsType <TestDiagnosticListener.BeginPageInstrumentationData>(data);
                Assert.NotNull(beginEvent.HttpContext);
                Assert.Equal(path, beginEvent.Path);

                return(beginEvent);
            };

            Action <object> assertEndEvent = data =>
            {
                var endEvent = Assert.IsType <TestDiagnosticListener.EndPageInstrumentationData>(data);
                Assert.NotNull(endEvent.HttpContext);
                Assert.Equal(path, endEvent.Path);
            };

            Assert.Collection(adapter.PageInstrumentationData,
                              data =>
            {
                var beginEvent = assertStartEvent(data);
                Assert.Equal(0, beginEvent.Position);
                Assert.Equal(6, beginEvent.Length);
                Assert.True(beginEvent.IsLiteral);
            },
                              assertEndEvent,
                              data =>
            {
                var beginEvent = assertStartEvent(data);
                Assert.Equal(6, beginEvent.Position);
                Assert.Equal(4, beginEvent.Length);
                Assert.False(beginEvent.IsLiteral);
            },
                              assertEndEvent,
                              data =>
            {
                var beginEvent = assertStartEvent(data);
                Assert.Equal(10, beginEvent.Position);
                Assert.Equal(6, beginEvent.Length);
                Assert.True(beginEvent.IsLiteral);
            },
                              assertEndEvent);
        }
示例#28
0
        public async Task ExceptionDiagnosticAvailable()
        {
            DiagnosticListener diagnosticListener = null;
            var builder = new WebHostBuilder().Configure(app =>
            {
                diagnosticListener = app.ApplicationServices.GetRequiredService<DiagnosticListener>();
                app.Run(context =>
                {
                    throw new Exception("Test exception");
                });
            });
            var server = new TestServer(builder);

            var listener = new TestDiagnosticListener();
            diagnosticListener.SubscribeWithAdapter(listener);
            await Assert.ThrowsAsync<Exception>(() => server.CreateClient().GetAsync("/path"));

            // This ensures that all diagnostics are completely written to the diagnostic listener
            Thread.Sleep(1000);

            Assert.NotNull(listener.BeginRequest?.HttpContext);
            Assert.Null(listener.EndRequest?.HttpContext);
            Assert.NotNull(listener.UnhandledException?.HttpContext);
            Assert.NotNull(listener.UnhandledException?.Exception);
        }
示例#29
0
        public async Task WriteAttribute_WritesBeginAndEndEvents_ToDiagnosticSource()
        {
            // Arrange
            var path = "path-to-page";
            var page = CreatePage(p =>
            {
                p.HtmlEncoder = new HtmlTestEncoder();
                p.BeginWriteAttribute("href", "prefix", 0, "suffix", 34, 2);
                p.WriteAttributeValue("prefix", 0, "attr1-value", 8, 14, true);
                p.WriteAttributeValue("prefix2", 22, "attr2", 29, 5, false);
                p.EndWriteAttribute();
            });
            page.Path = path;
            var adapter = new TestDiagnosticListener();
            var diagnosticListener = new DiagnosticListener("Microsoft.AspNet.Mvc.Razor");
            diagnosticListener.SubscribeWithAdapter(adapter);
            page.DiagnosticSource = diagnosticListener;

            // Act
            await page.ExecuteAsync();

            // Assert
            Func<object, TestDiagnosticListener.BeginPageInstrumentationData> assertStartEvent = data =>
            {
                var beginEvent = Assert.IsType<TestDiagnosticListener.BeginPageInstrumentationData>(data);
                Assert.NotNull(beginEvent.HttpContext);
                Assert.Equal(path, beginEvent.Path);

                return beginEvent;
            };

            Action<object> assertEndEvent = data =>
            {
                var endEvent = Assert.IsType<TestDiagnosticListener.EndPageInstrumentationData>(data);
                Assert.NotNull(endEvent.HttpContext);
                Assert.Equal(path, endEvent.Path);
            };

            Assert.Collection(adapter.PageInstrumentationData,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(0, beginEvent.Position);
                    Assert.Equal(6, beginEvent.Length);
                    Assert.True(beginEvent.IsLiteral);
                },
                assertEndEvent,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(0, beginEvent.Position);
                    Assert.Equal(6, beginEvent.Length);
                    Assert.True(beginEvent.IsLiteral);
                },
                assertEndEvent,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(8, beginEvent.Position);
                    Assert.Equal(14, beginEvent.Length);
                    Assert.True(beginEvent.IsLiteral);
                },
                assertEndEvent,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(22, beginEvent.Position);
                    Assert.Equal(7, beginEvent.Length);
                    Assert.True(beginEvent.IsLiteral);
                },
                assertEndEvent,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(29, beginEvent.Position);
                    Assert.Equal(5, beginEvent.Length);
                    Assert.False(beginEvent.IsLiteral);
                },
                assertEndEvent,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(34, beginEvent.Position);
                    Assert.Equal(6, beginEvent.Length);
                    Assert.True(beginEvent.IsLiteral);
                },
                assertEndEvent);
        }
示例#30
0
        public async Task WriteAttribute_WritesBeginAndEndEvents_ToDiagnosticSource_OnPrefixAndSuffixValues()
        {
            // Arrange
            var path = "some-path";
            var page = CreatePage(p =>
            {
                p.BeginWriteAttribute("href", "prefix", 0, "tail", 7, 0);
                p.EndWriteAttribute();
            });
            page.Path = path;
            var adapter = new TestDiagnosticListener();
            var diagnosticListener = new DiagnosticListener("Microsoft.AspNet.Mvc.Razor");
            diagnosticListener.SubscribeWithAdapter(adapter);
            page.DiagnosticSource = diagnosticListener;

            // Act
            await page.ExecuteAsync();

            // Assert
            Func<object, TestDiagnosticListener.BeginPageInstrumentationData> assertStartEvent = data =>
            {
                var beginEvent = Assert.IsType<TestDiagnosticListener.BeginPageInstrumentationData>(data);
                Assert.NotNull(beginEvent.HttpContext);
                Assert.Equal(path, beginEvent.Path);

                return beginEvent;
            };

            Action<object> assertEndEvent = data =>
            {
                var endEvent = Assert.IsType<TestDiagnosticListener.EndPageInstrumentationData>(data);
                Assert.NotNull(endEvent.HttpContext);
                Assert.Equal(path, endEvent.Path);
            };

            Assert.Collection(adapter.PageInstrumentationData,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(0, beginEvent.Position);
                    Assert.Equal(6, beginEvent.Length);
                    Assert.True(beginEvent.IsLiteral);
                },
                assertEndEvent,
                data =>
                {
                    var beginEvent = assertStartEvent(data);
                    Assert.Equal(7, beginEvent.Position);
                    Assert.Equal(4, beginEvent.Length);
                    Assert.True(beginEvent.IsLiteral);
                },
                assertEndEvent);
        }