private static void SetProfilingSessionClientIpAndLocalAddress(
            Message request, IClientChannel channel)
        {
            ProfilingSession profilingSession = ProfilingSession.Current;

            if (profilingSession != null)
            {
                // set local address
                if (channel != null)
                {
                    profilingSession.Profiler.GetTimingSession().Data["localAddress"] = channel.LocalAddress.Uri.ToString();
                }

                // set client IP address
                if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
                {
                    var remoteEndpoint =
                        request.Properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
                    if (remoteEndpoint != null)
                    {
                        profilingSession.Profiler.GetTimingSession().Data["clientIp"] = remoteEndpoint.Address;
                    }
                }
            }
        }
        public void TestProfilingSession_Start()
        {
            // mock http context
            var mockHttpContext = new HttpContextMock();

            HttpContext.Current = mockHttpContext.Object;

            // ensure HttpContextCallContextProfilingSessionContainer is in use
            Assert.IsTrue(ProfilingSession.ProfilingSessionContainer is WebProfilingSessionContainer);

            // mock profiler and provider
            var profilerId   = Guid.NewGuid();
            var mockProfiler = new Mock <IProfiler>();

            mockProfiler.Setup(p => p.Id).Returns(profilerId);
            mockProfiler.Setup(p => p.GetTimingSession()).Returns(new TimingSession(mockProfiler.Object, "test", null));
            ProfilingSession.CreateProfilerHandler = (s, storage, arg3) => mockProfiler.Object;

            // mock profiling storage
            var mockProfilingStorage = new Mock <IProfilingStorage>();

            ProfilingSession.ProfilingStorage = mockProfilingStorage.Object;
            Assert.AreEqual(mockProfilingStorage.Object, ProfilingSession.ProfilingStorage);

            // execute
            ProfilingSession.Start("test");

            Assert.AreEqual(mockProfiler.Object, ProfilingSession.Current.Profiler);
            Assert.AreEqual(mockProfiler.Object, (mockHttpContext.Object.Items["nano_profiler::current_profiling_session"] as ProfilingSession).Profiler);
            Assert.AreEqual(mockProfiler.Object.Id, CallContext.LogicalGetData("nano_profiler::current_profiling_session_id"));
        }
Esempio n. 3
0
        bool IErrorHandler.HandleError(Exception error)
        {
            ProfilingSession.Stop(discardResults: true);

            // we don't really handle the error, so always return false to move on to next error handler
            return(false);
        }
        public void TestProfilingSession_Stop_HandleException()
        {
            var discardResults    = true;
            var exceptionHandled  = false;
            var expectedException = new Exception();

            // mock profiler
            var profilerId   = Guid.NewGuid();
            var mockProfiler = new Mock <IProfiler>();

            mockProfiler.Setup(p => p.Id).Returns(profilerId);
            mockProfiler.Setup(p => p.GetTimingSession()).Returns(new TimingSession(mockProfiler.Object, "test", null));
            mockProfiler.Setup(profiler => profiler.Stop(It.IsAny <bool>())).Throws(expectedException);
            var expected = new ProfilingSession(mockProfiler.Object);

            ProfilingSession.ProfilingSessionContainer.CurrentSession = expected;

            ProfilingSession.HandleExceptionHandler = (a, b) =>
            {
                Assert.AreEqual(expectedException, a);
                Assert.AreEqual(typeof(ProfilingSession), b);

                exceptionHandled = true;
            };

            // execute
            ProfilingSession.Stop(discardResults);

            Assert.IsTrue(exceptionHandled);
        }
        public void TestProfilingSession_Stop()
        {
            var discardResults       = true;
            var stopOfProfilerCalled = false;

            // mock profiler
            var profilerId   = Guid.NewGuid();
            var mockProfiler = new Mock <IProfiler>();

            mockProfiler.Setup(p => p.Id).Returns(profilerId);
            mockProfiler.Setup(p => p.GetTimingSession()).Returns(new TimingSession(mockProfiler.Object, "test", null));
            mockProfiler.Setup(profiler => profiler.Stop(It.IsAny <bool>()))
            .Callback <bool>(a =>
            {
                Assert.AreEqual(discardResults, a);
                stopOfProfilerCalled = true;
            });
            var expected = new ProfilingSession(mockProfiler.Object);

            ProfilingSession.ProfilingSessionContainer.CurrentSession = expected;

            // execute
            ProfilingSession.Stop(discardResults);

            Assert.IsTrue(stopOfProfilerCalled);
        }
        public void TestProfilingSession_getProfiler()
        {
            var mockProfiler = new Mock <IProfiler>();
            var target       = new ProfilingSession(mockProfiler.Object);

            Assert.AreEqual(mockProfiler.Object, target.Profiler);
        }
        public void TestProfilingSession_StepImpl_HandleException()
        {
            var name = "test";
            var expectedException = new Exception();
            var exceptionHandled  = false;

            // mock step
            var mockStep = new Mock <IProfilingStep>();

            // mock profiler
            var mockProfiler = new Mock <IProfiler>();

            mockProfiler.Setup(profiler => profiler.Step(name, null)).Throws(expectedException);
            var target = new ProfilingSession(mockProfiler.Object);

            ProfilingSession.HandleExceptionHandler = (a, b) =>
            {
                Assert.AreEqual(expectedException, a);
                Assert.AreEqual(target, b);

                exceptionHandled = true;
            };

            // execute
            Assert.IsNull(target.StepImpl(name, null));
        }
