<commit_before>﻿// -----------------------------------------------------------------------
// <copyright file="ApplicationInsightsAppenderTests.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. 
// All rights reserved.  2013
// </copyright>
// -----------------------------------------------------------------------

namespace Microsoft.ApplicationInsights.Log4NetAppender.Tests
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;

    using log4net;
    using log4net.Config;
    using log4net.Util;

    using Microsoft.ApplicationInsights.Channel;
    using Microsoft.ApplicationInsights.DataContracts;
    using Microsoft.ApplicationInsights.Extensibility;
    using Microsoft.ApplicationInsights.Log4NetAppender;
    using Microsoft.ApplicationInsights.Tracing.Tests;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [System.Diagnostics.CodeAnalysis.SuppressMessage(
        category: "Microsoft.Design", checkId: "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Disposing the object in the Test Cleanup")]
    [TestClass]
    public class ApplicationInsightsAppenderTests
    {
        private AdapterHelper adapterHelper;
        private AppendableLogger appendableLogger;

        [TestInitialize]
        public void Initialize()
        {
            this.adapterHelper = new AdapterHelper();
            this.appendableLogger = new AppendableLogger();
        }

        [TestCleanup]
        public void Cleanup()
        {
            this.adapterHelper.Dispose();
            this.appendableLogger.Dispose();
            TelemetryConfiguration.Active.Dispose();
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void InitializeAppenderNotFailingWhenInstrumentionKeyIsEmptyString()
        {
            this.VerifyInitializationSuccess(
                () => ApplicationInsightsAppenderTests.InitializeLog4NetAIAdapter(@"<InstrumentationKey value="""" />"),
                string.Empty);
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void InitializeAppenderDoesNotThrowLogExceptionWhenInstrumentationKeyIsCorrect()
        {
            string instrumentationKey = Guid.NewGuid().ToString();
            this.VerifyInitializationSuccess(
                    () => ApplicationInsightsAppenderTests.InitializeLog4NetAIAdapter(string.Format(@"<InstrumentationKey value=""{0}"" />", instrumentationKey)),
                    instrumentationKey);
        }
        
        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void ValidateLoggingIsWorking()
        {
            string instrumentationKey = "93d9c2b7-e633-4571-8520-d391511a1df5";
            ApplicationInsightsAppenderTests.InitializeLog4NetAIAdapter(string.Format(@"<InstrumentationKey value=""{0}"" />", instrumentationKey));

            // Set up error handler to intercept exception
            ApplicationInsightsAppender aiAppender = (ApplicationInsightsAppender)log4net.LogManager.GetRepository().GetAppenders()[0];
            log4net.Util.OnlyOnceErrorHandler errorHandler = new log4net.Util.OnlyOnceErrorHandler();
            aiAppender.ErrorHandler = errorHandler;
            
            // Log something
            ILog logger = log4net.LogManager.GetLogger("TestAIAppender");
            for (int i = 0; i < 1500; i++)
            {
                logger.Debug("Trace Debug" + i + DateTime.Now);
            }

            Assert.AreEqual(instrumentationKey, aiAppender.TelemetryClient.Context.InstrumentationKey);
            Assert.IsNull(errorHandler.Exception);
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void TracesAreEnqueuedInChannel()
        {
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;

            ApplicationInsightsAppenderTests.InitializeLog4NetAIAdapter(string.Empty);
            this.SendMessagesToMockChannel(this.adapterHelper.InstrumentationKey);
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void InstrumentationKeyCanBeOverridden()
        {
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;

            // Set instrumentation key in Log4Net environment
            string instrumentationKey = "93d9c2b7-e633-4571-8520-d391511a1df5";
            ApplicationInsightsAppenderTests.InitializeLog4NetAIAdapter(string.Format(@"<InstrumentationKey value=""{0}"" />", instrumentationKey));
            Assert.AreNotEqual(instrumentationKey, this.adapterHelper.InstrumentationKey, "This test will not verify anything if the same instrumentation key is used by both");
            this.SendMessagesToMockChannel(instrumentationKey);
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void Log4NetAddsCustomPropertiesToTraceTelemetry()
        {
            ApplicationInsightsAppenderTests.InitializeLog4NetAIAdapter(string.Empty);
            this.VerifyPropertiesInTelemetry();
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void Log4NetSetsTimespamp()
        {
            this.appendableLogger.Logger.Debug("Trace Debug");

            var sentItems = this.appendableLogger.SentItems;
            Assert.AreEqual(1, sentItems.Length);

            var telemetry = (TraceTelemetry)sentItems[0];
            Assert.AreNotEqual(default(DateTimeOffset), telemetry.Timestamp);
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void Log4NetSetsUser()
        {
            this.appendableLogger.Logger.Debug("Trace Debug");

            var sentItems = this.appendableLogger.SentItems;
            Assert.AreEqual(1, sentItems.Length);

            var telemetry = (TraceTelemetry)sentItems[0];
            Assert.IsNotNull(default(DateTimeOffset), telemetry.Context.User.Id);
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void Log4NetAddsCustomProperties()
        {
            GlobalContext.Properties["CustomProperty1"] = "Value1";

            this.appendableLogger.Logger.Debug("Trace Debug");<commit_msg>Fix unit test<commit_after>﻿// -----------------------------------------------------------------------
// <copyright file="ApplicationInsightsAppenderTests.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. 
// All rights reserved.  2013
// </copyright>
// -----------------------------------------------------------------------

namespace Microsoft.ApplicationInsights.Log4NetAppender.Tests
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;

    using log4net;
    using log4net.Config;
    using log4net.Util;

    using Microsoft.ApplicationInsights.Channel;
    using Microsoft.ApplicationInsights.DataContracts;
    using Microsoft.ApplicationInsights.Extensibility;
    using Microsoft.ApplicationInsights.Log4NetAppender;
    using Microsoft.ApplicationInsights.Tracing.Tests;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [System.Diagnostics.CodeAnalysis.SuppressMessage(
        category: "Microsoft.Design", checkId: "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Disposing the object in the Test Cleanup")]
    [TestClass]
    public class ApplicationInsightsAppenderTests
    {
        private AdapterHelper adapterHelper;
        private AppendableLogger appendableLogger;

        [TestInitialize]
        public void Initialize()
        {
            this.adapterHelper = new AdapterHelper();
            this.appendableLogger = new AppendableLogger();
        }

        [TestCleanup]
        public void Cleanup()
        {
            this.adapterHelper.Dispose();
            this.appendableLogger.Dispose();
            TelemetryConfiguration.Active.Dispose();
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void InitializeAppenderNotFailingWhenInstrumentionKeyIsEmptyString()
        {
            this.VerifyInitializationSuccess(
                () => ApplicationInsightsAppenderTests.InitializeLog4NetAIAdapter(@"<InstrumentationKey value="""" />"),
                string.Empty);
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void InitializeAppenderDoesNotThrowLogExceptionWhenInstrumentationKeyIsCorrect()
        {
            string instrumentationKey = Guid.NewGuid().ToString();
            this.VerifyInitializationSuccess(
                    () => ApplicationInsightsAppenderTests.InitializeLog4NetAIAdapter(string.Format(@"<InstrumentationKey value=""{0}"" />", instrumentationKey)),
                    instrumentationKey);
        }
        
        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void ValidateLoggingIsWorking()
        {
            string instrumentationKey = "93d9c2b7-e633-4571-8520-d391511a1df5";
            ApplicationInsightsAppenderTests.InitializeLog4NetAIAdapter(string.Format(@"<InstrumentationKey value=""{0}"" />", instrumentationKey));

            // Set up error handler to intercept exception
            ApplicationInsightsAppender aiAppender = (ApplicationInsightsAppender)log4net.LogManager.GetRepository().GetAppenders()[0];
            log4net.Util.OnlyOnceErrorHandler errorHandler = new log4net.Util.OnlyOnceErrorHandler();
            aiAppender.ErrorHandler = errorHandler;
            
            // Log something
            ILog logger = log4net.LogManager.GetLogger("TestAIAppender");
            for (int i = 0; i < 1500; i++)
            {
                logger.Debug("Trace Debug" + i + DateTime.Now);
            }

            Assert.AreEqual(instrumentationKey, aiAppender.TelemetryClient.Context.InstrumentationKey);
            Assert.IsNull(errorHandler.Exception);
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void TracesAreEnqueuedInChannel()
        {
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;

            ApplicationInsightsAppenderTests.InitializeLog4NetAIAdapter(string.Empty);
            this.SendMessagesToMockChannel(this.adapterHelper.InstrumentationKey);
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void InstrumentationKeyCanBeOverridden()
        {
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;

            // Set instrumentation key in Log4Net environment
            string instrumentationKey = "93d9c2b7-e633-4571-8520-d391511a1df5";
            ApplicationInsightsAppenderTests.InitializeLog4NetAIAdapter(string.Format(@"<InstrumentationKey value=""{0}"" />", instrumentationKey));
            Assert.AreNotEqual(instrumentationKey, this.adapterHelper.InstrumentationKey, "This test will not verify anything if the same instrumentation key is used by both");
            this.SendMessagesToMockChannel(instrumentationKey);
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void Log4NetAddsCustomPropertiesToTraceTelemetry()
        {
            ApplicationInsightsAppenderTests.InitializeLog4NetAIAdapter(string.Empty);
            this.VerifyPropertiesInTelemetry();
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void Log4NetSetsTimespamp()
        {
            this.appendableLogger.Logger.Debug("Trace Debug");

            var sentItems = this.appendableLogger.SentItems;
            Assert.AreEqual(1, sentItems.Length);

            var telemetry = (TraceTelemetry)sentItems[0];
            Assert.AreNotEqual(default(DateTimeOffset), telemetry.Timestamp);
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void Log4NetSetsUser()
        {
            this.appendableLogger.Logger.Debug("Trace Debug");

            var sentItems = this.appendableLogger.SentItems;
            Assert.AreEqual(1, sentItems.Length);

            var telemetry = (TraceTelemetry)sentItems[0];
            Assert.IsNotNull(telemetry.Context.User.Id);
        }

        [TestMethod]
        [TestCategory("Log4NetAppender")]
        public void Log4NetAddsCustomProperties()
        {
            GlobalContext.Properties["CustomProperty1"] = "Value1";

            this.appendableLogger.Logger.Debug("Trace Debug");
{'fraction_non_alphanumeric': 0.11139462562794035, 'fraction_numerical': 0.015947691571645006, 'mean_word_length': 2.538939051918736, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2374500', 'n_tokens_mistral': 3230, 'n_tokens_neox': 3109, 'n_words': 494}