public void ShouldParseConfigfileCorrect(string level)
        {
            string configJsonString = @"
            {
              ""noise"": [
                {
                  ""type"": ""EventSource"",
                  ""sources"": [
                    { ""providerName"": ""Microsoft-ServiceFabric-Services"" },
                    { ""providerName"": ""MyCompany-AirTrafficControlApplication-Frontend"" }
                  ]
                }
              ],
              ""healthReporter"": {
                ""logFileFolder"": ""..\\App_Data\\"",
                ""logFilePrefix"": ""TestHealthReport"",
                ""minReportLevel"": ""@Level""
              }
            }
            ";

            configJsonString = configJsonString.Replace("@Level", level);
            using (var configFile = new TemporaryFile())
            {
                configFile.Write(configJsonString);
                using (CustomHealthReporter target = new CustomHealthReporter(configFile.FilePath))
                {
                    Assert.Equal(level, target.ConfigurationWrapper.MinReportLevel);
                }
            }
        }
        public void ShouldFlushOnceAWhile()
        {
            // Setup
            var      configuration = BuildTestConfigration();
            DateTime now           = DateTime.Now;

            // Exercise
            using (CustomHealthReporter target = new CustomHealthReporter(configuration, 200, customCreateFileStream: null, setNewStreamWriter: null, currentTimeProvider: () => now))
            {
                target.Activate();
                target.ReportProblem("Error message, with comma.", "UnitTest");
                // Verify
                Assert.False(target.FlushOperation.WaitOne(StreamOperationTimeoutMsec));
                target.StreamWriterMock.Verify(
                    s => s.Flush(),
                    Times.Never());

                now += TimeSpan.FromMilliseconds(500);
                target.ReportProblem("Error message, with comma.", "UnitTest");
                Assert.True(target.FlushOperation.WaitOne(StreamOperationTimeoutMsec));

                target.StreamWriterMock.Verify(
                    s => s.Flush(),
                    Times.Exactly(1));
            }
        }
        public async void ShouldFlushOnceAWhile()
        {
            // Setup
            var configuration       = BuildTestConfigration();
            int flushPeriodPlusMsec = 500;

            // Exercise
            using (CustomHealthReporter target = new CustomHealthReporter(configuration, 200))
            {
                target.Activate();
                target.ReportProblem("Error message, with comma.", "UnitTest");
                // Verify
                await Task.Delay(DefaultDelayMsec);

                target.StreamWriterMock.Verify(
                    s => s.Flush(),
                    Times.Never());

                await Task.Delay(flushPeriodPlusMsec);

                target.ReportProblem("Error message, with comma.", "UnitTest");
                await Task.Delay(DefaultDelayMsec);

                target.StreamWriterMock.Verify(
                    s => s.Flush(),
                    Times.Exactly(1));
            }
        }
        public void ConstructorShouldRequireConfigFile()
        {
            ArgumentNullException ex = Assert.Throws <ArgumentNullException>(() =>
            {
                CsvHealthReporter target = new CustomHealthReporter(configurationFilePath: null);
            });

            Assert.Equal("configurationFilePath", ex.ParamName);
        }
        public void ConstructorShouldRequireConfigFile()
        {
            Exception ex = Assert.Throws <ArgumentNullException>(() =>
            {
                CsvHealthReporter target = new CustomHealthReporter(configurationFilePath: null);
            });

            Assert.Equal("Value cannot be null.\r\nParameter name: configurationFilePath", ex.Message);
        }
        public void ShouldSetLogFileRetentionToDefaultWhenConfigUnderFlow()
        {
            var configuration = BuildTestConfigration(logRetention: -1);

            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                const int DefaultRetention = 30;
                Assert.Equal(DefaultRetention, target.ConfigurationWrapper.LogRetentionInDays);
            }
        }
        public void ShouldSetEnsureOutputCanBeSavedToFalseByDefault()
        {
            var configuration = BuildTestConfigration();

            Assert.Null(configuration[EnsureOutputCanBeSavedKey]);
            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                Assert.False(target.EnsureOutputCanBeSaved);
            }
        }
        public void ShouldSetLogFileSizeLimitToDefaultWhenConfigUnderflow()
        {
            var configuration = BuildTestConfigration(logFileMaxInMB: -1);

            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                const long DefaultSizeInBytes = (long)8192 * 1024 * 1024;
                Assert.Equal(-1, target.ConfigurationWrapper.SingleLogFileMaximumSizeInMBytes);
                Assert.Equal(DefaultSizeInBytes, target.SingleLogFileMaximumSizeInBytes);
            }
        }
        public void EscapeCommaShouldHandleNullOrEmptyString()
        {
            using (CustomHealthReporter target = new CustomHealthReporter(BuildTestConfigration()))
            {
                string actual = target.EscapeComma(null);
                Assert.Null(actual);

                actual = target.EscapeComma(string.Empty);
                Assert.Equal(string.Empty, actual);
            }
        }
        public void ShouldParseRelativePath()
        {
            // Setup
            var configuration = BuildTestConfigration();

            // Exercise
            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                Assert.True(Path.IsPathRooted(target.ConfigurationWrapper.LogFileFolder));
            }
        }
        public void ShouldHaveDefaultLogFileRetentionWhenNotSetInConfig()
        {
            var configuration = BuildTestConfigration();

            Assert.Equal(0, configuration.ToCsvHealthReporterConfiguration().LogRetentionInDays);
            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                const int DefaultRetentionDays = 30;
                Assert.Equal(DefaultRetentionDays, target.ConfigurationWrapper.LogRetentionInDays);
            }
        }
        public void ShouldHaveDefaultLogFileSizeLimitWhenNotSetInConfigure()
        {
            var configuration = BuildTestConfigration();

            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                const long DefaultSizeInBytes = (long)8192 * 1024 * 1024;
                // Accepts 0
                Assert.Equal(0, target.ConfigurationWrapper.SingleLogFileMaximumSizeInMBytes);
                // Update to default limit & convert to bytes
                Assert.Equal(DefaultSizeInBytes, target.SingleLogFileMaximumSizeInBytes);
            }
        }
        public void ShouldExpandEnvironmentVariablesForLogFolder()
        {
            var configuration = BuildTestConfigration();

            Environment.SetEnvironmentVariable("WarsawUnitTestPath", @"x:\temp");
            configuration[LogFileFolderKey] = @"%WarsawUnitTestPath%\logs";
            string expected = Environment.ExpandEnvironmentVariables(@"%WarsawUnitTestPath%\logs");

            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                Assert.Equal(expected, target.ConfigurationWrapper.LogFileFolder);
            }
        }
        public void ShouldCleanUpExistingLogsPerRetentionPolicy()
        {
            var configuration = BuildTestConfigration(logRetention: 1);

            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                int removedItemCount = 0;
                target.CleanupExistingLogs(info =>
                {
                    removedItemCount++;
                });
                Assert.Equal(2, removedItemCount);
            }
        }
        public void ShouldRotateLogFileWhenFileDoesExist()
        {
            var configuration = BuildTestConfigration();

            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                bool   rotate   = false;
                string fileName = target.RotateLogFileImp(".", path => true, path => { }, (from, to) =>
                {
                    rotate = true;
                });
                Assert.True(rotate);
            }
        }
        public void ShouldSetEnsureOutputCanBeSavedByConfiguration()
        {
            var configuration = BuildTestConfigration();

            configuration[EnsureOutputCanBeSavedKey] = "true";
            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                Assert.True(target.EnsureOutputCanBeSaved);
            }

            configuration[EnsureOutputCanBeSavedKey] = "false";
            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                Assert.False(target.EnsureOutputCanBeSaved);
            }
        }
        public void ReportProblemShouldWriteError()
        {
            var configuration = BuildTestConfigration();

            // Exercise
            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                target.Activate();
                target.ReportProblem("Error message.", "UnitTest");
                Assert.True(target.WriteOperation.WaitOne(StreamOperationTimeoutMsec));
                // Verify
                target.StreamWriterMock.Verify(
                    s => s.WriteLine(
                        It.Is <string>(msg => msg.Contains("UnitTest,Error,Error message."))),
                    Times.Exactly(1));
            }
        }
        public void ShouldEscapeQuotesWhenThereIsCommaInMessage()
        {
            // Setup
            var configuration = BuildTestConfigration();

            // Exercise
            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                target.Activate();
                target.ReportProblem("Error \"message\", with comma and quotes.", "UnitTest");
                // Verify
                Assert.True(target.WriteOperation.WaitOne(StreamOperationTimeoutMsec));
                target.StreamWriterMock.Verify(
                    s => s.WriteLine(
                        It.Is <string>(msg => msg.Contains("UnitTest,Error,\"Error \"\"message\"\", with comma and quotes.\""))),
                    Times.Exactly(1));
            }
        }
        public async void ReportProblemShouldWriteError()
        {
            var configuration = BuildTestConfigration();

            // Exercise
            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                target.Activate();
                target.ReportProblem("Error message.", "UnitTest");
                await Task.Delay(DefaultDelayMsec);

                // Verify
                target.StreamWriterMock.Verify(
                    s => s.WriteLine(
                        It.Is <string>(msg => msg.Contains("UnitTest,Error,Error message."))),
                    Times.Exactly(1));
            }
        }
        public void ConstructorShouldHandleWrongFilterLevel()
        {
            // Setup
            var configuration = BuildTestConfigration();

            configuration[MinReportLevelKey] = "WrongLevel";

            // Exercise
            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                target.Activate();
                Assert.True(target.WriteOperation.WaitOne(StreamOperationTimeoutMsec));
                // Verify
                target.StreamWriterMock.Verify(
                    s => s.WriteLine(
                        It.Is <string>(msg => msg.EndsWith("Failed to parse log level. Please check the value of: WrongLevel. Falling back to default value: Error"))),
                    Times.Exactly(1));
            }
        }
        public async void ReporterShouldFilterOutMessage()
        {
            // Setup
            var configuration = BuildTestConfigration();

            configuration[MinReportLevelKey] = "Warning";

            // Exercise
            using (CustomHealthReporter target = new CustomHealthReporter(configuration))
            {
                target.Activate();
                target.ReportHealthy("Supposed to be filtered.", "UnitTest");
                // Verify that message is filtered out.
                await Task.Delay(DefaultDelayMsec);

                target.StreamWriterMock.Verify(
                    s => s.WriteLine(
                        It.IsAny <string>()),
                    Times.Exactly(0));

                // Verify that warning is not filtered out.
                target.ReportWarning("Warning message", "UnitTests");
                await Task.Delay(DefaultDelayMsec);

                target.StreamWriterMock.Verify(
                    s => s.WriteLine(
                        It.IsAny <string>()),
                    Times.Exactly(1));

                // Verify that error is not filtered out.
                target.ReportWarning("Error message", "UnitTests");
                await Task.Delay(DefaultDelayMsec);

                target.StreamWriterMock.Verify(
                    s => s.WriteLine(
                        It.IsAny <string>()),
                    Times.Exactly(2));
            }
        }