Adds Configuration Manager + tests
This commit is contained in:
parent
55e65a1b21
commit
384cc3c6fd
16 changed files with 657 additions and 137 deletions
43
Tests/CodeSnippets/TestPostgresLISTENNOTIFY.cs
Normal file
43
Tests/CodeSnippets/TestPostgresLISTENNOTIFY.cs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
using Npgsql;
|
||||
|
||||
class TestPostgresLISTENNOTIFY
|
||||
{
|
||||
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 conn.OpenAsync();
|
||||
|
||||
Console.WriteLine("Forbundet til databasen. Lytter efter notifikationer...");
|
||||
|
||||
conn.Notification += (o, e) =>
|
||||
{
|
||||
Console.WriteLine($"Notifikation modtaget:");
|
||||
Console.WriteLine($" PID: {e.PID}");
|
||||
Console.WriteLine($" Kanal: {e.Channel}");
|
||||
Console.WriteLine($" Payload: {e.Payload}");
|
||||
Console.WriteLine("------------------------");
|
||||
};
|
||||
|
||||
await using (var cmd = new NpgsqlCommand("LISTEN config_changes;", conn))
|
||||
{
|
||||
await cmd.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
Console.WriteLine("Tryk på en tast for at stoppe...");
|
||||
|
||||
while (!Console.KeyAvailable)
|
||||
{
|
||||
await conn.WaitAsync();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Der opstod en fejl: {ex.Message}");
|
||||
Console.WriteLine($"Stack trace: {ex.StackTrace}");
|
||||
}
|
||||
}
|
||||
}
|
||||
171
Tests/TestConfigurationManagement.cs
Normal file
171
Tests/TestConfigurationManagement.cs
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using Moq;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using Tests;
|
||||
using Core.Configurations.ConfigurationManager;
|
||||
|
||||
namespace Configuration.Core.Tests;
|
||||
|
||||
[TestClass]
|
||||
public class ConfigurationTests : TestFixture
|
||||
{
|
||||
private Mock<IConfigurationRepository> _mockRepo;
|
||||
private KeyValueConfigurationBuilder _builder;
|
||||
|
||||
[TestInitialize]
|
||||
public void Init()
|
||||
{
|
||||
_mockRepo = new Mock<IConfigurationRepository>();
|
||||
_builder = new KeyValueConfigurationBuilder(_mockRepo.Object);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task LoadConfiguration_WithValidData_BuildsCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
var configurations = new List<AppConfiguration>
|
||||
{
|
||||
new AppConfiguration
|
||||
{
|
||||
Key = "Email:Templates:Welcome",
|
||||
Value = @"{""subject"":""Welcome"",""sender"":""test@company.com""}",
|
||||
ValidFrom = DateTime.UtcNow.AddDays(-1),
|
||||
ExpiresAt = DateTime.UtcNow.AddDays(1)
|
||||
}
|
||||
};
|
||||
|
||||
_mockRepo.Setup(r => r.GetActiveConfigurations())
|
||||
.ReturnsAsync(configurations);
|
||||
|
||||
// Act
|
||||
await _builder.LoadConfiguration();
|
||||
var config = _builder.Build();
|
||||
|
||||
// Assert
|
||||
Assert.IsNotNull(config);
|
||||
Assert.AreEqual("Welcome", config["Email:Templates:Welcome:subject"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task LoadConfiguration_WithExpiredData_NotIncluded()
|
||||
{
|
||||
// Arrange
|
||||
var configurations = new List<AppConfiguration>
|
||||
{
|
||||
new AppConfiguration
|
||||
{
|
||||
Key = "Test:Key",
|
||||
Value = @"{""value"":""test""}",
|
||||
ValidFrom = DateTime.UtcNow.AddDays(1),
|
||||
ExpiresAt = DateTime.UtcNow.AddDays(2)
|
||||
}
|
||||
};
|
||||
|
||||
_mockRepo.Setup(r => r.GetActiveConfigurations())
|
||||
.ReturnsAsync(new List<AppConfiguration>());
|
||||
|
||||
// Act
|
||||
await _builder.LoadConfiguration();
|
||||
var config = _builder.Build();
|
||||
|
||||
// Assert
|
||||
Assert.IsNull(config["Test:Key:value"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddKeyValue_WithNestedKeys_BuildsCorrectHierarchy()
|
||||
{
|
||||
// Arrange
|
||||
var key = "Level1:Level2:Level3";
|
||||
var value = @"{""setting"":""value""}";
|
||||
|
||||
// Act
|
||||
_builder.AddKeyValue(key, value);
|
||||
var config = _builder.Build();
|
||||
|
||||
// Assert
|
||||
Assert.AreEqual("value", config["Level1:Level2:Level3:setting"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetSection_ReturnsCorrectSubSection()
|
||||
{
|
||||
// Arrange
|
||||
var configurations = new List<AppConfiguration>
|
||||
{
|
||||
new AppConfiguration
|
||||
{
|
||||
Key = "Parent:Child",
|
||||
Value = @"{""setting"":""value""}",
|
||||
ValidFrom = DateTime.UtcNow.AddDays(-1)
|
||||
}
|
||||
};
|
||||
|
||||
_mockRepo.Setup(r => r.GetActiveConfigurations())
|
||||
.ReturnsAsync(configurations);
|
||||
|
||||
// Act
|
||||
await _builder.LoadConfiguration();
|
||||
var config = _builder.Build();
|
||||
var section = config.GetSection("Parent");
|
||||
|
||||
// Assert
|
||||
Assert.AreEqual("value", section["Child:setting"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Configuration_ShouldMapToTypedClass()
|
||||
{
|
||||
// Arrange
|
||||
var configData = new JObject
|
||||
{
|
||||
["Email"] = new JObject
|
||||
{
|
||||
["Templates"] = new JObject
|
||||
{
|
||||
["Welcome"] = new JObject
|
||||
{
|
||||
["subject"] = "Welcome to our service",
|
||||
["template"] = "welcome-template.html",
|
||||
["sender"] = "noreply@test.com",
|
||||
["settings"] = new JObject
|
||||
{
|
||||
["isEnabled"] = true,
|
||||
["retryCount"] = 3
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var configuration = new JsonConfiguration(configData, new Microsoft.Extensions.Configuration.ConfigurationReloadToken());
|
||||
|
||||
// Act
|
||||
var welcomeConfig = configuration.GetSection("Email:Templates:Welcome").Get<WelcomeEmailConfig>();
|
||||
|
||||
// Assert
|
||||
Assert.IsNotNull(welcomeConfig);
|
||||
Assert.AreEqual("Welcome to our service", welcomeConfig.Subject);
|
||||
Assert.AreEqual("welcome-template.html", welcomeConfig.Template);
|
||||
Assert.AreEqual("noreply@test.com", welcomeConfig.Sender);
|
||||
Assert.IsTrue(welcomeConfig.Settings.IsEnabled);
|
||||
Assert.AreEqual(3, welcomeConfig.Settings.RetryCount);
|
||||
}
|
||||
|
||||
public class WelcomeEmailConfig
|
||||
{
|
||||
public string Subject { get; set; }
|
||||
public string Template { get; set; }
|
||||
public string Sender { get; set; }
|
||||
public EmailSettings Settings { get; set; }
|
||||
}
|
||||
|
||||
public class EmailSettings
|
||||
{
|
||||
public bool IsEnabled { get; set; }
|
||||
public int RetryCount { get; set; }
|
||||
}
|
||||
}
|
||||
|
|
@ -9,89 +9,89 @@ using Microsoft.VisualStudio.TestTools.UnitTesting;
|
|||
|
||||
namespace Tests
|
||||
{
|
||||
/// <summary>
|
||||
/// Act as base class for tests. Avoids duplication of test setup code
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public abstract partial class TestFixture
|
||||
{
|
||||
protected IContainer Container { get; private set; }
|
||||
protected ContainerBuilder ContainerBuilder { get; private set; }
|
||||
/// <summary>
|
||||
/// Act as base class for tests. Avoids duplication of test setup code
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public abstract partial class TestFixture
|
||||
{
|
||||
protected IContainer Container { get; private set; }
|
||||
protected ContainerBuilder ContainerBuilder { get; private set; }
|
||||
|
||||
|
||||
[AssemblyInitialize]
|
||||
public static void AssemblySetup(TestContext tc)
|
||||
{
|
||||
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
|
||||
[AssemblyInitialize]
|
||||
public static void AssemblySetup(TestContext tc)
|
||||
{
|
||||
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
|
||||
|
||||
var envConfiguration = new ConfigurationBuilder()
|
||||
.AddEnvironmentVariables()
|
||||
.Build();
|
||||
var envConfiguration = new ConfigurationBuilder()
|
||||
.AddEnvironmentVariables()
|
||||
.Build();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public virtual IConfigurationRoot Configuration()
|
||||
{
|
||||
public virtual IConfigurationRoot Configuration()
|
||||
{
|
||||
|
||||
IConfigurationBuilder configBuilder = Core.Configurations.ConfigurationManager.AppConfigBuilder("appsettings.dev.json");
|
||||
IConfigurationRoot configuration = configBuilder.Build();
|
||||
IConfigurationBuilder configBuilder = Core.Configurations.AzureConfigurationManager.AppConfigBuilder("appsettings.dev.json");
|
||||
IConfigurationRoot configuration = configBuilder.Build();
|
||||
|
||||
return configuration;
|
||||
}
|
||||
return configuration;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Should not be overriden. Rather override PreArrangeAll to setup data needed for a test class.
|
||||
/// Override PrebuildContainer with a method that does nothing to prevent early build of IOC container
|
||||
/// </summary>
|
||||
[TestInitialize]
|
||||
public void Setup()
|
||||
{
|
||||
CreateContainerBuilder();
|
||||
Container = ContainerBuilder.Build();
|
||||
Insight.Database.Providers.PostgreSQL.PostgreSQLInsightDbProvider.RegisterProvider();
|
||||
}
|
||||
/// <summary>
|
||||
/// Should not be overriden. Rather override PreArrangeAll to setup data needed for a test class.
|
||||
/// Override PrebuildContainer with a method that does nothing to prevent early build of IOC container
|
||||
/// </summary>
|
||||
[TestInitialize]
|
||||
public void Setup()
|
||||
{
|
||||
CreateContainerBuilder();
|
||||
Container = ContainerBuilder.Build();
|
||||
Insight.Database.Providers.PostgreSQL.PostgreSQLInsightDbProvider.RegisterProvider();
|
||||
}
|
||||
|
||||
|
||||
protected virtual void CreateContainerBuilder()
|
||||
{
|
||||
IConfigurationRoot configuration = Configuration();
|
||||
protected virtual void CreateContainerBuilder()
|
||||
{
|
||||
IConfigurationRoot configuration = Configuration();
|
||||
|
||||
var builder = new ContainerBuilder();
|
||||
builder.RegisterInstance(new LoggerFactory())
|
||||
.As<ILoggerFactory>();
|
||||
var builder = new ContainerBuilder();
|
||||
builder.RegisterInstance(new LoggerFactory())
|
||||
.As<ILoggerFactory>();
|
||||
|
||||
builder.RegisterGeneric(typeof(Logger<>))
|
||||
.As(typeof(ILogger<>))
|
||||
.SingleInstance();
|
||||
builder.RegisterGeneric(typeof(Logger<>))
|
||||
.As(typeof(ILogger<>))
|
||||
.SingleInstance();
|
||||
|
||||
builder.RegisterModule(new Core.ModuleRegistry.DbPostgreSqlModule
|
||||
{
|
||||
ConnectionString = configuration.GetConnectionString("ptdb")
|
||||
});
|
||||
builder.RegisterModule(new Core.ModuleRegistry.DbPostgreSqlModule
|
||||
{
|
||||
ConnectionString = configuration.GetConnectionString("ptdb")
|
||||
});
|
||||
|
||||
builder.RegisterModule(new Core.ModuleRegistry.TelemetryModule
|
||||
{
|
||||
TelemetryConfig = configuration.GetSection("ApplicationInsights").Get<Core.ModuleRegistry.TelemetryConfig>()
|
||||
});
|
||||
builder.RegisterModule(new Core.ModuleRegistry.TelemetryModule
|
||||
{
|
||||
TelemetryConfig = configuration.GetSection("ApplicationInsights").Get<Core.ModuleRegistry.TelemetryConfig>()
|
||||
});
|
||||
|
||||
|
||||
|
||||
ContainerBuilder = builder;
|
||||
}
|
||||
ContainerBuilder = builder;
|
||||
}
|
||||
|
||||
[TestCleanup]
|
||||
public void CleanUp()
|
||||
{
|
||||
Trace.Flush();
|
||||
var telemetryClient = Container.Resolve<TelemetryClient>();
|
||||
telemetryClient.Flush();
|
||||
[TestCleanup]
|
||||
public void CleanUp()
|
||||
{
|
||||
Trace.Flush();
|
||||
var telemetryClient = Container.Resolve<TelemetryClient>();
|
||||
telemetryClient.Flush();
|
||||
|
||||
if (Container != null)
|
||||
{
|
||||
Container.Dispose();
|
||||
Container = null;
|
||||
}
|
||||
}
|
||||
if (Container != null)
|
||||
{
|
||||
Container.Dispose();
|
||||
Container = null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -11,6 +11,7 @@
|
|||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
|
||||
<PackageReference Include="moq" Version="4.20.72" />
|
||||
<PackageReference Include="MSTest.TestAdapter" Version="3.1.1" />
|
||||
<PackageReference Include="MSTest.TestFramework" Version="3.1.1" />
|
||||
</ItemGroup>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue