Ejemplo n.º 1
0
        public void FormatReturnsValueWithPadding(int scopeLevel)
        {
            var config       = new LoggingConfig();
            var padding      = new string(' ', config.ScopePaddingSpaces *scopeLevel);
            var categoryName = Guid.NewGuid().ToString();
            var logLevel     = LogLevel.Information;
            var eventId      = Model.Create <EventId>();
            var message      = Guid.NewGuid().ToString();
            var exception    = new ArgumentNullException(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());

            var sut = new DefaultFormatter(config);

            var actual = sut.Format(scopeLevel, categoryName, logLevel, eventId, message, exception);

            _output.WriteLine(actual);

            if (scopeLevel > 0)
            {
                actual.Should().StartWith(padding);
            }
            else
            {
                actual.Should().NotStartWith(" ");
            }
        }
Ejemplo n.º 2
0
        static ContextObject()
        {
            DefaultFormatter = MorestachioFormatterService.Default;
            DefaultFormatter.AddFromType(typeof(ObjectFormatter));
            DefaultFormatter.AddFromType(typeof(Number));
            DefaultFormatter.AddFromType(typeof(BooleanFormatter));
            DefaultFormatter.AddFromType(typeof(DateFormatter));
            DefaultFormatter.AddFromType(typeof(EqualityFormatter));
            DefaultFormatter.AddFromType(typeof(LinqFormatter));
            DefaultFormatter.AddFromType(typeof(ListExtensions));
            DefaultFormatter.AddFromType(typeof(RegexFormatter));
            DefaultFormatter.AddFromType(typeof(TimeSpanFormatter));
            DefaultFormatter.AddFromType(typeof(StringFormatter));
            DefaultFormatter.AddFromType(typeof(RandomFormatter));
            DefaultFormatter.AddFromType(typeof(Worktime));
            DefaultFormatter.AddFromType(typeof(Money));
            DefaultFormatter.AddFromType(typeof(HtmlFormatter));
            DefaultFormatter.AddFromType(typeof(LoggingFormatter));

            DefaultDefinitionOfFalse = value => value != null &&
                                       value as bool? != false &&
                                       // ReSharper disable once CompareOfFloatsByEqualityOperator
                                       value as double? != 0 &&
                                       value as int? != 0 &&
                                       value as string != string.Empty &&
                                       // We've gotten this far, if it is an object that does NOT cast as enumberable, it exists
                                       // OR if it IS an enumerable and .Any() returns true, then it exists as well
                                       (!(value is IEnumerable) || ((IEnumerable)value).Cast <object>().Any()
                                       );
            DefinitionOfFalse = DefaultDefinitionOfFalse;
        }
Ejemplo n.º 3
0
        /// <summary>
        ///     Parses the current object by using the given argument
        /// </summary>
        public async Task <object> Format(string name, KeyValuePair <string, object>[] argument)
        {
            await EnsureValue();

            var retval = Value;

            if (Value == null)
            {
                return(retval);
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                name = null;
            }

            //call formatters that are given by the Options for this run
            retval = await Options.Formatters.CallMostMatchingFormatter(Value.GetType(), argument, Value, name);

            if (!Equals(retval, MorestachioFormatterService.FormatterFlow.Skip))
            {
                //one formatter has returned a valid value so use this one.
                return(retval);
            }

            //all formatters in the options object have rejected the value so try use the global ones
            retval = await DefaultFormatter.CallMostMatchingFormatter(Value.GetType(), argument, Value, name);

            if (!Equals(retval, MorestachioFormatterService.FormatterFlow.Skip))
            {
                return(retval);
            }
            return(Value);
        }
