public void TestScope()
        {
            var log = GetLogger();

            log.Debug("with no scope");
            using (LogScope.Init("testing my scope"))
            {
                log.Trace("a message with scope");
            }
            log.Debug("with no scope2");

            var contains = false;
            var txt      = "";

            using (FileStream stream = File.Open(@"./logs/testing.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    txt = reader.ReadToEnd();
                }
            }


            var lines  = txt.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            var scoped = lines[lines.Length - 2];

            contains = scoped?.Contains("[NDC:testing my scope]") ?? false;
            var noContains = lines.LastOrDefault()?.Contains("[NDC:(null)]") ?? false;

            Assert.True(contains);
            Assert.True(noContains);
        }
Example #2
0
 public void Execute(LogScope logScope)
 {
     try
     {
         SetCurrentTestContext();
         m_Result = m_Action();
         if (logScope.AnyFailingLogs())
         {
             var failingLog = logScope.FailingLogs.First();
             throw new UnhandledLogMessageException(failingLog);
         }
         if (logScope.ExpectedLogs.Any())
         {
             throw new UnexpectedLogMessageException(LogScope.Current.ExpectedLogs.Peek());
         }
     }
     catch (Exception e)
     {
         m_Exception = e;
     }
     finally
     {
         m_Action = null;
         m_Signal.Set();
     }
 }
Example #3
0
 static void PostTestValidation(LogScope logScope, TestCommand command, TestResult result)
 {
     if (MustExpect(command.Test.Method.MethodInfo))
     {
         CaptureException(result, logScope.NoUnexpectedReceived);
     }
 }
Example #4
0
        public void SaveContext()
        {
            var currentContext = UnityTestExecutionContext.CurrentContext;

            if (currentContext.TestObject != null)
            {
                m_TestObjectTypeName = currentContext.TestObject.GetType().AssemblyQualifiedName;
                m_TestObject         = null;
                m_TestObjectTxt      = null;
                if (currentContext.TestObject is ScriptableObject)
                {
                    m_TestObject            = currentContext.TestObject as ScriptableObject;
                    m_OriginalHideFlags     = m_TestObject.hideFlags;
                    m_TestObject.hideFlags |= HideFlags.DontSave;
                }
                else
                {
                    m_TestObjectTxt = JsonUtility.ToJson(currentContext.TestObject);
                }
            }

            output      = currentContext.CurrentResult.Output;
            StartTicks  = currentContext.StartTicks;
            StartTimeOA = currentContext.StartTime.ToOADate();
            if (LogScope.HasCurrentLogScope())
            {
                m_ExpectedLogs = LogScope.Current.ExpectedLogs.ToArray();
            }

            m_ShouldRestore = true;
        }
Example #5
0
            public void LogsOnlySpecifiedCategories()
            {
                using var logScope = LogScope.Create("NewScope", this.LogMethod);

                logScope.Category = LogCategories.Technical;
                this.LogMessages.Clear();
                logScope.Log(LogCategories.Technical, LogLevel.Trace, "Trace");
                Assert.AreEqual(1, this.LogMessages.Count);
                logScope.Log(LogCategories.Business, LogLevel.Trace, "Trace");
                Assert.AreEqual(1, this.LogMessages.Count);

                logScope.Category = LogCategories.Business;
                this.LogMessages.Clear();
                logScope.Log(LogCategories.Technical, LogLevel.Trace, "Trace");
                Assert.AreEqual(0, this.LogMessages.Count);
                logScope.Log(LogCategories.Business, LogLevel.Trace, "Trace");
                Assert.AreEqual(1, this.LogMessages.Count);

                logScope.Category = LogCategories.Business | LogCategories.Technical;
                this.LogMessages.Clear();
                logScope.Log(LogCategories.Technical, LogLevel.Trace, "Trace");
                Assert.AreEqual(1, this.LogMessages.Count);
                logScope.Log(LogCategories.Business, LogLevel.Trace, "Trace");
                Assert.AreEqual(2, this.LogMessages.Count);
            }