Esempio n. 8
0
        public void TestProfilingSessionExtensions_Step_InvalidGetName()
        {
            var mockProfiler = new Mock <IProfiler>();
            var target       = new ProfilingSession(mockProfiler.Object);

            Assert.IsNull(target.Step((Func <string>)null));
        }
        private void SaveQueuedSessions()
        {
            do
            {
                // Suspend for a while
                //_processWait.WaitOne(ThreadSleepMilliseconds, exitContext: false);
                _processWait.WaitOne(ThreadSleepMilliseconds);

                // Upgrade to foreground thread
                Thread.CurrentThread.IsBackground = false;

                // set null the current profiling session bound to the running thread to release the memory
                ProfilingSession.SetCurrentProfilingSession(null);

                // Save all the queued sessions
                ITimingSession session;
                while (TryDequeue(out session))
                {
                    Save(session);

                    // Signal waiting threads to continue
                    _entryWait.Set();
                }

                // Downgrade to background thread while waiting
                Thread.CurrentThread.IsBackground = true;
            } while (true);
        }
        public static ProfilingSession AddProfiler(this IConnectionMultiplexer mutex)
        {
            var session = new ProfilingSession();

            mutex.RegisterProfiler(() => session);
            return(session);
        }
Esempio n. 11
0
        private static async Task <string> DoWork()
        {
            ProfilingSession.Start("DoWork");

            // Avoid GC of session
            _current = ProfilingSession.Current;

            ITimingSession timingSession = ProfilingSession.Current.Profiler.GetTimingSession();

            using (ProfilingSession.Current.Step("child1"))
            {
                await Task.WhenAll(Task.Run(() =>
                {
                    using (ProfilingSession.Current.Step("child1.1"))
                    {
                        Thread.Sleep(10);
                    }
                }),
                                   Task.Run(() =>
                {
                    using (ProfilingSession.Current.Step("child1.2"))
                    {
                        Thread.Sleep(20);
                    }
                }));
            }
            ProfilingSession.Stop();
            string report = GetReport(timingSession);

            return(report);
        }
Esempio n. 12
0
        public void SimpleProfiling()
        {
            using (var conn = Create())
            {
                var profiler = new ProfilingSession();
                var key      = Me();
                var db       = conn.GetDatabase();
                db.KeyDelete(key, CommandFlags.FireAndForget);

                conn.RegisterProfiler(() => profiler);
                db.StringSet(key, "world");
                var val = db.StringGet(key);
                Assert.Equal("world", val);

                var msgs = profiler.FinishProfiling().Where(m => m.Command == "GET" || m.Command == "SET").ToList();
                foreach (var msg in msgs)
                {
                    Log("Profiler Message: " + Environment.NewLine + msg);
                }
                Log("Checking GET...");
                Assert.Contains(msgs, m => m.Command == "GET");
                Log("Checking SET...");
                Assert.Contains(msgs, m => m.Command == "SET");
                Assert.Equal(2, msgs.Count(m => m.RetransmissionOf is null));

                var arr = msgs.Where(m => m.RetransmissionOf is null).ToArray();
                Assert.Equal("SET", arr[0].Command);
                Assert.Equal("GET", arr[1].Command);
            }
        }
