diff --git a/Tests/CodeSnippets/TestPostgresLISTENNOTIFY.cs b/Tests/CodeSnippets/TestPostgresLISTENNOTIFY.cs index ed52167..b33a593 100644 --- a/Tests/CodeSnippets/TestPostgresLISTENNOTIFY.cs +++ b/Tests/CodeSnippets/TestPostgresLISTENNOTIFY.cs @@ -1,21 +1,23 @@ using Npgsql; -class TestPostgresLISTENNOTIFY +namespace PlanTempus.X.TDD.CodeSnippets; + +internal class TestPostgresLISTENNOTIFY { - static async Task Main(string[] args) + private static async Task Main(string[] args) { var connectionString = "Host=192.168.1.57;Database=ptdb01;Username=postgres;Password=3911"; try { - await using NpgsqlConnection conn = new NpgsqlConnection(connectionString); + await using var conn = new NpgsqlConnection(connectionString); await conn.OpenAsync(); Console.WriteLine("Forbundet til databasen. Lytter efter notifikationer..."); conn.Notification += (o, e) => { - Console.WriteLine($"Notifikation modtaget:"); + Console.WriteLine("Notifikation modtaget:"); Console.WriteLine($" PID: {e.PID}"); Console.WriteLine($" Kanal: {e.Channel}"); Console.WriteLine($" Payload: {e.Payload}"); @@ -29,10 +31,7 @@ class TestPostgresLISTENNOTIFY Console.WriteLine("Tryk på en tast for at stoppe..."); - while (!Console.KeyAvailable) - { - await conn.WaitAsync(); - } + while (!Console.KeyAvailable) await conn.WaitAsync(); } catch (Exception ex) { diff --git a/Tests/ConfigurationSystem/SetupConfigurationTests.cs b/Tests/ConfigurationSystem/SetupConfigurationTests.cs index f1676d1..df1cfec 100644 --- a/Tests/ConfigurationSystem/SetupConfigurationTests.cs +++ b/Tests/ConfigurationSystem/SetupConfigurationTests.cs @@ -1,18 +1,16 @@ -using PlanTempus.Database.ConfigurationManagementSystem; -using Insight.Database; -using System.Data; -using Newtonsoft.Json; +using System.Data; using Autofac; -using Shouldly; +using Insight.Database; +using Newtonsoft.Json; using PlanTempus.Core.Sql.ConnectionFactory; +using Shouldly; -namespace PlanTempus.Tests.ConfigurationSystem; +namespace PlanTempus.X.TDD.ConfigurationSystem; [TestClass] public class SetupConfigurationTests : TestFixture { private IDbConnection _connection; - private SetupConfiguration _setupConfiguration; [TestInitialize] public void Setup() @@ -52,15 +50,15 @@ public class SetupConfigurationTests : TestFixture SELECT key, value, label, action_type FROM app_configuration_history WHERE id = @id AND action_type = 'I'", - new { id = (int)result.id }) + new { id = (int)result.id }) .Single(); // Assert var expected = JsonConvert.SerializeObject(new { - key = configData.key, - value = configData.value, - label = configData.label, + configData.key, + configData.value, + configData.label, action_type = "I" }); var actual = JsonConvert.SerializeObject(history) as string; @@ -83,7 +81,7 @@ public class SetupConfigurationTests : TestFixture RETURNING modified_at", configData) .Single(); - System.Threading.Thread.Sleep(1000); + Thread.Sleep(1000); // Act var updated = _connection.QuerySql(@" @@ -91,7 +89,7 @@ public class SetupConfigurationTests : TestFixture SET value = @value WHERE key = @key RETURNING modified_at", - new { key = configData.key, value = "updated value" }) + new { configData.key, value = "updated value" }) .Single(); // Assert @@ -124,13 +122,13 @@ public class SetupConfigurationTests : TestFixture SELECT key, value, action_type FROM app_configuration_history WHERE id = @id AND action_type = 'D'", - new { id = (int)original.id }) + new { id = (int)original.id }) .Single(); var expected = JsonConvert.SerializeObject(new { - key = configData.key, - value = configData.value, + configData.key, + configData.value, action_type = "D" }); var actual = JsonConvert.SerializeObject(history) as string; @@ -177,10 +175,10 @@ public class SetupConfigurationTests : TestFixture // Assert var expected = JsonConvert.SerializeObject(new { - key = configData.key, - value = configData.value, - label = configData.label, - content_type = configData.content_type, + configData.key, + configData.value, + configData.label, + configData.content_type, valid_from = ((DateTimeOffset)configData.valid_from).ToUnixTimeSeconds(), expires_at = ((DateTimeOffset)configData.expires_at).ToUnixTimeSeconds() }); diff --git a/Tests/ConfigurationTests/JsonConfigurationProviderTests.cs b/Tests/ConfigurationTests/JsonConfigurationProviderTests.cs index 8ae0689..923e65e 100644 --- a/Tests/ConfigurationTests/JsonConfigurationProviderTests.cs +++ b/Tests/ConfigurationTests/JsonConfigurationProviderTests.cs @@ -1,142 +1,144 @@ using Newtonsoft.Json.Linq; -using Shouldly; -using PlanTempus.Tests; using PlanTempus.Core.Configurations; using PlanTempus.Core.Configurations.JsonConfigProvider; using PlanTempus.Core.Configurations.SmartConfigProvider; +using Shouldly; -namespace PlanTempus.Tests.ConfigurationTests +namespace PlanTempus.X.TDD.ConfigurationTests; + +[TestClass] +public class JsonConfigurationProviderTests : TestFixture { - [TestClass] - public class JsonConfigurationProviderTests : TestFixture + private const string _testFolder = "ConfigurationTests/"; + + public JsonConfigurationProviderTests() : base(_testFolder) { - const string _testFolder = "ConfigurationTests/"; - - public JsonConfigurationProviderTests() : base(_testFolder) { } + } - [TestMethod] - public void GetSection_ShouldReturnCorrectFeatureSection() - { - // Arrange - var expectedJObject = JObject.Parse(@"{ + [TestMethod] + public void GetSection_ShouldReturnCorrectFeatureSection() + { + // Arrange + var expectedJObject = JObject.Parse(@"{ 'Enabled': true, 'RolloutPercentage': 25, 'AllowedUserGroups': ['beta'] }") as JToken; - var builder = new ConfigurationBuilder() - .AddJsonFile($"{_testFolder}appconfiguration.dev.json") - .Build(); + var builder = new ConfigurationBuilder() + .AddJsonFile($"{_testFolder}appconfiguration.dev.json") + .Build(); - // Act - var section = builder.GetSection("Feature"); + // Act + var section = builder.GetSection("Feature"); - // Assert - section.ShouldNotBeNull(); - section.Value.ShouldBeEquivalentTo(expectedJObject); - } - - [TestMethod] - public void Get_ShouldReturnCorrectFeatureObject() - { - // Arrange - var expectedFeature = new Feature - { - Enabled = true, - RolloutPercentage = 25, - AllowedUserGroups = new() { "beta" } - }; - - var builder = new ConfigurationBuilder() - .AddJsonFile($"{_testFolder}appconfiguration.dev.json") - .Build(); - - // Act - var actualFeature = builder.GetSection("Feature").ToObject(); -#pragma warning disable CS0618 // Type or member is obsolete - var actualFeatureObsoleted = builder.GetSection("Feature").Get(); -#pragma warning restore CS0618 // Type or member is obsolete - // Assert - actualFeature.ShouldBeEquivalentTo(expectedFeature); - actualFeatureObsoleted.ShouldBeEquivalentTo(expectedFeature); - - } - [TestMethod] - public void Get_ShouldReturnCorrectValueAsString() - { - // Arrange - var expectedFeature = "123"; - - var builder = new ConfigurationBuilder() - .AddJsonFile($"{_testFolder}appconfiguration.dev.json") - .Build(); - - // Act - var actualFeature = builder.GetSection("AnotherSetting").Get("Thresholds:High"); - - // Assert - actualFeature.ShouldBeEquivalentTo(expectedFeature); - } - /// - /// Testing a stupid indexer for compability with Microsoft ConfigurationBuilder - /// - [TestMethod] - public void Indexer_ShouldReturnValueAsString() - { - // Arrange - var expected = "SHA256"; - - var builder = new ConfigurationBuilder() - .AddJsonFile($"{_testFolder}appconfiguration.dev.json") - .Build(); - - // Act - var actual = builder["Authentication"]; - - // Assert - actual.ShouldBeEquivalentTo(expected); - } - [TestMethod] - public void Get_ShouldReturnCorrectValueAsInt() - { - // Arrange - var expectedFeature = 22; - - var builder = new ConfigurationBuilder() - .AddJsonFile($"{_testFolder}appconfiguration.dev.json") - .Build(); - - // Act - var actualFeature = builder.GetSection("AnotherSetting:Temperature").Get("Indoor:Max:Limit"); - - // Assert - actualFeature.ShouldBe(expectedFeature); - } - [TestMethod] - public void Get_ShouldReturnCorrectValueAsBool() - { - // Arrange - var expectedFeature = true; - - var configRoot = new ConfigurationBuilder() - .AddJsonFile($"{_testFolder}appconfiguration.dev.json") - .AddSmartConfig() - .Build(); - - // Act - var actualFeature = configRoot.Get("Database:UseSSL"); - - // Assert - actualFeature.ShouldBe(expectedFeature); - } + // Assert + section.ShouldNotBeNull(); + section.Value.ShouldBeEquivalentTo(expectedJObject); } - internal class Feature + [TestMethod] + public void Get_ShouldReturnCorrectFeatureObject() { - public bool Enabled { get; set; } - public int RolloutPercentage { get; set; } - public List AllowedUserGroups { get; set; } + // Arrange + var expectedFeature = new Feature + { + Enabled = true, + RolloutPercentage = 25, + AllowedUserGroups = new List { "beta" } + }; + + var builder = new ConfigurationBuilder() + .AddJsonFile($"{_testFolder}appconfiguration.dev.json") + .Build(); + + // Act + var actualFeature = builder.GetSection("Feature").ToObject(); +#pragma warning disable CS0618 // Type or member is obsolete + var actualFeatureObsoleted = builder.GetSection("Feature").Get(); +#pragma warning restore CS0618 // Type or member is obsolete + // Assert + actualFeature.ShouldBeEquivalentTo(expectedFeature); + actualFeatureObsoleted.ShouldBeEquivalentTo(expectedFeature); } + [TestMethod] + public void Get_ShouldReturnCorrectValueAsString() + { + // Arrange + var expectedFeature = "123"; + + var builder = new ConfigurationBuilder() + .AddJsonFile($"{_testFolder}appconfiguration.dev.json") + .Build(); + + // Act + var actualFeature = builder.GetSection("AnotherSetting").Get("Thresholds:High"); + + // Assert + actualFeature.ShouldBeEquivalentTo(expectedFeature); + } + + /// + /// Testing a stupid indexer for compability with Microsoft ConfigurationBuilder + /// + [TestMethod] + public void Indexer_ShouldReturnValueAsString() + { + // Arrange + var expected = "SHA256"; + + var builder = new ConfigurationBuilder() + .AddJsonFile($"{_testFolder}appconfiguration.dev.json") + .Build(); + + // Act + var actual = builder["Authentication"]; + + // Assert + actual.ShouldBeEquivalentTo(expected); + } + + [TestMethod] + public void Get_ShouldReturnCorrectValueAsInt() + { + // Arrange + var expectedFeature = 22; + + var builder = new ConfigurationBuilder() + .AddJsonFile($"{_testFolder}appconfiguration.dev.json") + .Build(); + + // Act + var actualFeature = builder.GetSection("AnotherSetting:Temperature").Get("Indoor:Max:Limit"); + + // Assert + actualFeature.ShouldBe(expectedFeature); + } + + [TestMethod] + public void Get_ShouldReturnCorrectValueAsBool() + { + // Arrange + var expectedFeature = true; + + var configRoot = new ConfigurationBuilder() + .AddJsonFile($"{_testFolder}appconfiguration.dev.json") + .AddSmartConfig() + .Build(); + + // Act + var actualFeature = configRoot.Get("Database:UseSSL"); + + // Assert + actualFeature.ShouldBe(expectedFeature); + } +} + +internal class Feature +{ + public bool Enabled { get; set; } + public int RolloutPercentage { get; set; } + public List AllowedUserGroups { get; set; } } \ No newline at end of file diff --git a/Tests/ConfigurationTests/KeyValueJsonHandlingTests.cs b/Tests/ConfigurationTests/KeyValueJsonHandlingTests.cs index 7d89439..ac45350 100644 --- a/Tests/ConfigurationTests/KeyValueJsonHandlingTests.cs +++ b/Tests/ConfigurationTests/KeyValueJsonHandlingTests.cs @@ -1,8 +1,7 @@ using Newtonsoft.Json.Linq; using PlanTempus.Core.Configurations.Common; -using PlanTempus.Tests; -namespace PlanTempus.Tests.ConfigurationTests; +namespace PlanTempus.X.TDD.ConfigurationTests; [TestClass] public class ConfigurationTests : TestFixture @@ -17,31 +16,31 @@ public class ConfigurationTests : TestFixture public void ConfigurationSettingsTest() { var pairs = new List> - { - new("Debug", true), - // Database konfiguration - new("Database:ConnectionString", "Server=db.example.com;Port=5432"), - new("Database:Timeout", 30), - new("Database:UseSSL", true), + { + new("Debug", true), + // Database konfiguration + new("Database:ConnectionString", "Server=db.example.com;Port=5432"), + new("Database:Timeout", 30), + new("Database:UseSSL", true), - // Logging konfiguration med JObject - new("Logging:FileOptions", JObject.Parse(@"{ + // Logging konfiguration med JObject + new("Logging:FileOptions", JObject.Parse(@"{ 'Path': '/var/logs/app.log', 'MaxSizeMB': 100, 'RetentionDays': 7 }")), - // Feature flags med kompleks konfiguration - new("Features:Experimental", JObject.Parse(@"{ + // Feature flags med kompleks konfiguration + new("Features:Experimental", JObject.Parse(@"{ 'Enabled': true, 'RolloutPercentage': 25, 'AllowedUserGroups': ['beta'] }")), - // API endpoints med array - new("API:Endpoints", "/api/users"), - new("API:Endpoints", "/api/products") - }; + // API endpoints med array + new("API:Endpoints", "/api/users"), + new("API:Endpoints", "/api/products") + }; var result = KeyValueToJson.Convert(pairs); diff --git a/Tests/ConfigurationTests/SmartConfigProviderTests.cs b/Tests/ConfigurationTests/SmartConfigProviderTests.cs index 1304afe..2a351cf 100644 --- a/Tests/ConfigurationTests/SmartConfigProviderTests.cs +++ b/Tests/ConfigurationTests/SmartConfigProviderTests.cs @@ -1,86 +1,82 @@ using Autofac; -using Shouldly; -using System.Data; using Insight.Database; using PlanTempus.Core.Configurations; using PlanTempus.Core.Configurations.JsonConfigProvider; using PlanTempus.Core.Configurations.SmartConfigProvider; using PlanTempus.Core.Sql.ConnectionFactory; +using Shouldly; -namespace PlanTempus.Tests.ConfigurationTests +namespace PlanTempus.X.TDD.ConfigurationTests; + +[TestClass] +public class SmartConfigProviderTests : TestFixture { - [TestClass] - public class SmartConfigProviderTests : TestFixture - { - const string _testFolder = "ConfigurationTests/"; + private const string _testFolder = "ConfigurationTests/"; - [TestMethod] - public void TrySmartConfigWithOptionsForPostgres() - { - var config = new ConfigurationBuilder() - .AddJsonFile($"{_testFolder}appconfiguration.dev.json") - .AddSmartConfig(options => options.UsePostgres("DefaultConnection")) - .Build(); + [TestMethod] + public void TrySmartConfigWithOptionsForPostgres() + { + var config = new ConfigurationBuilder() + .AddJsonFile($"{_testFolder}appconfiguration.dev.json") + .AddSmartConfig(options => options.UsePostgres("DefaultConnection")) + .Build(); - var actualFeature = config.Get("Database:UseSSL"); + var actualFeature = config.Get("Database:UseSSL"); + } - } + [TestMethod] + public void Get_ShouldReturnCorrectValueAsBool() + { + // Arrange + var expectedFeature = true; - [TestMethod] - public void Get_ShouldReturnCorrectValueAsBool() - { - // Arrange - var expectedFeature = true; + var config = new ConfigurationBuilder() + .AddJsonFile($"{_testFolder}appconfiguration.dev.json") + .AddSmartConfig(options => options.UsePostgres("DefaultConnection")) + .Build(); - var config = new ConfigurationBuilder() - .AddJsonFile($"{_testFolder}appconfiguration.dev.json") - .AddSmartConfig(options => options.UsePostgres("DefaultConnection")) - .Build(); + // Act + var actualFeature = config.Get("Database:UseSSL"); - // Act - var actualFeature = config.Get("Database:UseSSL"); + // Assert + actualFeature.ShouldBe(expectedFeature); + } - // Assert - actualFeature.ShouldBe(expectedFeature); - } - [TestMethod] - public void Get_ShouldReturnCorrectValueWhenSelectingIntoValueRowInConfigTable() - { - // Arrange - var expectedFeature = 100; + [TestMethod] + public void Get_ShouldReturnCorrectValueWhenSelectingIntoValueRowInConfigTable() + { + // Arrange + var expectedFeature = 100; - var builder = new ConfigurationBuilder() - .AddJsonFile($"{_testFolder}appconfiguration.dev.json") - .AddSmartConfig(options => options.UsePostgres("DefaultConnection")) - .Build(); + var builder = new ConfigurationBuilder() + .AddJsonFile($"{_testFolder}appconfiguration.dev.json") + .AddSmartConfig(options => options.UsePostgres("DefaultConnection")) + .Build(); - // Act - var actualFeature = builder.GetSection("Logging:FileOptions").Get("MaxSizeMB"); - var withoutSectionThisAlsoWorks = builder.Get("Logging:FileOptions:MaxSizeMB"); + // Act + var actualFeature = builder.GetSection("Logging:FileOptions").Get("MaxSizeMB"); + var withoutSectionThisAlsoWorks = builder.Get("Logging:FileOptions:MaxSizeMB"); - // Assert - actualFeature.ShouldBe(expectedFeature); - actualFeature.ShouldBe(withoutSectionThisAlsoWorks); + // Assert + actualFeature.ShouldBe(expectedFeature); + actualFeature.ShouldBe(withoutSectionThisAlsoWorks); + } - } + [TestMethod] + public void TryGetActiveConfigurations() + { + var connFactory = Container.Resolve(); - [TestMethod] - public void TryGetActiveConfigurations() - { - var connFactory = Container.Resolve(); - - const string sql = @" + const string sql = @" SELECT id, ""key"", value, label, content_type, valid_from, expires_at, created_at, modified_at, etag FROM app_configuration WHERE CURRENT_TIMESTAMP BETWEEN valid_from AND expires_at OR (valid_from IS NULL AND expires_at IS NULL)"; - using (var conn = connFactory.Create()) - { - var result = conn.QuerySql(sql); - - } - } - } + using (var conn = connFactory.Create()) + { + var result = conn.QuerySql(sql); + } + } } \ No newline at end of file diff --git a/Tests/ConfigurationTests/appconfiguration.dev.json b/Tests/ConfigurationTests/appconfiguration.dev.json index 46b99b3..abd099d 100644 --- a/Tests/ConfigurationTests/appconfiguration.dev.json +++ b/Tests/ConfigurationTests/appconfiguration.dev.json @@ -16,23 +16,31 @@ "Feature": { "Enabled": true, "RolloutPercentage": 25, - "AllowedUserGroups": [ "beta" ] + "AllowedUserGroups": [ + "beta" + ] }, "AnotherSetting": { - "Thresholds": { "High": "123", "Low": "-1" }, "Temperature": { - "Indoor": { - "Max": { "Limit": 22 }, - "Min": { "Limit": 18 } + "Max": { + "Limit": 22 + }, + "Min": { + "Limit": 18 + } }, "Outdoor": { - "Max": { "Limit": 12 }, - "Min": { "Limit": 9 } + "Max": { + "Limit": 12 + }, + "Min": { + "Limit": 9 + } } } }, diff --git a/Tests/Logging/SeqBackgroundServiceTest.cs b/Tests/Logging/SeqBackgroundServiceTest.cs index 49aae6d..05cfe7c 100644 --- a/Tests/Logging/SeqBackgroundServiceTest.cs +++ b/Tests/Logging/SeqBackgroundServiceTest.cs @@ -1,3 +1,4 @@ +using System.Net; using Autofac; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Channel; @@ -5,67 +6,66 @@ using Microsoft.ApplicationInsights.DataContracts; using PlanTempus.Core.Logging; using PlanTempus.Core.Telemetry; -namespace PlanTempus.Tests.Logging +namespace PlanTempus.X.TDD.Logging; + +[TestClass] +public class SeqBackgroundServiceTest : TestFixture { - [TestClass] - public class SeqBackgroundServiceTest : TestFixture + private CancellationTokenSource _cts; + private IMessageChannel _messageChannel; + private SeqBackgroundService _service; + + [TestInitialize] + public void SetupThis() { - private IMessageChannel _messageChannel; - private SeqBackgroundService _service; - private CancellationTokenSource _cts; + _messageChannel = new MessageChannel(); + var telemetryClient = Container.Resolve(); - [TestInitialize] - public void SetupThis() + var config = new SeqConfiguration("http://localhost:5341", null, "MSTEST"); + + var httpClient = new SeqHttpClient(config); + var logger = new SeqLogger(httpClient, config); + + _service = new SeqBackgroundService(telemetryClient, _messageChannel, logger); + _cts = new CancellationTokenSource(); + } + + [TestMethod] + public async Task Messages_ShouldBeProcessedFromQueue() + { + await _service.StartAsync(_cts.Token); + + for (var i = 0; i < 5; i++) { - _messageChannel = new MessageChannel(); - var telemetryClient = Container.Resolve(); + var eventTelemetry = new EventTelemetry + { + Name = "Test Event", + Timestamp = DateTimeOffset.UtcNow + }; + eventTelemetry.Properties.Add("TestId", Guid.NewGuid().ToString()); + eventTelemetry.Metrics.Add("TestMetric", 42.0); - var config = new SeqConfiguration("http://localhost:5341", null, "MSTEST"); - - var httpClient = new SeqHttpClient(config); - var logger = new SeqLogger(httpClient, config); - - _service = new SeqBackgroundService(telemetryClient, _messageChannel, logger); - _cts = new CancellationTokenSource(); + await _messageChannel.Writer.WriteAsync(eventTelemetry); } - [TestMethod] - public async Task Messages_ShouldBeProcessedFromQueue() + // wait for processing + await Task.Delay(5000); + + _cts.Cancel(); //not sure about this, we need to analyse more before this is "the way" + await _service.StopAsync(CancellationToken.None); + + + var hasMoreMessages = await _messageChannel.Reader.WaitToReadAsync(); + Assert.IsFalse(hasMoreMessages, "Queue should be empty after 5 seconds"); + } + + private class TestMessageHandler : HttpMessageHandler + { + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) { - await _service.StartAsync(_cts.Token); - - for (int i = 0; i < 5; i++) - { - var eventTelemetry = new EventTelemetry - { - Name = "Test Event", - Timestamp = DateTimeOffset.UtcNow - }; - eventTelemetry.Properties.Add("TestId", Guid.NewGuid().ToString()); - eventTelemetry.Metrics.Add("TestMetric", 42.0); - - await _messageChannel.Writer.WriteAsync(eventTelemetry); - } - - // wait for processing - await Task.Delay(5000); - - _cts.Cancel(); //not sure about this, we need to analyse more before this is "the way" - await _service.StopAsync(CancellationToken.None); - - - bool hasMoreMessages = await _messageChannel.Reader.WaitToReadAsync(); - Assert.IsFalse(hasMoreMessages, "Queue should be empty after 5 seconds"); - } - - private class TestMessageHandler : HttpMessageHandler - { - protected override Task SendAsync( - HttpRequestMessage request, - CancellationToken cancellationToken) - { - return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK)); - } + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)); } } } \ No newline at end of file diff --git a/Tests/Logging/SeqLoggerTests.cs b/Tests/Logging/SeqLoggerTests.cs index 0842851..25b6c04 100644 --- a/Tests/Logging/SeqLoggerTests.cs +++ b/Tests/Logging/SeqLoggerTests.cs @@ -3,146 +3,143 @@ using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.DataContracts; using PlanTempus.Core.Logging; -namespace PlanTempus.Tests.Logging +namespace PlanTempus.X.TDD.Logging; + +[TestClass] +public class SeqLoggerTests : TestFixture { - [TestClass] - public class SeqLoggerTests : TestFixture + private readonly string _testId; + private readonly SeqHttpClient _httpClient; + private readonly SeqLogger _logger; + + public SeqLoggerTests() { - private SeqLogger _logger; - private SeqHttpClient _httpClient; - private readonly string _testId; + _testId = Guid.NewGuid().ToString(); + var config = new SeqConfiguration("http://localhost:5341", null, "MSTEST"); + _httpClient = new SeqHttpClient(config); + _logger = new SeqLogger(_httpClient, config); + } - public SeqLoggerTests() + [TestMethod] + public async Task LogTraceTelemetry_SendsCorrectDataWithErrorLevel() + { + // Arrange + var traceTelemetry = new TraceTelemetry { - _testId = Guid.NewGuid().ToString(); - var config = new SeqConfiguration("http://localhost:5341", null, "MSTEST"); - _httpClient = new SeqHttpClient(config); - _logger = new SeqLogger(_httpClient, config); - } + Message = "Test trace error message", + SeverityLevel = SeverityLevel.Error, + Timestamp = DateTimeOffset.UtcNow + }; + traceTelemetry.Properties.Add("TestId", _testId); - [TestMethod] - public async Task LogTraceTelemetry_SendsCorrectDataWithErrorLevel() + // Act + await _logger.LogAsync(traceTelemetry); + } + + [TestMethod] + public async Task LogTraceTelemetry_SendsCorrectDataWithWarningLevel() + { + // Arrange + var traceTelemetry = new TraceTelemetry + { + Message = "Test trace warning message", + SeverityLevel = SeverityLevel.Warning, + Timestamp = DateTimeOffset.UtcNow + }; + traceTelemetry.Properties.Add("TestId", _testId); + + // Act + await _logger.LogAsync(traceTelemetry); + } + + [TestMethod] + public async Task LogEventTelemetry_SendsCorrectData() + { + // Arrange + var eventTelemetry = new EventTelemetry + { + Name = "Test Event", + Timestamp = DateTimeOffset.UtcNow + }; + eventTelemetry.Properties.Add("TestId", _testId); + eventTelemetry.Metrics.Add("TestMetric", 42.0); + + // Act + await _logger.LogAsync(eventTelemetry); + } + + [TestMethod] + public async Task LogExceptionTelemetry_SendsCorrectData() + { + try + { + var t = 0; + var result = 10 / t; + } + catch (Exception e) { // Arrange - var traceTelemetry = new TraceTelemetry + var exceptionTelemetry = new ExceptionTelemetry(e) { - Message = "Test trace error message", - SeverityLevel = SeverityLevel.Error, Timestamp = DateTimeOffset.UtcNow }; - traceTelemetry.Properties.Add("TestId", _testId); + exceptionTelemetry.Properties.Add("TestId", _testId); // Act - await _logger.LogAsync(traceTelemetry); - - - } - [TestMethod] - public async Task LogTraceTelemetry_SendsCorrectDataWithWarningLevel() - { - // Arrange - var traceTelemetry = new TraceTelemetry - { - Message = "Test trace warning message", - SeverityLevel = SeverityLevel.Warning, - Timestamp = DateTimeOffset.UtcNow - }; - traceTelemetry.Properties.Add("TestId", _testId); - - // Act - await _logger.LogAsync(traceTelemetry); - - } - [TestMethod] - public async Task LogEventTelemetry_SendsCorrectData() - { - // Arrange - var eventTelemetry = new EventTelemetry - { - Name = "Test Event", - Timestamp = DateTimeOffset.UtcNow - }; - eventTelemetry.Properties.Add("TestId", _testId); - eventTelemetry.Metrics.Add("TestMetric", 42.0); - - // Act - await _logger.LogAsync(eventTelemetry); - } - - [TestMethod] - public async Task LogExceptionTelemetry_SendsCorrectData() - { - try - { - int t = 0; - var result = 10 / t; - - } - catch (Exception e) - { - - // Arrange - var exceptionTelemetry = new ExceptionTelemetry(e) - { - Timestamp = DateTimeOffset.UtcNow - }; - exceptionTelemetry.Properties.Add("TestId", _testId); - - // Act - await _logger.LogAsync(exceptionTelemetry); - } - } - - [TestMethod] - public async Task LogDependencyTelemetry_SendsCorrectData() - { - // Arrange - var dependencyTelemetry = new DependencyTelemetry - { - Name = "SQL Query", - Type = "SQL", - Target = "TestDB", - Success = true, - Duration = TimeSpan.FromMilliseconds(100), - Timestamp = DateTimeOffset.UtcNow - }; - dependencyTelemetry.Properties.Add("TestId", _testId); - - // Act - await _logger.LogAsync(dependencyTelemetry); - } - - /// - /// This is for scope test in SeqLogger. It is not testing anything related to the TelemetryChannel which logs to Seq. - /// - /// - [TestMethod] - public async Task LogRequestTelemetryInOperationHolderWithParentChild_SendsCorrectData() - { - var telemetryClient = Container.Resolve(); - - using (Microsoft.ApplicationInsights.Extensibility.IOperationHolder parent = telemetryClient.StartOperation("Parent First")) - { - - parent.Telemetry.Duration = TimeSpan.FromMilliseconds(250); - parent.Telemetry.Url = new Uri("http://parent.test.com/api/test"); - - using (var child = telemetryClient.StartOperation("Child 1")) - { - child.Telemetry.Success = true; - child.Telemetry.ResponseCode = "200"; - child.Telemetry.Duration = TimeSpan.FromMilliseconds(50); - child.Telemetry.Url = new Uri("http://child.test.com/api/test"); - child.Telemetry.Timestamp = DateTimeOffset.UtcNow; - - child.Telemetry.Properties.Add("httpMethod", HttpMethod.Get.ToString()); - child.Telemetry.Properties.Add("TestId", _testId); - - await _logger.LogAsync(child); - }; - - await _logger.LogAsync(parent); - } + await _logger.LogAsync(exceptionTelemetry); } } -} + + [TestMethod] + public async Task LogDependencyTelemetry_SendsCorrectData() + { + // Arrange + var dependencyTelemetry = new DependencyTelemetry + { + Name = "SQL Query", + Type = "SQL", + Target = "TestDB", + Success = true, + Duration = TimeSpan.FromMilliseconds(100), + Timestamp = DateTimeOffset.UtcNow + }; + dependencyTelemetry.Properties.Add("TestId", _testId); + + // Act + await _logger.LogAsync(dependencyTelemetry); + } + + /// + /// This is for scope test in SeqLogger. It is not testing anything related to the TelemetryChannel which logs to Seq. + /// + /// + [TestMethod] + public async Task LogRequestTelemetryInOperationHolderWithParentChild_SendsCorrectData() + { + var telemetryClient = Container.Resolve(); + + using (var parent = telemetryClient.StartOperation("Parent First")) + { + parent.Telemetry.Duration = TimeSpan.FromMilliseconds(250); + parent.Telemetry.Url = new Uri("http://parent.test.com/api/test"); + + using (var child = telemetryClient.StartOperation("Child 1")) + { + child.Telemetry.Success = true; + child.Telemetry.ResponseCode = "200"; + child.Telemetry.Duration = TimeSpan.FromMilliseconds(50); + child.Telemetry.Url = new Uri("http://child.test.com/api/test"); + child.Telemetry.Timestamp = DateTimeOffset.UtcNow; + + child.Telemetry.Properties.Add("httpMethod", HttpMethod.Get.ToString()); + child.Telemetry.Properties.Add("TestId", _testId); + + await _logger.LogAsync(child); + } + + ; + + await _logger.LogAsync(parent); + } + } +} \ No newline at end of file diff --git a/Tests/Logging/SeqTelemetryChannelTest.cs b/Tests/Logging/SeqTelemetryChannelTest.cs index 3d7aeec..cd8ceec 100644 --- a/Tests/Logging/SeqTelemetryChannelTest.cs +++ b/Tests/Logging/SeqTelemetryChannelTest.cs @@ -5,57 +5,56 @@ using Microsoft.ApplicationInsights.DataContracts; using PlanTempus.Core.Logging; using PlanTempus.Core.Telemetry; -namespace PlanTempus.Tests.Logging +namespace PlanTempus.X.TDD.Logging; + +[TestClass] +public class SeqTelemetryChannelTest : TestFixture { - [TestClass] - public class SeqTelemetryChannelTest : TestFixture + private CancellationTokenSource _cts; + private IMessageChannel _messageChannel; + private SeqBackgroundService _service; + private TelemetryClient _telemetryClient; + + [TestInitialize] + public void SetupThis() { - private IMessageChannel _messageChannel; - TelemetryClient _telemetryClient; - private SeqBackgroundService _service; - private CancellationTokenSource _cts; + //it is important to use the same MessageChannel as the BackgroundService uses + //we know that IMessageChannel _messageChannel; is registered via Autofac and manually injected into SeqBackgroundService + //so we can get it by calling the Autofac Container in this test. - [TestInitialize] - public void SetupThis() + _messageChannel = Container.Resolve>(); + _service = Container.Resolve(); + _telemetryClient = Container.Resolve(); + + _cts = new CancellationTokenSource(); + } + + [TestMethod] + public async Task Messages_ShouldBeProcessedFromQueue() + { + await _service.StartAsync(_cts.Token); + + for (var i = 0; i < 5; i++) { - //it is important to use the same MessageChannel as the BackgroundService uses - //we know that IMessageChannel _messageChannel; is registered via Autofac and manually injected into SeqBackgroundService - //so we can get it by calling the Autofac Container in this test. - - _messageChannel = Container.Resolve>(); - _service = Container.Resolve(); - _telemetryClient = Container.Resolve(); - - _cts = new CancellationTokenSource(); - } - - [TestMethod] - public async Task Messages_ShouldBeProcessedFromQueue() - { - await _service.StartAsync(_cts.Token); - - for (int i = 0; i < 5; i++) + var eventTelemetry = new EventTelemetry { - var eventTelemetry = new EventTelemetry - { - Name = "Test Event 3", - Timestamp = DateTimeOffset.UtcNow - }; + Name = "Test Event 3", + Timestamp = DateTimeOffset.UtcNow + }; - eventTelemetry.Properties.Add("TestId", Guid.NewGuid().ToString()); - eventTelemetry.Metrics.Add("TestMetric", 42.0); + eventTelemetry.Properties.Add("TestId", Guid.NewGuid().ToString()); + eventTelemetry.Metrics.Add("TestMetric", 42.0); - //we don't write to the _messageChannel.Writer.WriteAsync(eventTelemetry);, but the TelemetryClient which is configured to use SeqTelemetryChannel - _telemetryClient.TrackEvent(eventTelemetry); - } - - // wait for processing - await Task.Delay(5000); - - await _service.StopAsync(CancellationToken.None); - - bool hasMoreMessages = await _messageChannel.Reader.WaitToReadAsync(); - Assert.IsFalse(hasMoreMessages, "Queue should be empty after 5 seconds"); + //we don't write to the _messageChannel.Writer.WriteAsync(eventTelemetry);, but the TelemetryClient which is configured to use SeqTelemetryChannel + _telemetryClient.TrackEvent(eventTelemetry); } + + // wait for processing + await Task.Delay(5000); + + await _service.StopAsync(CancellationToken.None); + + var hasMoreMessages = await _messageChannel.Reader.WaitToReadAsync(); + Assert.IsFalse(hasMoreMessages, "Queue should be empty after 5 seconds"); } } \ No newline at end of file diff --git a/Tests/PasswordHasherTest.cs b/Tests/PasswordHasherTest.cs index 60521f6..455923b 100644 --- a/Tests/PasswordHasherTest.cs +++ b/Tests/PasswordHasherTest.cs @@ -1,89 +1,87 @@ using System.Diagnostics; -using Sodium; +using System.Text; using PlanTempus.Core; +using Sodium; -namespace PlanTempus.Tests +namespace PlanTempus.X.TDD; + +[TestClass] +public class PasswordHasherTests : TestFixture { - [TestClass] - public class PasswordHasherTests : TestFixture + [TestMethod] + public void MyTestMethod() { + var stopwatch = Stopwatch.StartNew(); - [TestMethod] - public void MyTestMethod() - { - var stopwatch = Stopwatch.StartNew(); + var salt = PasswordHash.ScryptGenerateSalt(); - byte[] salt = PasswordHash.ScryptGenerateSalt(); + // 2. Konverter password til byte[] + var passwordBytes = Encoding.UTF8.GetBytes("password123"); - // 2. Konverter password til byte[] - byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes("password123"); + // 3. Kald ScryptHashBinary korrekt + var hash = PasswordHash.ScryptHashBinary( + passwordBytes, + salt + ); - // 3. Kald ScryptHashBinary korrekt - byte[] hash = PasswordHash.ScryptHashBinary( - password: passwordBytes, - salt: salt, // 32-byte array - limit: PasswordHash.Strength.Interactive, - outputLength: 32 - ); + stopwatch.Stop(); + } - stopwatch.Stop(); - } - [TestMethod] - public void HashPassword_ShouldCreateValidHashFormat() - { - // Arrange - string password = "TestPassword123"; + [TestMethod] + public void HashPassword_ShouldCreateValidHashFormat() + { + // Arrange + var password = "TestPassword123"; - // Act - string hashedPassword = new SecureTokenizer().TokenizeText(password); - string[] parts = hashedPassword.Split('.'); + // Act + var hashedPassword = new SecureTokenizer().TokenizeText(password); + var parts = hashedPassword.Split('.'); - // Assert - Assert.AreEqual(3, parts.Length); - Assert.AreEqual("100000", parts[0]); - } + // Assert + Assert.AreEqual(3, parts.Length); + Assert.AreEqual("100000", parts[0]); + } - [TestMethod] - public void VerifyPassword_WithCorrectPassword_ShouldReturnTrue() - { - // Arrange - string password = "TestPassword123"; - string hashedPassword = new SecureTokenizer().TokenizeText(password); + [TestMethod] + public void VerifyPassword_WithCorrectPassword_ShouldReturnTrue() + { + // Arrange + var password = "TestPassword123"; + var hashedPassword = new SecureTokenizer().TokenizeText(password); - // Act - bool result = new SecureTokenizer().VerifyToken(hashedPassword, password); + // Act + var result = new SecureTokenizer().VerifyToken(hashedPassword, password); - // Assert - Assert.IsTrue(result); - } + // Assert + Assert.IsTrue(result); + } - [TestMethod] - public void VerifyPassword_WithWrongPassword_ShouldReturnFalse() - { - // Arrange - string correctPassword = "TestPassword123"; - string wrongPassword = "WrongPassword123"; - string hashedPassword = new SecureTokenizer().TokenizeText(correctPassword); + [TestMethod] + public void VerifyPassword_WithWrongPassword_ShouldReturnFalse() + { + // Arrange + var correctPassword = "TestPassword123"; + var wrongPassword = "WrongPassword123"; + var hashedPassword = new SecureTokenizer().TokenizeText(correctPassword); - // Act - bool result = new SecureTokenizer().VerifyToken(hashedPassword, wrongPassword); + // Act + var result = new SecureTokenizer().VerifyToken(hashedPassword, wrongPassword); - // Assert - Assert.IsFalse(result); - } + // Assert + Assert.IsFalse(result); + } - [TestMethod] - public void VerifyPassword_WithInvalidHashFormat_ShouldReturnFalse() - { - // Arrange - string password = "TestPassword123"; - string invalidHash = "InvalidHash"; + [TestMethod] + public void VerifyPassword_WithInvalidHashFormat_ShouldReturnFalse() + { + // Arrange + var password = "TestPassword123"; + var invalidHash = "InvalidHash"; - // Act - bool result = new SecureTokenizer().VerifyToken(invalidHash, password); + // Act + var result = new SecureTokenizer().VerifyToken(invalidHash, password); - // Assert - Assert.IsFalse(result); - } + // Assert + Assert.IsFalse(result); } } \ No newline at end of file diff --git a/Tests/PlanTempus.X.TDD.csproj b/Tests/PlanTempus.X.TDD.csproj index 396e620..0277cef 100644 --- a/Tests/PlanTempus.X.TDD.csproj +++ b/Tests/PlanTempus.X.TDD.csproj @@ -1,41 +1,41 @@  - - net8.0 - enable + + net8.0 + enable - false - true - + false + true + - - - - - - - - + + + + + + + + - - - - + + + + - - - + + + - - - Always - - - Always - - - Always - - + + + Always + + + Always + + + Always + + diff --git a/Tests/PostgresTests.cs b/Tests/PostgresTests.cs index a1e77c4..7d40669 100644 --- a/Tests/PostgresTests.cs +++ b/Tests/PostgresTests.cs @@ -1,95 +1,137 @@ using Autofac; -using System.Data; using Insight.Database; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using PlanTempus.Core.Sql.ConnectionFactory; using PlanTempus.Core.Sql; +using PlanTempus.Core.Sql.ConnectionFactory; +using Shouldly; -namespace PlanTempus.Tests +namespace PlanTempus.X.TDD; + +[TestClass] +public class PostgresTests : TestFixture { - [TestClass] - public class PostgresTests : TestFixture + private IDbConnectionFactory _connFactory; + private IDatabaseOperations _databaseOperations; + + [TestInitialize] + public void MyTestMethod() { - IDbConnectionFactory _connFactory; - IDatabaseOperations _databaseOperations; + _connFactory = Container.Resolve(); + _databaseOperations = Container.Resolve(); + } - [TestInitialize] - public void MyTestMethod() + [TestMethod] + public void TestDefaultConnection() + { + //https://stackoverflow.com/questions/69169247/how-to-create-idbconnection-factory-using-autofac-for-dapper + + using (var conn = _connFactory.Create()) { - _connFactory = Container.Resolve(); - _databaseOperations = Container.Resolve(); - } - [TestMethod] - public void TestDefaultConnection() - { - //https://stackoverflow.com/questions/69169247/how-to-create-idbconnection-factory-using-autofac-for-dapper - - using (var conn = _connFactory.Create()) - conn.ExecuteSql("SELECT 1 as p"); - - } - - [TestMethod] - public async Task TestScopeConnectionWithLogging() - { - using var db = _databaseOperations.CreateScope(nameof(TestScopeConnectionWithLogging)); - try - { - var user = await db.Connection.QuerySqlAsync( - "SELECT tablename FROM pg_tables limit 5"); - - db.Success(); - } - catch (Exception ex) - { - db.Error(ex); - throw; - } - } - [TestMethod] - public async Task TestScopeConnectionWithErrorLogging() - { - using var db = _databaseOperations.CreateScope(nameof(TestScopeConnectionWithLogging)); - try - { - var user = await db.Connection.QuerySqlAsync( - "SELECT tablename FROM pg_tabless limit 5"); - - db.Success(); - } - catch (Exception ex) - { - db.Error(ex); - } - } - [TestMethod] - public async Task TestSimpleDatabaseOperation() - { - try - { - await _databaseOperations.ExecuteAsync(async connection => - { - return await connection.QuerySqlAsync( - "SELECT tablename FROM pg_tables limit 5"); - }, nameof(TestSimpleDatabaseOperation)); - - } - catch (Exception ex) - { - throw; - } - } - [TestMethod] - public void SetupPostgresql_LISTEN() - { - //this is not in use a the moment... kind of premature test to get my mind in to gear - //var builder = new ConfigurationBuilder() - // .AddPostgresConfiguration(options => - // { - // options.ConnectionString = "Host=192.168.1.57;Database=ptdb01;Username=postgres;Password=3911"; - // options.Channel = "config_changes"; - // options.ConfigurationQuery = @"select * from dev.app_configuration"; - // }); + conn.ExecuteSql("SELECT 1 as p"); } } + + [TestMethod] + public async Task TestScopeConnectionWithLogging() + { + using var db = _databaseOperations.CreateScope(nameof(TestScopeConnectionWithLogging)); + try + { + var user = await db.Connection.QuerySqlAsync( + "SELECT tablename FROM pg_tables limit 5"); + + db.Success(); + } + catch (Exception ex) + { + db.Error(ex); + throw; + } + } + + [TestMethod] + public async Task TestScopeConnectionWithErrorLogging() + { + using var db = _databaseOperations.CreateScope(nameof(TestScopeConnectionWithLogging)); + try + { + var user = await db.Connection.QuerySqlAsync( + "SELECT tablename FROM pg_tables limit 5"); + + db.Success(); + } + catch (Exception ex) + { + db.Error(ex); + } + } + + [TestMethod] + public async Task TestForUniqueUserEmail() + { + using var db = _databaseOperations.CreateScope(nameof(TestForUniqueUserEmail)); + try + { + var sql = @" + INSERT INTO system.users(email, password_hash, security_stamp, email_confirmed, + access_failed_count, lockout_enabled, + is_active) + VALUES(@Email, @PasswordHash, @SecurityStamp, @EmailConfirmed, + @AccessFailedCount, @LockoutEnabled, @IsActive) + RETURNING id, created_at, email, is_active"; + + var parameters = new + { + Email = "elon.musk@mars.com", + PasswordHash = "MartianRover2025", + SecurityStamp = "MarsOrBust", + EmailConfirmed = true, + AccessFailedCount = 0, + LockoutEnabled = false, + IsActive = true + }; + + var user = await db.Connection.QuerySqlAsync(sql, parameters); + + user.ShouldNotBeNull(); + // ((string)user.email).ShouldBe("elon.musk@mars.com"); + // ((bool)user.is_active).ShouldBeTrue(); + + db.Success(); + } + catch (Exception ex) + { + db.Error(ex); + } + } + + + [TestMethod] + public async Task TestSimpleDatabaseOperation() + { + try + { + await _databaseOperations.ExecuteAsync(async connection => + { + return await connection.QuerySqlAsync( + "SELECT tablename FROM pg_tables limit 5"); + }, nameof(TestSimpleDatabaseOperation)); + } + catch (Exception ex) + { + throw; + } + } + + [TestMethod] + public void SetupPostgresql_LISTEN() + { + //this is not in use a the moment... kind of premature test to get my mind in to gear + //var builder = new ConfigurationBuilder() + // .AddPostgresConfiguration(options => + // { + // options.ConnectionString = "Host=192.168.1.57;Database=ptdb01;Username=postgres;Password=3911"; + // options.Channel = "config_changes"; + // options.ConfigurationQuery = @"select * from dev.app_configuration"; + // }); + } } \ No newline at end of file diff --git a/Tests/SecureConnectionStringTests.cs b/Tests/SecureConnectionStringTests.cs index 791fbf4..5765328 100644 --- a/Tests/SecureConnectionStringTests.cs +++ b/Tests/SecureConnectionStringTests.cs @@ -1,6 +1 @@ - - -namespace PlanTempus.Tests -{ - -} \ No newline at end of file +namespace PlanTempus.X.TDD; \ No newline at end of file diff --git a/Tests/TestFixture.cs b/Tests/TestFixture.cs index 7d6b103..941f54b 100644 --- a/Tests/TestFixture.cs +++ b/Tests/TestFixture.cs @@ -1,96 +1,99 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; using Autofac; using Microsoft.ApplicationInsights; using Microsoft.Extensions.Logging; using PlanTempus.Core.Configurations; using PlanTempus.Core.Configurations.JsonConfigProvider; +using PlanTempus.Core.Logging; using PlanTempus.Core.ModuleRegistry; -namespace PlanTempus.Tests +using PlanTempus.Database.ModuleRegistry; + +namespace PlanTempus.X.TDD; + +/// +/// Act as base class for tests. Avoids duplication of test setup code +/// +[TestClass] +public abstract class TestFixture { - /// - /// Act as base class for tests. Avoids duplication of test setup code - /// - [TestClass] - public abstract partial class TestFixture + private readonly string _configurationFilePath; + + protected TestFixture() : this(null) { - private readonly string _configurationFilePath; + } - protected IContainer Container { get; private set; } - protected ContainerBuilder ContainerBuilder { get; private set; } + public TestFixture(string configurationFilePath) + { + if (configurationFilePath is not null) + _configurationFilePath = configurationFilePath?.TrimEnd('/') + "/"; - public virtual IConfigurationRoot Configuration() + CreateContainerBuilder(); + Container = ContainerBuilder.Build(); + } + + protected IContainer Container { get; private set; } + protected ContainerBuilder ContainerBuilder { get; private set; } + + public virtual IConfigurationRoot Configuration() + { + var configuration = new ConfigurationBuilder() + .AddJsonFile($"{_configurationFilePath}appconfiguration.dev.json") + .Build(); + + return configuration; + } + + protected virtual void CreateContainerBuilder() + { + var configuration = Configuration(); + + //var logger = new LoggerConfiguration() + // .MinimumLevel.Verbose() + // .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning) + // .MinimumLevel.Override("System", Serilog.Events.LogEventLevel.Error) + // .WriteTo.Seq("http://localhost:5341", apiKey: "Gt8hS9ClGNfOCAdswDlW") + // .WriteTo.ApplicationInsights(configuration.Get("ApplicationInsights:ConnectionString"), + // TelemetryConverter.Traces) + // .Enrich.FromLogContext() + // .Enrich.WithMachineName() + // .CreateLogger(); + + var builder = new ContainerBuilder(); + + builder.RegisterGeneric(typeof(Logger<>)) + .As(typeof(ILogger<>)) + .SingleInstance(); + + + builder.RegisterModule(new DbPostgreSqlModule { - var configuration = new ConfigurationBuilder() - .AddJsonFile($"{_configurationFilePath}appconfiguration.dev.json") - .Build(); + ConnectionString = configuration.GetConnectionString("DefaultConnection") + }); - return configuration; - } - - protected TestFixture() : this(null) { } - public TestFixture(string configurationFilePath) + builder.RegisterModule(new TelemetryModule { - if (configurationFilePath is not null) - _configurationFilePath = configurationFilePath?.TrimEnd('/') + "/"; - - CreateContainerBuilder(); - Container = ContainerBuilder.Build(); - } - protected virtual void CreateContainerBuilder() + TelemetryConfig = configuration.GetSection("ApplicationInsights").ToObject() + }); + builder.RegisterModule(new SeqLoggingModule { - IConfigurationRoot configuration = Configuration(); - - //var logger = new LoggerConfiguration() - // .MinimumLevel.Verbose() - // .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning) - // .MinimumLevel.Override("System", Serilog.Events.LogEventLevel.Error) - // .WriteTo.Seq("http://localhost:5341", apiKey: "Gt8hS9ClGNfOCAdswDlW") - // .WriteTo.ApplicationInsights(configuration.Get("ApplicationInsights:ConnectionString"), - // TelemetryConverter.Traces) - // .Enrich.FromLogContext() - // .Enrich.WithMachineName() - // .CreateLogger(); - - var builder = new ContainerBuilder(); - - builder.RegisterGeneric(typeof(Logger<>)) - .As(typeof(ILogger<>)) - .SingleInstance(); + SeqConfiguration = configuration.GetSection("SeqConfiguration").ToObject() + }); - builder.RegisterModule(new Database.ModuleRegistry.DbPostgreSqlModule - { - ConnectionString = configuration.GetConnectionString("DefaultConnection") - }); + ContainerBuilder = builder; + } - builder.RegisterModule(new TelemetryModule - { - TelemetryConfig = configuration.GetSection("ApplicationInsights").ToObject() - }); - builder.RegisterModule(new SeqLoggingModule - { - SeqConfiguration = configuration.GetSection("SeqConfiguration").ToObject() + [TestCleanup] + public void CleanUp() + { + Trace.Flush(); + var telemetryClient = Container.Resolve(); + telemetryClient.Flush(); - }); - - - ContainerBuilder = builder; - } - - [TestCleanup] - public void CleanUp() + if (Container != null) { - Trace.Flush(); - var telemetryClient = Container.Resolve(); - telemetryClient.Flush(); - - if (Container != null) - { - Container.Dispose(); - Container = null; - } + Container.Dispose(); + Container = null; } - } } \ No newline at end of file