Example #6
0
            public async Task OnlyMatchingLogMessagesAreLogged()
            {
                var level = LogScope.DefaultLevel;

                try
                {
                    LogScope.DefaultLevel = LogLevel.Information;
                    await using (var logScope = LogScope.Create("NewScope", this.LogMethod))
                    {
                        this.LogMessages.Clear();
                        logScope.Log(LogCategories.Business, LogLevel.Information, "test1");
                        logScope.Log(LogCategories.Technical, LogLevel.Trace, "test2");
                        Assert.AreEqual(1, this.LogMessages.Count);
                        Assert.AreEqual("Business, Information, /0004, NewScope - test1", this.LogMessages[0]);
                    }

                    LogScope.DefaultLevel = LogLevel.Trace;
                    await using (var logScope = LogScope.Create("NewScope", this.LogMethod))
                    {
                        this.LogMessages.Clear();
                        logScope.Log(LogCategories.Business, LogLevel.Information, "test1");
                        logScope.Log(LogCategories.Technical, LogLevel.Trace, "test2");
                        Assert.AreEqual(2, this.LogMessages.Count);
                        Assert.AreEqual("Business, Information, /0004, NewScope - test1", this.LogMessages[0]);
                        Assert.AreEqual("Technical, Trace, /0004, NewScope - test2", this.LogMessages[1]);
                    }
                }
                finally
                {
                    LogScope.DefaultLevel = level;
                }
            }
Example #7
0
        /// <summary>
        /// Entry point for the integration test program.
        /// </summary>
        /// <returns>A task to wait for.</returns>
        public static async Task Main()
        {
            var con = "Server=.;Database=master;Trusted_Connection=True;";

            await using var db = (IDatabase) new SqlDatabase(con);

            // setting up a very simple logging method.
            LogScope.LogMethod = LogScope.LogMethod
                                 .AddConsole()
                                 .AddDebug()
                                 .Batch(5);

            // create a logger (providing a logger is optional for IDatabase)
            await using var logger = LogScope.Create("DB Access");

            for (var i = 0; i < 10; i++)
            {
                // executing the SPROC and map the result to a simple anonymous type with just one property "Name"
                var enumerable = db.Execute(
                    "sys.sp_databases",
                    async reader => new
                {
                    Name = await reader.Get <string>(0).ConfigureAwait(false),
                },
                    logger);

                Console.WriteLine(await enumerable.CountAsync().ConfigureAwait(false));
            }
        }
Example #8
0
        /// <summary>
        /// Re-render a previously rendered raw msg in a JSON form
        /// </summary>
        /// <param name="logLevel"></param>
        /// <param name="eventId"></param>
        /// <param name="prerendered"></param>
        /// <param name="state"></param>
        /// <param name="includeScopes">true if instructed to include scopes</param>
        /// <param name="exception"></param>
        /// <param name="categoryName"></param>
        /// <param name="cfg"></param>
        /// <returns>JSON-form, with "msg" property bearing the original msg</returns>
        string IAugmentingRenderer.ReRender(LogLevel logLevel, EventId eventId, string prerendered, object state, bool includeScopes, Exception exception, string categoryName, IConfiguration cfg)
        {
            LogScope lsc = null;

            if (includeScopes)
            {
                lsc = LogScope.Current;
            }

            var scopes = lsc?.EnumerateScopes() ?? ImmutableList <object> .Empty;

            var(unaries, groupedPairs) = scopes.EvaluateLogstate();
            var taglist = string.Join(";", unaries);  //cloudwatch insights can search delimited taglist more easily than a proper JSON array.
            var obj     = new { logLevel, categoryName, msg = prerendered, exception, eventId, tags = taglist, scope = groupedPairs };

            using (var ms = new MemoryStream())
            {
                using (var sw = new StreamWriter(ms))
                {
                    _jss.Serialize(sw, obj);
                }

                return(Encoding.UTF8.GetString(ms.ToArray()));
            }
        }