Esempio n. 13
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseCoreProfiler(true);

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

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            // InitializeDatabase is executed in async thread on app startup
            // to profile its performance, we need to call ProfilingSession.Start()/Stop() explicitly
            try
            {
                ProfilingSession.Start("InitializeDatabase");
                InitializeDatabase(app);
            }
            finally
            {
                ProfilingSession.Stop();
            }
        }
 public void TestProfilingSessionExtensions_Step()
 {
     var mockStep = new Mock<IProfilingStep>();
     var mockProfiler = new Mock<IProfiler>();
     mockProfiler.Setup(profiler => profiler.Step(It.IsAny<string>(), It.IsAny<string[]>(), It.IsAny<string>())).Returns(mockStep.Object);
     var target = new ProfilingSession(mockProfiler.Object);
     Assert.AreEqual(mockStep.Object, target.Step(() => "test"));
 }
Esempio n. 15
0
        /// <summary>
        /// Gets the profiled connection (with NanoProfiler).
        /// </summary>
        /// <param name="connectionString">The connection string.</param>
        /// <param name="currentSession">The current session.</param>
        /// <returns>IDbConnection.</returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public IDbConnection GetProfiledConnection(
            string connectionString, ProfilingSession currentSession)
        {
            var profiler = GetProfiler(ProfilingSession.Current);
            var conn     = this.GetConnection(connectionString, profiler);

            return(conn);
        }
Esempio n. 16
0
        private void ApplicationOnError(object sender, EventArgs eventArgs)
        {
            // stop and save profiling results on error

            using (ProfilingSession.Current.Step("Stop on Error")) { }

            ProfilingSession.Stop();
        }
 public void TestProfilingSessionExtensions_Ignore()
 {
     var mockStep = new Mock<IDisposable>();
     var mockProfiler = new Mock<IProfiler>();
     mockProfiler.Setup(profiler => profiler.Ignore()).Returns(mockStep.Object);
     var target = new ProfilingSession(mockProfiler.Object);
     Assert.AreEqual(mockStep.Object, target.Ignore());
 }
Esempio n. 18
0
        /// <summary>
        /// Gets the profiler.
        /// </summary>
        /// <param name="currentSession">The current session.</param>
        /// <returns>IProfiler.</returns>
        private static IProfiler GetProfiler(ProfilingSession currentSession)
        {
            IProfiler profiler = currentSession == null
                                 ? null
                                 : currentSession.Profiler;

            return(profiler);
        }
Esempio n. 19
0
        public void ManyThreads()
        {
            using (var conn = Create())
            {
                var session = new ProfilingSession();
                var prefix  = Me();

                conn.RegisterProfiler(() => session);

                var       threads  = new List <Thread>();
                const int CountPer = 100;
                for (var i = 1; i <= 16; i++)
                {
                    var db = conn.GetDatabase(i);

                    threads.Add(new Thread(() =>
                    {
                        var threadTasks = new List <Task>();

                        for (var j = 0; j < CountPer; j++)
                        {
                            var task = db.StringSetAsync(prefix + j, "" + j);
                            threadTasks.Add(task);
                        }

                        Task.WaitAll(threadTasks.ToArray());
                    }));
                }

                threads.ForEach(thread => thread.Start());
                threads.ForEach(thread => thread.Join());

                var allVals  = session.FinishProfiling();
                var relevant = allVals.Where(cmd => cmd.Db > 0).ToList();

                var kinds = relevant.Select(cmd => cmd.Command).Distinct().ToList();
                foreach (var k in kinds)
                {
                    Log("Kind Seen: " + k);
                }
                Assert.True(kinds.Count <= 2);
                Assert.Contains("SET", kinds);
                if (kinds.Count == 2 && !kinds.Contains("SELECT") && !kinds.Contains("GET"))
                {
                    Assert.True(false, "Non-SET, Non-SELECT, Non-GET command seen");
                }

                Assert.Equal(16 * CountPer, relevant.Count);
                Assert.Equal(16, relevant.Select(cmd => cmd.Db).Distinct().Count());

                for (var i = 1; i <= 16; i++)
                {
                    var setsInDb = relevant.Count(cmd => cmd.Db == i);
                    Assert.Equal(CountPer, setsInDb);
                }
            }
        }