Ejemplo n.º 4
0
        public void FormatHidesSensitiveDataInException(string?sensitiveValue, string message, string expected)
        {
            var config       = new LoggingConfig();
            var scopeLevel   = 1;
            var categoryName = Guid.NewGuid().ToString();
            var logLevel     = LogLevel.Information;
            var eventId      = Model.Create <EventId>();
            var logMessage   = Guid.NewGuid().ToString();
            var exception    = new InvalidOperationException(message);

            if (sensitiveValue != null)
            {
                config.SensitiveValues.Add(sensitiveValue);
            }

            var sut = new DefaultFormatter(config);

            var actual = sut.Format(scopeLevel, categoryName, logLevel, eventId, logMessage, exception);

            actual.Should().Contain(expected);

            if (sensitiveValue != null)
            {
                actual.Should().NotContain(sensitiveValue);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        ///     Parses the current object by using the given argument
        /// </summary>
        /// <param name="argument"></param>
        /// <returns></returns>
        public async Task <object> Format(KeyValuePair <string, object>[] argument)
        {
            await EnsureValue();

            var retval = Value;

            if (Value == null)
            {
                return(retval);
            }

            //call formatters that are given by the Options for this run
            retval = await Options.Formatters.CallMostMatchingFormatter(Value.GetType(), argument, Value);

            if ((retval as FormatterMatcher.FormatterFlow) != FormatterMatcher.FormatterFlow.Skip)
            {
                //one formatter has returned a valid value so use this one.
                return(retval);
            }

            //all formatters in the options object have rejected the value so try use the global ones
            retval = await DefaultFormatter.CallMostMatchingFormatter(Value.GetType(), argument, Value);

            if ((retval as FormatterMatcher.FormatterFlow) != FormatterMatcher.FormatterFlow.Skip)
            {
                return(retval);
            }
            return(Value);
        }
Ejemplo n.º 6
0
        public void OnTearDown()
        {
            _formatter  = null;
            _fakeLogger = null;
            _testObject = null;

            Log.CompoundLogger.ClearLoggers();
        }
Ejemplo n.º 7
0
        private static CommandLineApplication ConfigureApplication()
        {
            var app = new CommandLineApplication();

            app.Name        = "grep.core";
            app.Description = "Intelligent grep in .NET Core";

            app.HelpOption();
            app.ThrowOnUnexpectedArgument     = false;
            app.MakeSuggestionsInErrorMessage = true;
            app.VersionOptionFromAssemblyAttributes(Assembly.GetExecutingAssembly());

            var regexp          = app.Option("-e|--regexp", "Pattern to search for", CommandOptionType.SingleValue).IsRequired();
            var isSimplePattern = app.Option("-F|--fixed-strings", "Interpret pattern as a fixed string not a regular expression", CommandOptionType.NoValue);
            var recurse         = app.Option("-r|--recursive", "Read all files under each directory, recursively", CommandOptionType.NoValue);
            var ignoreCase      = app.Option("-i|--ignore-case", "Ignore case distinctions in both the pattern and the input files", CommandOptionType.NoValue);
            var listFileMatches = app.Option("-l|--files-with-matches", $"Suppress normal output; instead print the name of each input file{Environment.NewLine}from which output would normally have been printed", CommandOptionType.NoValue);
            var ignoreBinary    = app.Option("-I", "Process a binary file as if it did not contain matching data", CommandOptionType.NoValue);
            var excludeDir      = app.Option("--exclude-dir", "Exclude directories matching the pattern from recursive searches", CommandOptionType.SingleValue);

            var file = app.Argument("FILE", "Input files to search", multipleValues: true).IsRequired();

            app.OnExecuteAsync(async cancellationToken =>
            {
                var sw = Stopwatch.StartNew();

                var fileProviders = file.Values.Select(x => (IFileProvider) new DefaultFileProvider(x, recurse.HasValue(), excludeDir.Value())).ToList();

                var matcher = isSimplePattern.HasValue() ? (ITextMatcher) new SimpleMatcher(regexp.Value(), ignoreCase.HasValue()) : (ITextMatcher) new RegexMatcher(regexp.Value(), ignoreCase.HasValue());

                var formatter = new DefaultFormatter();

                var results = new ResultInfo();

                var printTask = PrintResults(results, formatter, listFileMatches.HasValue(), cancellationToken);

                var processTask = ProcessFiles(fileProviders, matcher, results, ignoreBinary.HasValue(), cancellationToken);

                await Task.WhenAll(printTask, processTask).ContinueWith(
                    t =>
                {
                    sw.Stop();
                    Write($"{results.MatchedFiles} file(s)", ConsoleColor.Yellow);
                    Write(" with ", ConsoleColor.DarkGray);
                    Write($"{results.TotalMatches} match(es)", ConsoleColor.Blue);
                    WriteLine($" in {results.TotalFiles} file(s) in {sw.Elapsed:g}", ConsoleColor.DarkGray);

                    if (Debugger.IsAttached)
                    {
                        Console.WriteLine("Press any key to continue...");
                        Console.ReadKey(true);
                    }
                },
                    cancellationToken);
            });

            return(app);
        }
Ejemplo n.º 8
0
        public void OnSetup()
        {
            _formatter  = new DefaultFormatter();
            _fakeLogger = new FakeLogger();
            _testObject = new object();

            Log.CompoundLogger.ClearLoggers();
            Log.CompoundLogger.SetLoggers(_fakeLogger);
        }
        private InfluxdbFormatter GetDefaultFormatter()
        {
            var formatter = new DefaultFormatter(false, null);

            formatter.ContextNameFormatter = null;
            formatter.MetricNameFormatter  = null;
            formatter.TagKeyFormatter      = null;
            formatter.FieldKeyFormatter    = null;
            return(formatter);
        }
Ejemplo n.º 10
0
        public void FormatTotal_ReturnsOriginalString()
        {
            var formatter = new DefaultFormatter();
            var testSb    = new StringBuilder("test");

            formatter.FormatTotal(testSb);

            var result = testSb.ToString();

            Assert.AreEqual(result, "test");
        }
Ejemplo n.º 11
0
        public void FormatTax_ReturnsWithNewLine()
        {
            var formatter = new DefaultFormatter();
            var testSb    = new StringBuilder("test");

            formatter.FormatTax(testSb);

            var result = testSb.ToString();

            Assert.AreEqual(result, $"test{Environment.NewLine}");
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Pick the best available formatter to format the given piece of code.
        /// </summary>
        /// <param name="code">The code to be formatted. This parameter cannot be null.</param>
        /// <param name="language">
        /// The language into which code has been written. Ex: "C#", "Java".
        /// If no such formatter is available, a default formatting is applied.
        /// This parameter cannot be null.
        /// </param>
        /// <returns>
        /// The formatting for this piece of code.
        /// </returns>
        public FormattedCode Format(string code, string language)
        {
            UiExceptionHelper.CheckNotNull(code, "code");
            UiExceptionHelper.CheckNotNull(language, "language");

            if (_formatters.HasLanguage(language))
            {
                return(_formatters[language].Format(code));
            }

            return(DefaultFormatter.Format(code));
        }
Ejemplo n.º 13
0
        /// <summary>
        /// A convenient method to make the formatting of a piece of code when
        /// only the file extension is known.
        /// </summary>
        /// <param name="code">The piece of code to be formatted. This parameter
        /// cannot be null.</param>
        /// <param name="extension">The file extension associated to this piece of code.
        /// Ex: "cs", "cpp". This is used to pick the formatter assigned to. If no such
        /// formatter exists, the default one is picked up.</param>
        /// <returns>The FormattedCode for this piece of code.</returns>
        public FormattedCode FormatFromExtension(string code, string extension)
        {
            UiExceptionHelper.CheckNotNull(code, "code");
            UiExceptionHelper.CheckNotNull(extension, "extension");

            if (_formatters.HasExtension(extension))
            {
                return(_formatters.GetFromExtension(extension).Format(code));
            }

            return(DefaultFormatter.Format(code));
        }
Ejemplo n.º 14
0
        public int Execute()
        {
            DefaultFormatter formatter = new DefaultFormatter("fr");

            Console.WriteLine(formatter.DateHumanize_Now());
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()
                     .Where(a => a.GetName().Name.StartsWith("Humanizer")))
            {
                Console.WriteLine($"{assembly.FullName} from {assembly.Location}");
            }

            return(0);
        }
Ejemplo n.º 15
0
        public void FormatReturnsEmptyWhenMessageIsNullEmptyOrWhiteSpace(string message)
        {
            var config       = new LoggingConfig().Set(x => x.ScopePaddingSpaces = 2);
            var scopeLevel   = 1;
            var categoryName = Guid.NewGuid().ToString();
            var logLevel     = LogLevel.Information;
            var eventId      = Model.Create <EventId>();

            var sut = new DefaultFormatter(config);

            var actual = sut.Format(scopeLevel, categoryName, logLevel, eventId, message, null);

            actual.Should().BeEmpty();
        }
Ejemplo n.º 16
0
        public void FormatMethodEntry_HideTimeStampInMethodIsSet_ExpectedTextIsReturned()
        {
            // Arrange
            var filters      = LogFiltersBuilder.Create().WithTimeStampInMethodHidden().Build();
            var formatter    = new DefaultFormatter();
            var entry        = new MethodEntry(1, "Yalf.TestMethod", new[] { "param1", "param2" }, DateTime.Parse("2022-10-22 22:22:31.678"));
            var expectedText = "[Enter] Yalf.TestMethod(param1, param2)";

            // Act
            var outputText = formatter.FormatMethodEntry(22, 1, 33, entry, filters, true);

            // Assert
            Assert.That(outputText, Is.Not.Empty, "Expected a string to be returned");
            Assert.That(outputText, Is.EqualTo(expectedText), "Not the expected output text, you may need to adjust the test if the formatter has been changed.");
        }
Ejemplo n.º 17
0
        public void FormatMethodExit_ReturnRecordedIsFalse_ExpectedTextIsReturned()
        {
            // Arrange
            var filters      = this.GetDefaultFilters();
            var formatter    = new DefaultFormatter();
            var entry        = new MethodExit(1, "Yalf.TestMethod", 345, false, "returnVal");
            var expectedText = "[Exit] Yalf.TestMethod() duration 345ms";

            // Act
            var outputText = formatter.FormatMethodExit(22, 1, 33, entry, filters, true);

            // Assert
            Assert.That(outputText, Is.Not.Empty, "Expected a string to be returned");
            Assert.That(outputText, Is.EqualTo(expectedText), "Not the expected output text, you may need to adjust the test if the formatter has been changed.");
        }
Ejemplo n.º 18
0
        public void FormatMethodExit_HideMethodReturnValueIsSet_ExpectedTextIsReturned()
        {
            // Arrange
            var filters      = LogFiltersBuilder.Create().WithMethodReturnValueHidden().Build();
            var formatter    = new DefaultFormatter();
            var entry        = new MethodExit(1, "Yalf.TestMethod", 345, true, "returnVal");
            var expectedText = "[Exit] Yalf.TestMethod() duration 345ms";

            // Act
            var outputText = formatter.FormatMethodExit(22, 1, 33, entry, filters, true);

            // Assert
            Assert.That(outputText, Is.Not.Empty, "Expected a string to be returned");
            Assert.That(outputText, Is.EqualTo(expectedText), "Not the expected output text, you may need to adjust the test if the formatter has been changed.");
        }
Ejemplo n.º 19
0
        public void FormatLogEvent_ValidLog_ExpectedTextIsReturned()
        {
            // Arrange
            var filters   = this.GetDefaultFilters();
            var formatter = new DefaultFormatter();
            var entry     = new LogEvent(LogLevel.Info, DateTime.Parse("2022-10-22 22:22:31.678"), "This is a log entry");

            var expectedText = "[Log] [Info] This is a log entry";

            // Act
            var outputText = formatter.FormatLogEvent(22, 1, 33, entry, filters, true);

            // Assert
            Assert.That(outputText, Is.Not.Empty, "Expected a string to be returned");
            Assert.That(outputText, Is.EqualTo(expectedText), "Not the expected output text, you may need to adjust the test if the formatter has been changed.");
        }
Ejemplo n.º 20
0
        public void FormatReturnsValueWithLogLevel(LogLevel logLevel)
        {
            var config       = new LoggingConfig();
            var scopeLevel   = 1;
            var eventId      = Model.Create <EventId>();
            var message      = Guid.NewGuid().ToString();
            var categoryName = Guid.NewGuid().ToString();

            var sut = new DefaultFormatter(config);

            var actual = sut.Format(scopeLevel, categoryName, logLevel, eventId, message, null);

            _output.WriteLine(actual);

            actual.Should().Contain(logLevel.ToString());
        }
Ejemplo n.º 21
0
        public void FormatReturnsValueWithoutException()
        {
            var config     = new LoggingConfig();
            var scopeLevel = 1;
            var name       = Guid.NewGuid().ToString();
            var logLevel   = LogLevel.Information;
            var eventId    = Model.Create <EventId>();
            var message    = Guid.NewGuid().ToString();

            var sut = new DefaultFormatter(config);

            var actual = sut.Format(scopeLevel, name, logLevel, eventId, message, null);

            _output.WriteLine(actual);

            actual.Should().NotContain("Exception");
        }
Ejemplo n.º 22
0
        protected virtual string Format(object value, string format, string language)
        {
            if (_formatters != null)
            {
                for (var i = 0; i < _formatters.Count; i++)
                {
                    var formatter = _formatters[i];

                    if (formatter.CanFormat(value, format, language))
                    {
                        return(formatter.Format(value, format, language));
                    }
                }
            }

            return(DefaultFormatter.Format(value, format, language));
        }
Ejemplo n.º 23
0
        public void FormatException_ValidLog_ExpectedTextIsReturned()
        {
            // Arrange
            var filters   = this.GetDefaultFilters();
            var formatter = new DefaultFormatter();
            var ex        = this.GenerateExceptionWithStackTrace();
            var entry     = new ExceptionTrace(ex, DateTime.Parse("2022-10-22 22:22:31.678"));

            var expectedText = "[Exception] 22:22:31.678 Attempted to divide by zero.";

            // Act
            var outputText = formatter.FormatException(22, 1, 33, entry, filters);

            // Assert
            Assert.That(outputText, Is.Not.Empty, "Expected a string to be returned");
            Assert.That(outputText, Is.EqualTo(expectedText), "Not the expected output text, you may need to adjust the test if the formatter has been changed.");
        }
Ejemplo n.º 24
0
        public void FormatReturnsValueWithoutName()
        {
            var config       = new LoggingConfig();
            var scopeLevel   = 1;
            var categoryName = Guid.NewGuid().ToString();
            var logLevel     = LogLevel.Information;
            var eventId      = Model.Create <EventId>();
            var message      = Guid.NewGuid().ToString();
            var exception    = new ArgumentNullException(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());

            var sut = new DefaultFormatter(config);

            var actual = sut.Format(scopeLevel, categoryName, logLevel, eventId, message, exception);

            _output.WriteLine(actual);

            actual.Should().NotContain(categoryName);
        }
Ejemplo n.º 25
0
        public void FormatThread_ValidLogWithBlankThreadName_ExpectedTextIsReturned()
        {
            // Arrange
            var filters   = this.GetDefaultFilters();
            var formatter = new DefaultFormatter();

            var entry1 = new MethodEntry(1, "Yalf.TestMethod", new[] { "param1", "param2" }, DateTime.Parse("2022-10-22 22:22:31.678"));
            var entry2 = new MethodExit(1, "Yalf.TestMethod", 345, true, "returnVal");
            var entry  = new ThreadData(22, String.Empty, new BaseEntry[] { entry1, entry2 });

            var expectedText = "[Thread 22]";

            // Act
            var outputText = formatter.FormatThread(entry, filters);

            // Assert
            Assert.That(outputText, Is.Not.Empty, "Expected a string to be returned");
            Assert.That(outputText, Is.EqualTo(expectedText), "Not the expected output text, you may need to adjust the test if the formatter has been changed.");
        }
Ejemplo n.º 26
0
        static async Task MainAsync(string[] args)
        {
            var         searchTerm = new SearchTerm(args);
            var         searchers  = GetSearchers();
            ICalculator calculator = new DefaultCalculator();
            var         searcher   = new SearchService(searchTerm, searchers, calculator);

            await searcher.Search();

            IFormatter formatter = new DefaultFormatter();
            var        sb        = new StringBuilder();

            sb.Append(formatter.FormatResultsPerTerm(searcher.ResultsPerTerm));
            sb.Append(formatter.FormatWinnersPerEngine(searcher.WinnersPerEngine));
            sb.Append(formatter.FormatTotalWinner(searcher.TotalWinner));

            Console.WriteLine(sb);
            Console.ReadLine();
        }
Ejemplo n.º 27
0
        public void FormatHidesSensitiveDataInMessage(string?sensitiveValue, string message, string expected)
        {
            var config       = new LoggingConfig();
            var scopeLevel   = 1;
            var categoryName = Guid.NewGuid().ToString();
            var logLevel     = LogLevel.Information;
            var eventId      = Model.Create <EventId>();

            if (sensitiveValue != null)
            {
                config.SensitiveValues.Add(sensitiveValue);
            }

            var sut = new DefaultFormatter(config);

            var actual = sut.Format(scopeLevel, categoryName, logLevel, eventId, message, null);

            actual.Should().Be($"   Information [{eventId.Id}]: {expected}");
        }
Ejemplo n.º 28
0
        public async Task <object> Format(KeyValuePair <string, object>[] argument)
        {
            await EnsureValue();

            var retval = Value;

            if (Value == null)
            {
                return(retval);
            }

            var name = argument.FirstOrDefault().Value?.ToString();
            var argumentWithoutName = argument.Skip(1).ToArray();

            //call formatters that are given by the Options for this run
            retval = await Options.Formatters.CallMostMatchingFormatter(Value.GetType(), argumentWithoutName, Value, name);

            if (!Equals(retval, MorestachioFormatterService.FormatterFlow.Skip))
            {
                //one formatter has returned a valid value so use this one.
                return(retval);
            }

            //call formatters that are given by the Options for this run
            retval = await Options.Formatters.CallMostMatchingFormatter(Value.GetType(), argument, Value, null);

            if (!Equals(retval, MorestachioFormatterService.FormatterFlow.Skip))
            {
                //one formatter has returned a valid value so use this one.
                return(retval);
            }

            //all formatters in the options object have rejected the value so try use the global ones
            retval = await DefaultFormatter.CallMostMatchingFormatter(Value.GetType(), argument, Value, null);

            if (!Equals(retval, MorestachioFormatterService.FormatterFlow.Skip))
            {
                return(retval);
            }
            return(Value);
        }
Ejemplo n.º 29
0
        public void FormatIncludesNewLineBetweenMessageAndException(string message, bool exceptionExists)
        {
            var       config       = new LoggingConfig();
            var       scopeLevel   = 1;
            var       categoryName = Guid.NewGuid().ToString();
            var       logLevel     = LogLevel.Information;
            var       eventId      = Model.Create <EventId>();
            Exception?exception    = exceptionExists
                ? new ArgumentNullException(Guid.NewGuid().ToString(), Guid.NewGuid().ToString())
                : null;

            var sut = new DefaultFormatter(config);

            var actual = sut.Format(scopeLevel, categoryName, logLevel, eventId, message, exception);

            actual.Should().NotStartWith(Environment.NewLine);
            actual.Should().NotEndWith(Environment.NewLine);

            if (string.IsNullOrWhiteSpace(message))
            {
                if (exception != null)
                {
                    actual.Should().Be($"   Information [{eventId.Id}]: {exception}");
                }
                else
                {
                    actual.Should().BeEmpty();
                }
            }
            else if (exception != null)
            {
                actual.Should()
                .Be(
                    $"   Information [{eventId.Id}]: stuff{Environment.NewLine}   Information [{eventId.Id}]: {exception}");
            }
            else
            {
                actual.Should().Be($"   Information [{eventId.Id}]: stuff");
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        ///     Gets an FormatterCache from ether the custom formatter or the global one
        /// </summary>
        public virtual FormatterCache PrepareFormatterCall(Type type,
                                                           string name,
                                                           FormatterArgumentType[] arguments,
                                                           ScopeData scopeData)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                name = null;
            }

            //call formatters that are given by the Options for this run
            var cache = scopeData.ParserOptions.Formatters.PrepareCallMostMatchingFormatter(type, arguments, name, scopeData.ParserOptions, scopeData);

            if (cache != null)
            {
                //one formatter has returned a valid value so use this one.
                return(cache);
            }

            //all formatters in the options object have rejected the value so try use the global ones
            return(DefaultFormatter.PrepareCallMostMatchingFormatter(type, arguments, name, scopeData.ParserOptions, scopeData));
        }