Example #9
0
        public static IDisposable BeginScope(string category, string enterText, Func <string> exitText = null, bool writeBraces = false)
        {
            if (!IsEnabled)
            {
                return(new LogScope(null));
            }

            var startTime = _stopwatch.Elapsed;

            var scope = new LogScope(() =>
            {
                var elapsed = _stopwatch.Elapsed - startTime;

                _depth.Value--;
                if (exitText != null || writeBraces)
                {
                    Write(category, (writeBraces ? "} " : "") + (exitText?.Invoke() ?? "") + " (" + (int)elapsed.TotalMilliseconds + " ms)");
                }
            });

            if (enterText != null)
            {
                Write(category, enterText);
            }
            if (writeBraces)
            {
                Write(category, "{");
            }
            _depth.Value++;

            return(scope);
        }
        public override TestResult Execute(ITestExecutionContext context)
        {
            var logCollector = new LogScope();

            try
            {
                innerCommand.Execute(context);

                if (logCollector.AnyFailingLogs())
                {
                    var failingLog = logCollector.FailingLogs.First();
                    throw new UnhandledLogMessageException(failingLog);
                }

                if (logCollector.ExpectedLogs.Any())
                {
                    throw new UnexpectedLogMessageException(logCollector.ExpectedLogs.Peek());
                }
            }
            catch (Exception exception)
            {
                context.CurrentResult.RecordException(exception);
            }
            logCollector.Dispose();
            return(context.CurrentResult);
        }
Example #11
0
            public void ExplicitNullBasePathIsAccepted()
            {
                var basePath = LogScope.BasePath;

                LogScope.BasePath = null;
                using var target  = LogScope.Create("test");
                LogScope.BasePath = basePath;
            }
Example #12
0
 public async Task Clear()
 {
     LogScope.Information("Invoke");
     if (OnClear != null)
     {
         await OnClear();
     }
 }
Example #13
0
 public async Task Initialize()
 {
     LogScope.Information("Invoke");
     if (OnInitialize != null)
     {
         await OnInitialize();
     }
 }
Example #14
0
 public virtual async Task Initialize()
 {
     LogScope.Invoked();
     if (OnInitialize != null)
     {
         await OnInitialize();
     }
 }
Example #15
0
 public IDisposable BeginScope <TState>(TState state)
 {
     if (state == null)
     {
         throw new ArgumentNullException(nameof(state));
     }
     return(LogScope.Push(_category, state));
 }
Example #16
0
            public void DefaultMethodWillBeUsed()
            {
                var logs = new List <string>();

                LogScope.LogMethod = (categories, level, scope, message) => logs.Add(message);
                using var target   = LogScope.Create("test");
                Assert.AreEqual("test - Starting scope test in member DefaultMethodWillBeUsed of ClassLogScope.cs.", logs[0]);
            }
Example #17
0
 public virtual async Task Clear()
 {
     LogScope.Invoked();
     if (OnClear != null)
     {
         await OnClear();
     }
 }
Example #18
0
            public void LogsScopeStart()
            {
                using var logScope = LogScope.Create("NewScope", this.LogMethod);

                var expected = "Technical, Trace, /0004, NewScope - Starting scope NewScope in member LogsScopeStart of ClassLogScope.cs.";

                Assert.AreEqual(1, this.LogMessages.Count);
                Assert.AreEqual(expected, this.LogMessages[0]);
            }
Example #19
0
            public async Task AsyncDisposeCorrectlyLogsEndOfScope()
            {
                await using (var logScope = LogScope.Create("NewScope", this.LogMethod))
                {
                    this.LogMessages.Clear();
                }

                const string expected = "Technical, Trace, /0004, NewScope - Finished scope - Data: {\"scopeName\":\"NewScope\",\"ms\":";

                Assert.IsTrue(this.LogMessages[0].StartsWith(expected, StringComparison.Ordinal));
            }