Esempio n. 20
0
        public void Simple()
        {
            using (var conn = Create())
            {
                var key = Me();

                var session = new ProfilingSession();

                conn.RegisterProfiler(() => session);

                var dbId = TestConfig.GetDedicatedDB();
                var db   = conn.GetDatabase(dbId);
                db.StringSet(key, "world");
                var result = db.ScriptEvaluate(LuaScript.Prepare("return redis.call('get', @key)"), new { key = (RedisKey)key });
                Assert.Equal("world", result.AsString());
                var val = db.StringGet(key);
                Assert.Equal("world", (string)val);
                var s = (string)db.Execute("ECHO", "fii");
                Assert.Equal("fii", s);

                var cmds = session.FinishProfiling();
                var i    = 0;
                foreach (var cmd in cmds)
                {
                    Log("Command {0} (DB: {1}): {2}", i++, cmd.Db, cmd.ToString().Replace("\n", ", "));
                }

                var all = string.Join(",", cmds.Select(x => x.Command));
                Assert.Equal("SET,EVAL,GET,ECHO", all);
                Log("Checking for SET");
                var set = cmds.SingleOrDefault(cmd => cmd.Command == "SET");
                Assert.NotNull(set);
                Log("Checking for GET");
                var get = cmds.SingleOrDefault(cmd => cmd.Command == "GET");
                Assert.NotNull(get);
                Log("Checking for EVAL");
                var eval = cmds.SingleOrDefault(cmd => cmd.Command == "EVAL");
                Assert.NotNull(eval);
                Log("Checking for ECHO");
                var echo = cmds.SingleOrDefault(cmd => cmd.Command == "ECHO");
                Assert.NotNull(echo);

                Assert.Equal(4, cmds.Count());

                Assert.True(set.CommandCreated <= eval.CommandCreated);
                Assert.True(eval.CommandCreated <= get.CommandCreated);

                AssertProfiledCommandValues(set, conn, dbId);

                AssertProfiledCommandValues(get, conn, dbId);

                AssertProfiledCommandValues(eval, conn, dbId);

                AssertProfiledCommandValues(echo, conn, dbId);
            }
        }
Esempio n. 21
0
        protected ProfiledCommandEnumerable Log(ProfilingSession session)
        {
            var profile = session.FinishProfiling();

            foreach (var command in profile)
            {
                Writer.WriteLineNoTime(command.ToString());
            }
            return(profile);
        }
Esempio n. 22
0
            public ProfilingSession GetSession()
            {
                var val = perThreadSession.Value;

                if (val == null)
                {
                    perThreadSession.Value = val = new ProfilingSession();
                }
                return(val);
            }
Esempio n. 23
0
        public void TestProfilingSessionExtensions_Ignore()
        {
            var mockStep     = new Mock <IDisposable>();
            var mockProfiler = new Mock <IProfiler>();

            mockProfiler.Setup(profiler => profiler.Ignore()).Returns(mockStep.Object);
            var target = new ProfilingSession(mockProfiler.Object);

            Assert.AreEqual(mockStep.Object, target.Ignore());
        }
Esempio n. 24
0
        public void TestProfilingSessionExtensions_Step()
        {
            var mockStep     = new Mock <IProfilingStep>();
            var mockProfiler = new Mock <IProfiler>();

            mockProfiler.Setup(profiler => profiler.Step(It.IsAny <string>(), It.IsAny <TagCollection>())).Returns(mockStep.Object);
            var target = new ProfilingSession(mockProfiler.Object);

            Assert.AreEqual(mockStep.Object, target.Step(() => "test"));
        }
Esempio n. 25
0
        public ProfilingSession StartSession()
        {
            var profilingSession = perAsyncFlowSession.Value;

            if (profilingSession == null)
            {
                perAsyncFlowSession.Value = profilingSession = new ProfilingSession();
            }
            return(profilingSession);
        }
Esempio n. 26
0
        public void TestProfilingSession_getCurrent_FromHttpContext()
        {
            var mockProfiler    = new Mock <IProfiler>();
            var expected        = new ProfilingSession(mockProfiler.Object);
            var mockHttpContext = new HttpContextMock();

            mockHttpContext.Object.Items["nano_profiler::current_profiling_session"] = expected;
            HttpContext.Current = mockHttpContext.Object;

            Assert.AreEqual(expected, ProfilingSession.Current);
        }
