Example #1
0
        public override void Initialize(TestContext context, MethodInfo methodInfo, object[] testMethodArguments, ITestOutputHelper testOutputHelper)
        {
            base.Initialize(context, methodInfo, testMethodArguments, testOutputHelper);

            TestSink = new TestSink();
            LoggerFactory.AddProvider(new TestLoggerProvider(TestSink));
        }
Example #2
0
 internal static ResponseCachingContext CreateTestContext(ITestSink testSink)
 {
     return(new ResponseCachingContext(new DefaultHttpContext(), new TestLogger("ResponseCachingTests", testSink, true))
     {
         ResponseTime = DateTimeOffset.UtcNow
     });
 }
Example #3
0
        public LoggingTestWithoutHelpers(WebApplicationFactory <Startup> factory)
        {
            // Creates a sink that capture only log entry generated in our namespace
            _sink = new TestSink(x => x.LoggerName.StartsWith($"{nameof(SampleWebApplication)}."));

            // Wires the TestSink in the TestHost
            _factory = factory.WithWebHostBuilder(builder => builder.ConfigureLogging(logging => logging.AddProvider(new TestLoggerProvider(_sink))));
        }
Example #4
0
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
        public TestLoggerFactory(ITestSink sink)
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddLogging(builder => builder.AddTestLogger(sink));
            _serviceProvider = serviceCollection.BuildServiceProvider();
            _loggerFactory   = _serviceProvider.GetService <ILoggerFactory>();
        }
Example #5
0
 public virtual void Dispose()
 {
     if (!_disposedValue)
     {
         if (Sink != null)
         {
             Sink.CurrentScope = ParentScope;
         }
         Sink           = null;
         _disposedValue = true;
     }
 }
Example #6
0
        public void StartupErrorsAreLoggedIfCaptureStartupErrorsIsFalse()
        {
            ITestSink testSink = null;

            var builder = CreateWebHostBuilder()
                          .CaptureStartupErrors(false)
                          .Configure(app =>
            {
                testSink = app.ApplicationServices.GetRequiredService <ITestSink>();

                throw new InvalidOperationException("Startup exception");
            })
                          .UseServer(new TestServer());

            Assert.Throws <InvalidOperationException>(() => builder.Build().Start());

            Assert.NotNull(testSink);
            Assert.Contains(testSink.Writes, w => w.Exception?.Message == "Startup exception");
        }
 public static IWebHostBuilder UseTestLogging(this IWebHostBuilder builder, ITestSink sink)
 => builder.ConfigureLogging(logging => logging.AddTestLogger(sink));
 public TestLogger(string name, ITestSink sink, bool enabled)
     : this(name, sink, (Func <LogLevel, bool>)(_ => enabled))
 {
 }
        public static void VerifyEventLogEvent(ITestSink testSink, string expectedRegexMatchString)
        {
            var eventLogRegex = new Regex($"Event Log: {expectedRegexMatchString}");

            Assert.Contains(testSink.Writes, context => eventLogRegex.IsMatch(context.Message));
        }
Example #10
0
 public static ILoggingBuilder AddTestLogger(this ILoggingBuilder builder, ITestSink sink)
 {
     builder.Services.TryAddSingleton(sink);
     return(builder.AddProvider(new TestLoggerProvider(sink)));
 }
 public TestLogger(string name, ITestSink sink, bool enabled)
     : this(name, sink, _ => enabled)
 {
 }
 public TestLoggerFactory(ITestSink sink, bool enabled)
 {
     _sink    = sink;
     _enabled = enabled;
 }
Example #13
0
 public TestLogger(string name, ITestSink sink)
     : this(name, sink, _ => true)
 {
 }
 public TestLogger(string name, ITestSink sink, bool enabled)
 {
     _sink    = sink;
     _name    = name;
     _enabled = enabled;
 }
Example #15
0
 public TestLoggerFactory(ITestSink sink)
 {
     _sink = sink ?? throw new ArgumentNullException(nameof(sink));
 }
Example #16
0
 public LoggingTest(WebApplicationFactory <Startup> factory)
 {
     _sink    = MELTBuilder.CreateTestSink(options => options.FilterByNamespace(nameof(SampleWebApplication)));
     _factory = factory.WithWebHostBuilder(builder => builder.UseTestLogging(_sink));
 }