Example #20
0
            public void ExplicitOverridesDefaultMethod()
            {
                var logs1 = new List <string>();
                var logs2 = new List <string>();

                void Log2(LogCategories categories, LogLevel level, LogScope scope, string message) => logs2.Add(message);

                LogScope.LogMethod = this.Log1;
                using var target   = LogScope.Create("test", Log2);
                Assert.AreEqual("test - Starting scope test in member ExplicitOverridesDefaultMethod of ClassLogScope.cs.", logs2[0]);
            }
Example #21
0
            public async Task ParametersAreCorrectlyLogged()
            {
                await using (var logScope = LogScope.Create("NewScope", this.LogMethod))
                {
                    this.LogMessages.Clear();
                    await using var subScope = logScope.MethodStart(new { this.LogMessages.Count, test = "true" });
                }

                Assert.AreEqual("Technical, Trace, /0004/0005, Method ParametersAreCorrectlyLogged - Starting scope Method ParametersAreCorrectlyLogged in member ParametersAreCorrectlyLogged of ClassLogScope.cs.", this.LogMessages[0]);
                Assert.AreEqual("Technical, Debug, /0004/0005, Method ParametersAreCorrectlyLogged - scope value:  - Data: {\"Count\":0,\"test\":\"true\"}", this.LogMessages[1]);
            }
Example #22
0
            public void StartingChildScopeAddsIdToHierarchy()
            {
                using var logScope = LogScope.Create("NewScope", this.LogMethod);
                this.LogMessages.Clear();

                using var target = logScope.Child("the child");
                const string expected = "Technical, Trace, /0004/0005, the child - Starting scope the child in member StartingChildScopeAddsIdToHierarchy of ClassLogScope.cs.";

                Assert.AreEqual(1, this.LogMessages.Count);
                Assert.AreEqual(expected, this.LogMessages[0]);
            }
Example #23
0
        static bool CheckExpectedLogs(LogScope logScope, TestResult result)
        {
            if (!logScope.ExpectedLogs.Any())
            {
                return(true);
            }

            var expectedLog = logScope.ExpectedLogs.Peek();

            result.RecordException(new UnexpectedLogMessageException(expectedLog));
            return(false);
        }
Example #24
0
            public void DefaultsToCorrectLevelAndCategory()
            {
                using var logScope = LogScope.Create("NewScope", this.LogMethod);
                this.LogMessages.Clear();

                Assert.AreEqual(0, this.LogMessages.Count);

                logScope.Log("Just a test");

                Assert.AreEqual(1, this.LogMessages.Count);
                Assert.AreEqual("Technical, Information, /0004, NewScope - Just a test", this.LogMessages[0]);
            }
Example #25
0
            public void LogsScopeEnd()
            {
                using (var logScope = LogScope.Create("NewScope", this.LogMethod))
                {
                    this.LogMessages.Clear();
                }

                var expected = "Technical, Trace, /0004, NewScope - Finished scope - Data: \\{\"scopeName\":\"NewScope\",\"ms\":\\d+\\.\\d+\\}";

                Assert.AreEqual(1, this.LogMessages.Count);
                Assert.IsTrue(Regex.IsMatch(this.LogMessages[0], expected));
            }
Example #26
0
        public override TestResult Execute(ITestExecutionContext context)
        {
            using (var logScope = new LogScope())
            {
                if (ExecuteAndCheckLog(logScope, context.CurrentResult, () => innerCommand.Execute(context)))
                {
                    PostTestValidation(logScope, innerCommand, context.CurrentResult);
                }
            }

            return(context.CurrentResult);
        }