Esempio n. 27
0
        public void TestProfilingSession_getCurrent_FromCallContext()
        {
            lock (typeof (CallContextProfilingSessionContainer))
            {
                var mockProfiler = new Mock<IProfiler>();
                var expected = new ProfilingSession(mockProfiler.Object);
                ProfilingSession.ProfilingSessionContainer.CurrentSession = expected;

                Assert.AreEqual(expected, ProfilingSession.Current);
            }
        }
        public async Task ProfilerSessionsHandleMultipleSpans()
        {
            var connectionOptions = new ConfigurationOptions
            {
                AbortOnConnectFail = false,
            };

            connectionOptions.EndPoints.Add("localhost:6379");

            var connection = ConnectionMultiplexer.Connect(connectionOptions);

            using var instrumentation = new StackExchangeRedisCallsInstrumentation(connection, new StackExchangeRedisCallsInstrumentationOptions());
            var profilerFactory = instrumentation.GetProfilerSessionsFactory();

            // start a root level activity
            using Activity rootActivity = new Activity("Parent")
                                          .SetParentId(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.Recorded)
                                          .Start();

            Assert.NotNull(rootActivity.Id);

            // get an initial profiler from root activity
            Activity.Current = rootActivity;
            ProfilingSession profiler0 = profilerFactory();

            // expect different result from synchronous child activity
            ProfilingSession profiler1;

            using (Activity.Current = new Activity("Child-Span-1").SetParentId(rootActivity.Id).Start())
            {
                profiler1 = profilerFactory();
                Assert.NotSame(profiler0, profiler1);
            }

            Activity.Current = rootActivity;

            // expect different result from asynchronous child activity
            using (Activity.Current = new Activity("Child-Span-2").SetParentId(rootActivity.Id).Start())
            {
                // lose async context on purpose
                await Task.Delay(100).ConfigureAwait(false);

                ProfilingSession profiler2 = profilerFactory();
                Assert.NotSame(profiler0, profiler2);
                Assert.NotSame(profiler1, profiler2);
            }

            Activity.Current = rootActivity;

            // ensure same result back in root activity
            ProfilingSession profiles3 = profilerFactory();

            Assert.Same(profiler0, profiles3);
        }
Esempio n. 29
0
        public void TestProfilingSession_getCurrent_FromCallContext()
        {
            lock (typeof(CallContextProfilingSessionContainer))
            {
                var mockProfiler = new Mock <IProfiler>();
                var expected     = new ProfilingSession(mockProfiler.Object);
                ProfilingSession.ProfilingSessionContainer.CurrentSession = expected;

                Assert.AreEqual(expected, ProfilingSession.Current);
            }
        }
Esempio n. 30
0
        private void EndProfilingSession(object sender, ProfilingSession session)
        {
            IExecutionSegment executionSegment = sender as Span;
            string            segmentType;

            if (executionSegment is null)
            {
                executionSegment = sender as Transaction;
                if (executionSegment is null)
                {
                    return;
                }

                segmentType = "transaction";
            }
            else
            {
                segmentType = "span";
            }

            try
            {
                // Remove the session. Use session passed to EndProfilingSession rather than the removed session in the event
                // there was an issue in adding or removing the session
                if (!_executionSegmentSessions.TryRemove(executionSegment.Id, out _))
                {
                    _logger.Value.Debug()?.Log(
                        "could not remove profiling session from tracked sessions for {ExecutionSegment} {Id}",
                        segmentType, executionSegment.Id);
                }

                var profiledCommands = session.FinishProfiling();
                _logger.Value.Trace()?.Log(
                    "Finished profiling session for {ExecutionSegment}. Collected {ProfiledCommandCount} commands",
                    executionSegment, profiledCommands.Count());

                foreach (var profiledCommand in profiledCommands)
                {
                    ProcessCommand(profiledCommand, executionSegment);
                }

                _logger.Value.Trace()?.Log(
                    "End profiling session for {ExecutionSegment} {Id}",
                    segmentType, executionSegment.Id);
            }
            catch (Exception e)
            {
                _logger.Value.Error()?.LogException(e,
                                                    "Exception ending profiling session for {ExecutionSegment} {Id}",
                                                    segmentType, executionSegment.Id);
            }
        }