Example #17
0
 public TestLogger(string name, ITestSink sink)
 {
     Name  = name ?? throw new ArgumentNullException(nameof(name));
     _sink = sink ?? throw new ArgumentNullException(nameof(sink));
 }
Example #18
0
 public TestLogger(string name, ITestSink sink, Func <LogLevel, bool>?filter = null)
 {
     _sink   = sink ?? throw new ArgumentNullException(nameof(sink));
     Name    = name ?? throw new ArgumentNullException(nameof(name));
     _filter = filter;
 }
Example #19
0
 public TestLoggerProvider()
 {
     _sink = new TestSink();
 }
 /// <summary>
 /// Creats the provider and inject the ITestSink but also creates a filter for the registerd logs
 /// </summary>
 /// <param name="testSink"><see cref="ITestSink"/></param>
 /// <param name="filter">the filter for the registered logs on ITestSink</param>
 public TestLoggerProvider(ITestSink testSink, Func <LogLevel, bool> filter)
 {
     Sink    = testSink;
     _filter = filter;
 }
Example #21
0
 public TestLoggerProvider(ITestSink sink)
 {
     _sink = sink;
 }
 /// <summary>
 /// Creates the provider and inject the ITestSink
 /// </summary>
 /// <param name="testSink"><see cref="ITestSink"/></param>
 /// <param name="isEnabled">enable or not the logger</param>
 public TestLoggerProvider(ITestSink testSink, bool isEnabled) : this(testSink, _ => isEnabled)
 {
 }
Example #23
0
 public TestLoggerFactory(ITestSink sink)
 {
     _sink = sink;
 }
 public TestLogger(string name, ITestSink sink, Func <LogLevel, bool> filter)
 {
     _sink   = sink;
     _name   = name;
     _filter = filter;
 }
Example #25
0
        public static void VerifyEventLogEvent(IISDeploymentResult deploymentResult, ITestSink testSink, string expectedRegexMatchString)
        {
            Assert.True(deploymentResult.HostProcess.HasExited);

            var builder = new StringBuilder();

            foreach (var context in testSink.Writes)
            {
                builder.Append(context.Message);
            }

            var count         = 0;
            var expectedRegex = new Regex(expectedRegexMatchString, RegexOptions.Singleline);

            foreach (Match match in EventLogRegex.Matches(builder.ToString()))
            {
                var eventLogText = match.Groups["EventLogMessage"].Value;
                if (expectedRegex.IsMatch(eventLogText))
                {
                    count++;
                }
            }

            Assert.True(count > 0, $"'{expectedRegexMatchString}' didn't match any event log messaged");
            Assert.True(count < 2, $"'{expectedRegexMatchString}' matched more then one event log message");

            var eventLog = new EventLog("Application");

            // Eventlog is already sorted based on time of event in ascending time.
            // Check results in reverse order.
            var expectedRegexEventLog = new Regex(expectedRegexMatchString);
            var processIdString       = $"Process Id: {deploymentResult.HostProcess.Id}.";

            // Event log messages round down to the nearest second, so subtract a second
            var processStartTime = deploymentResult.HostProcess.StartTime.AddSeconds(-1);

            for (var i = eventLog.Entries.Count - 1; i >= 0; i--)
            {
                var eventLogEntry = eventLog.Entries[i];
                if (eventLogEntry.TimeGenerated < processStartTime)
                {
                    // If event logs is older than the process start time, we didn't find a match.
                    break;
                }

                if (eventLogEntry.ReplacementStrings == null ||
                    eventLogEntry.ReplacementStrings.Length < 3)
                {
                    continue;
                }

                // ReplacementStings == EventData collection in EventLog
                // This is unaffected if event providers are not registered correctly
                if (eventLogEntry.Source == AncmVersionToMatch(deploymentResult) &&
                    processIdString == eventLogEntry.ReplacementStrings[1] &&
                    expectedRegex.IsMatch(eventLogEntry.ReplacementStrings[0]))
                {
                    return;
                }
            }

            Assert.True(false, $"'{expectedRegexMatchString}' didn't match any event log messaged.");
        }
Example #26
0
 public override void SetUp()
 {
     base.SetUp();
     _testSink = new RemoteTestDiscoverySink(BinaryWriter);
 }
 private static void AssertLogMessage(ITestSink sink, string logMesage, LogLevel logLevel) =>
 sink.Writes.Any(x => x.Message.Contains(logMesage, StringComparison.InvariantCultureIgnoreCase) && x.LogLevel == logLevel)
 .Should().BeTrue();