Example #27
0
        static bool CheckFailingLogs(LogScope logScope, TestResult result)
        {
            if (!logScope.AnyFailingLogs())
            {
                return(true);
            }

            var failingLog = logScope.FailingLogs.First();

            result.RecordException(new UnhandledLogMessageException(failingLog));
            return(false);
        }
Example #28
0
 public void Execute(LogScope logScope)
 {
     try
     {
         if (typeof(ScriptableObject).IsAssignableFrom(m_RequestedType))
         {
             if (m_CurrentRunningTest != null && m_RequestedType != m_CurrentRunningTest.GetType())
             {
                 DestroyCurrentTestObjectIfExists();
             }
             if (m_CurrentRunningTest == null)
             {
                 if (m_StateSerializer.CanRestoreFromScriptableObject(m_RequestedType))
                 {
                     m_CurrentRunningTest = m_StateSerializer.RestoreScriptableObjectInstance();
                 }
                 else
                 {
                     m_CurrentRunningTest = ScriptableObject.CreateInstance(m_RequestedType);
                 }
             }
             m_Result = m_CurrentRunningTest;
         }
         else
         {
             DestroyCurrentTestObjectIfExists();
             m_Result = Activator.CreateInstance(m_RequestedType, m_Arguments);
             if (m_StateSerializer.CanRestoreFromJson(m_RequestedType))
             {
                 m_StateSerializer.RestoreClassFromJson(ref m_Result);
             }
         }
         if (logScope.AnyFailingLogs())
         {
             var failingLog = logScope.FailingLogs.First();
             throw new UnhandledLogMessageException(failingLog);
         }
         if (logScope.ExpectedLogs.Any())
         {
             throw new UnexpectedLogMessageException(LogScope.Current.ExpectedLogs.Peek());
         }
     }
     catch (Exception e)
     {
         m_Exception = e;
     }
     finally
     {
         m_RequestedType = null;
         m_Arguments     = null;
     }
 }
        protected string GetScopeString(LogScope scope)
        {
            StringBuilder builder      = new StringBuilder();
            var           scopeStrings = Enum.GetValues(typeof(LogScope)).Cast <LogScope>()?.Where(s => s == scope);

            if (scopeStrings != null)
            {
                return(string.Join(", ", scopeStrings));
            }
            else
            {
                return(null);
            }
        }
Example #30
0
        public object Delegate(Type type, object[] arguments)
        {
            AssertState();
            m_Context = UnityTestExecutionContext.CurrentContext;

            m_RequestedType = type;
            m_Arguments     = arguments;

            using (var logScope = new LogScope())
            {
                Execute(logScope);
            }

            return(HandleResult());
        }
Example #31
0
 public void Write(LogScope scope, Verbosity verbosity, string source, string text)
 {
     DateTime dt = DateTime.Now;
     string span = "";
     if(scope != null)
          span = (dt - scope.CreateDateTime).ToString();
     TreeIter iter = AppendValues(FindParentIter(scope), dt, (int)verbosity, verbosity.ToString(), text, source, span);
     TreePath path = store.GetPath(iter);
     view.ExpandToPath(path);
     view.ScrollToCell(path, view.Columns[1], false, 0.0f, 0.0f);
 }
Example #32
0
 TreeIter? FindParentIter(LogScope scope)
 {
     if(scope == null)
         return null;
     TreeIter? iter = null;
     if(scope_iters.TryGetValue(scope, out iter))
        return iter;
     LogScope s = scope;
     while(s.ParentScope != null)
     {
         s = s.ParentScope;
         if(scope_iters.TryGetValue(s, out iter))
             break;
     }
     if(iter != null)
         s = s.ChildScope;
     while(s != null && s.ParentScope != scope)
     {
         iter = AppendValues(iter, s.CreateDateTime, -1, "Skupina", s.Text, s.Source, "");
         s.Disposed += ScopeDisposed;
         scope_iters[s] = iter;
         s = s.ChildScope;
     }
     return iter;
 }