Esempio n. 31
0
        /// <summary>
        /// Gets a profiling session for StackExchange.Redis to add redis commands to.
        /// Creates a profiling session per span or transaction
        /// </summary>
        /// <remarks>
        /// See https://stackexchange.github.io/StackExchange.Redis/Profiling_v2.html
        /// </remarks>
        /// <returns>A profiling session for the current span or transaction, or null if the agent is not enabled or not recording</returns>
        public ProfilingSession GetProfilingSession()
        {
            if (!Agent.Config.Enabled || !Agent.Config.Recording)
            {
                return(null);
            }

            var         executionSegment = _agent.Value.GetCurrentExecutionSegment();
            var         realSpan         = executionSegment as Span;
            Transaction realTransaction  = null;

            // don't profile when there's no real span or transaction
            if (realSpan is null)
            {
                realTransaction = executionSegment as Transaction;
                if (realTransaction is null)
                {
                    return(null);
                }
            }

            var isSpan = realSpan != null;

            if (!_executionSegmentSessions.TryGetValue(executionSegment.Id, out var session))
            {
                _logger.Value.Trace()?.Log("Creating profiling session for {ExecutionSegment} {Id}",
                                           isSpan ? "span" : "transaction",
                                           executionSegment.Id);

                session = new ProfilingSession();

                if (!_executionSegmentSessions.TryAdd(executionSegment.Id, session))
                {
                    _logger.Value.Debug()?.Log("could not add profiling session to tracked sessions for {ExecutionSegment} {Id}",
                                               isSpan ? "span" : "transaction",
                                               executionSegment.Id);
                }

                if (isSpan)
                {
                    realSpan.Ended += (sender, _) => EndProfilingSession(sender, session);
                }
                else
                {
                    realTransaction.Ended += (sender, _) => EndProfilingSession(sender, session);
                }
            }

            return(session);
        }
Esempio n. 32
0
        public void LowAllocationEnumerable()
        {
            const int OuterLoop = 1000;

            using (var conn = Create())
            {
                var session = new ProfilingSession();
                conn.RegisterProfiler(() => session);

                var prefix = Me();
                var db     = conn.GetDatabase(1);

                var allTasks = new List <Task <string> >();

                foreach (var i in Enumerable.Range(0, OuterLoop))
                {
                    var t =
                        db.StringSetAsync(prefix + i, "bar" + i)
                        .ContinueWith(
                            async _ => (string)(await db.StringGetAsync(prefix + i).ForAwait())
                            );

                    var finalResult = t.Unwrap();
                    allTasks.Add(finalResult);
                }

                conn.WaitAll(allTasks.ToArray());

                var res = session.FinishProfiling();
                Assert.True(res.GetType().IsValueType);

                using (var e = res.GetEnumerator())
                {
                    Assert.True(e.GetType().IsValueType);

                    Assert.True(e.MoveNext());
                    var i = e.Current;

                    e.Reset();
                    Assert.True(e.MoveNext());
                    var j = e.Current;

                    Assert.True(object.ReferenceEquals(i, j));
                }

                Assert.Equal(OuterLoop, res.Count(r => r.Command == "GET" && r.Db > 0));
                Assert.Equal(OuterLoop, res.Count(r => r.Command == "SET" && r.Db > 0));
                Assert.Equal(OuterLoop * 2, res.Count(r => r.Db > 0));
            }
        }
Esempio n. 33
0
        public void TestProfilingSession_StepImpl()
        {
            var name = "test";

            // mock step
            var mockStep = new Mock <IProfilingStep>();

            // mock profiler
            var mockProfiler = new Mock <IProfiler>();

            mockProfiler.Setup(profiler => profiler.Step(name, null)).Returns(mockStep.Object);
            var target = new ProfilingSession(mockProfiler.Object);


            Assert.AreEqual(mockStep.Object, target.StepImpl(name, null));
        }
 private static void MergeRequestTags(ProfilingSession profilingSession, IEnumerable<string> tags)
 {
     if (tags != null)
     {
         if (profilingSession.Profiler.Tags == null)
         {
             profilingSession.Profiler.Tags = new TagCollection(tags);
         }
         else
         {
             foreach (var tag in tags)
             {
                 profilingSession.Profiler.Tags.Add(tag);
             }
         }
     }
 }
Esempio n. 35
0
        public void TestProfilingSession_getCurrent_FromHttpContext()
        {
            var mockProfiler = new Mock<IProfiler>();
            var expected = new ProfilingSession(mockProfiler.Object);
            var mockHttpContext = new HttpContextMock();
            mockHttpContext.Object.Items["nano_profiler::current_profiling_session"] = expected;
            HttpContext.Current = mockHttpContext.Object;

            Assert.AreEqual(expected, ProfilingSession.Current);
        }
Esempio n. 36
0
        public void TestProfilingSession_Stop_HandleException()
        {
            var discardResults = true;
            var exceptionHandled = false;
            var expectedException = new Exception();

            // mock profiler
            var profilerId = Guid.NewGuid();
            var mockProfiler = new Mock<IProfiler>();
            mockProfiler.Setup(p => p.Id).Returns(profilerId);
            mockProfiler.Setup(profiler => profiler.Stop(It.IsAny<bool>())).Throws(expectedException);
            var expected = new ProfilingSession(mockProfiler.Object);
            ProfilingSession.ProfilingSessionContainer.CurrentSession = expected;

            // mock provider
            var mockProflingProvider = new Mock<IProfilerProvider>();
            mockProflingProvider.Setup(provider => provider.HandleException(It.IsAny<Exception>(), It.IsAny<object>()))
                .Callback<Exception, object>((a, b) =>
                    {
                        Assert.AreEqual(expectedException, a);
                        Assert.AreEqual(typeof(ProfilingSession), b);

                        exceptionHandled = true;
                    });
            ProfilingSession.ProfilerProvider = mockProflingProvider.Object;

            // execute
            ProfilingSession.Stop(discardResults);

            Assert.IsTrue(exceptionHandled);
        }
 public void TestProfilingSessionExtensions_Step_InvalidName()
 {
     var mockProfiler = new Mock<IProfiler>();
     var target = new ProfilingSession(mockProfiler.Object);
     Assert.IsNull(target.Step((string)null));
 }
Esempio n. 38
0
        public void TestProfilingSession_Stop()
        {
            var discardResults = true;
            var stopOfProfilerCalled = false;

            // mock profiler
            var profilerId = Guid.NewGuid();
            var mockProfiler = new Mock<IProfiler>();
            mockProfiler.Setup(p => p.Id).Returns(profilerId);
            mockProfiler.Setup(profiler => profiler.Stop(It.IsAny<bool>()))
                .Callback<bool>(a =>
                    {
                        Assert.AreEqual(discardResults, a);
                        stopOfProfilerCalled = true;
                    });
            var expected = new ProfilingSession(mockProfiler.Object);
            ProfilingSession.ProfilingSessionContainer.CurrentSession = expected;

            // execute
            ProfilingSession.Stop(discardResults);

            Assert.IsTrue(stopOfProfilerCalled);
        }
Esempio n. 39
0
        public void TestProfilingSession_StepImpl_HandleException()
        {
            var name = "test";
            var expectedException = new Exception();
            var exceptionHandled = false;

            // mock step
            var mockStep = new Mock<IProfilingStep>();

            // mock profiler
            var mockProfiler = new Mock<IProfiler>();
            mockProfiler.Setup(profiler => profiler.Step(name, null, null)).Throws(expectedException);
            var target = new ProfilingSession(mockProfiler.Object);

            // mock provider
            var mockProflingProvider = new Mock<IProfilerProvider>();
            mockProflingProvider.Setup(provider => provider.HandleException(It.IsAny<Exception>(), It.IsAny<object>()))
                .Callback<Exception, object>((a, b) =>
                {
                    Assert.AreEqual(expectedException, a);
                    Assert.AreEqual(target, b);

                    exceptionHandled = true;
                });
            ProfilingSession.ProfilerProvider = mockProflingProvider.Object;

            // execute
            Assert.IsNull(target.StepImpl(name, null));
        }
Esempio n. 40
0
        public void TestProfilingSession_StepImpl()
        {
            var name = "test";

            // mock step
            var mockStep = new Mock<IProfilingStep>();

            // mock profiler
            var mockProfiler = new Mock<IProfiler>();
            mockProfiler.Setup(profiler => profiler.Step(name, null, It.IsAny<string>())).Returns(mockStep.Object);
            var target = new ProfilingSession(mockProfiler.Object);

            Assert.AreEqual(mockStep.Object, target.StepImpl(name, null));
        }
Esempio n. 41
0
        public void TestProfilingSession_getProfiler()
        {
            var mockProfiler = new Mock<IProfiler>();
            var target = new ProfilingSession(mockProfiler.Object);

            Assert.AreEqual(mockProfiler.Object, target.Profiler);
        }