wip on tests

This commit is contained in:
Janus Knudsen 2025-02-18 17:35:00 +01:00
parent 440087c43b
commit 75e0406251
4 changed files with 234 additions and 165 deletions

View file

@ -11,131 +11,132 @@ using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests.ConfigurationTests namespace Tests.ConfigurationTests
{ {
[TestClass] [TestClass]
public class JsonConfigurationProviderTests : TestFixture public class JsonConfigurationProviderTests : TestFixture
{ {
[TestMethod] public JsonConfigurationProviderTests() : base("ConfigurationTests") { }
public void GetSection_ShouldReturnCorrectFeatureSection() [TestMethod]
{ public void GetSection_ShouldReturnCorrectFeatureSection()
// Arrange {
var expectedJObject = JObject.Parse(@"{ // Arrange
var expectedJObject = JObject.Parse(@"{
'Enabled': true, 'Enabled': true,
'RolloutPercentage': 25, 'RolloutPercentage': 25,
'AllowedUserGroups': ['beta'] 'AllowedUserGroups': ['beta']
}") as JToken; }") as JToken;
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.AddJsonFile("appconfiguration.dev.json") .AddJsonFile("appconfiguration.dev.json")
.Build(); .Build();
// Act // Act
var section = builder.GetSection("Feature"); var section = builder.GetSection("Feature");
// Assert // Assert
section.Should().NotBeNull(); section.Should().NotBeNull();
section.Value.Should().BeEquivalentTo(expectedJObject); section.Value.Should().BeEquivalentTo(expectedJObject);
} }
[TestMethod] [TestMethod]
public void Get_ShouldReturnCorrectFeatureObject() public void Get_ShouldReturnCorrectFeatureObject()
{ {
// Arrange // Arrange
var expectedFeature = new Feature var expectedFeature = new Feature
{ {
Enabled = true, Enabled = true,
RolloutPercentage = 25, RolloutPercentage = 25,
AllowedUserGroups = new() { "beta" } AllowedUserGroups = new() { "beta" }
}; };
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.AddJsonFile("appconfiguration.dev.json") .AddJsonFile("appconfiguration.dev.json")
.Build(); .Build();
// Act // Act
var actualFeature = builder.GetSection("Feature").ToObject<Feature>(); var actualFeature = builder.GetSection("Feature").ToObject<Feature>();
#pragma warning disable CS0618 // Type or member is obsolete #pragma warning disable CS0618 // Type or member is obsolete
var actualFeatureObsoleted = builder.GetSection("Feature").Get<Feature>(); var actualFeatureObsoleted = builder.GetSection("Feature").Get<Feature>();
#pragma warning restore CS0618 // Type or member is obsolete #pragma warning restore CS0618 // Type or member is obsolete
// Assert // Assert
actualFeature.Should().BeEquivalentTo(expectedFeature); actualFeature.Should().BeEquivalentTo(expectedFeature);
actualFeatureObsoleted.Should().BeEquivalentTo(expectedFeature); actualFeatureObsoleted.Should().BeEquivalentTo(expectedFeature);
} }
[TestMethod] [TestMethod]
public void Get_ShouldReturnCorrectValueAsString() public void Get_ShouldReturnCorrectValueAsString()
{ {
// Arrange // Arrange
var expectedFeature = "123"; var expectedFeature = "123";
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.AddJsonFile("appconfiguration.dev.json") .AddJsonFile("appconfiguration.dev.json")
.Build(); .Build();
// Act // Act
var actualFeature = builder.GetSection("AnotherSetting").Get<string>("Thresholds:High"); var actualFeature = builder.GetSection("AnotherSetting").Get<string>("Thresholds:High");
// Assert // Assert
actualFeature.Should().BeEquivalentTo(expectedFeature); actualFeature.Should().BeEquivalentTo(expectedFeature);
} }
/// <summary> /// <summary>
/// Testing a stupid indexer for compability with Microsoft ConfigurationBuilder /// Testing a stupid indexer for compability with Microsoft ConfigurationBuilder
/// </summary> /// </summary>
[TestMethod] [TestMethod]
public void Indexer_ShouldReturnValueAsString() public void Indexer_ShouldReturnValueAsString()
{ {
// Arrange // Arrange
var expected = "SHA256"; var expected = "SHA256";
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.AddJsonFile("appconfiguration.dev.json") .AddJsonFile("appconfiguration.dev.json")
.Build(); .Build();
// Act // Act
var actual = builder["Authentication"]; var actual = builder["Authentication"];
// Assert // Assert
actual.Should().BeEquivalentTo(expected); actual.Should().BeEquivalentTo(expected);
} }
[TestMethod] [TestMethod]
public void Get_ShouldReturnCorrectValueAsInt() public void Get_ShouldReturnCorrectValueAsInt()
{ {
// Arrange // Arrange
var expectedFeature = 22; var expectedFeature = 22;
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.AddJsonFile("appconfiguration.dev.json") .AddJsonFile("appconfiguration.dev.json")
.Build(); .Build();
// Act // Act
var actualFeature = builder.GetSection("AnotherSetting:Temperature").Get<int>("Indoor:Max:Limit"); var actualFeature = builder.GetSection("AnotherSetting:Temperature").Get<int>("Indoor:Max:Limit");
// Assert // Assert
actualFeature.Should().Be(expectedFeature); actualFeature.Should().Be(expectedFeature);
} }
[TestMethod] [TestMethod]
public void Get_ShouldReturnCorrectValueAsBool() public void Get_ShouldReturnCorrectValueAsBool()
{ {
// Arrange // Arrange
var expectedFeature = true; var expectedFeature = true;
var configRoot = new ConfigurationBuilder() var configRoot = new ConfigurationBuilder()
.AddJsonFile("appconfiguration.dev.json") .AddJsonFile("appconfiguration.dev.json")
.AddSmartConfig() .AddSmartConfig()
.Build(); .Build();
// Act // Act
var actualFeature = configRoot.Get<bool>("Database:UseSSL"); var actualFeature = configRoot.Get<bool>("Database:UseSSL");
// Assert // Assert
actualFeature.Should().Be(expectedFeature); actualFeature.Should().Be(expectedFeature);
} }
} }
public class Feature public class Feature
{ {
public bool Enabled { get; set; } public bool Enabled { get; set; }
public int RolloutPercentage { get; set; } public int RolloutPercentage { get; set; }
public List<string> AllowedUserGroups { get; set; } public List<string> AllowedUserGroups { get; set; }
} }
} }

View file

@ -0,0 +1,60 @@
{
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Host=192.168.1.57;Port=5432;Database=ptmain;User Id=sathumper;Password=3911;"
},
"ApplicationInsights": {
"ConnectionString": "InstrumentationKey=6d2e76ee-5343-4691-a5e3-81add43cb584;IngestionEndpoint=https://northeurope-0.in.applicationinsights.azure.com/"
},
"Authentication": "SHA256",
"Feature": {
"Enabled": true,
"RolloutPercentage": 25,
"AllowedUserGroups": [ "beta" ]
},
"AnotherSetting": {
"Thresholds": {
"High": "123",
"Low": "-1"
},
"Temperature": {
"Indoor": {
"Max": { "Limit": 22 },
"Min": { "Limit": 18 }
},
"Outdoor": {
"Max": { "Limit": 12 },
"Min": { "Limit": 9 }
}
}
},
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "Seq",
"Args": {
"serverUrl": "http://localhost:5341",
"apiKey": ""
}
}
],
"Enrich": [
"WithMachineName",
"WithThreadId",
"WithProcessId",
"WithEnvironmentName"
],
"Properties": {
"Application": "PlanTempus"
}
}
}

View file

@ -8,87 +8,92 @@ using Microsoft.Extensions.Logging;
using Core.Configurations.JsonConfigProvider; using Core.Configurations.JsonConfigProvider;
namespace Tests namespace Tests
{ {
/// <summary> /// <summary>
/// Act as base class for tests. Avoids duplication of test setup code /// Act as base class for tests. Avoids duplication of test setup code
/// </summary> /// </summary>
[TestClass] [TestClass]
public abstract partial class TestFixture public abstract partial class TestFixture
{ {
protected IContainer Container { get; private set; } private readonly string _configurationFilePath;
protected ContainerBuilder ContainerBuilder { get; private set; }
public virtual IConfigurationRoot Configuration() protected IContainer Container { get; private set; }
{ protected ContainerBuilder ContainerBuilder { get; private set; }
var configuration = new ConfigurationBuilder()
.AddJsonFile("appconfiguration.dev.json")
.Build();
return configuration; public virtual IConfigurationRoot Configuration()
} {
var configuration = new ConfigurationBuilder()
.AddJsonFile($"{_configurationFilePath}appconfiguration.dev.json")
.Build();
protected TestFixture() return configuration;
{ }
CreateContainerBuilder();
Container = ContainerBuilder.Build();
}
protected virtual void CreateContainerBuilder() protected TestFixture()
{ {
IConfigurationRoot configuration = Configuration(); CreateContainerBuilder();
Container = ContainerBuilder.Build();
}
public TestFixture(string configurationFilePath) : this()
{
_configurationFilePath = configurationFilePath;
}
protected virtual void CreateContainerBuilder()
{
IConfigurationRoot configuration = Configuration();
//var logger = new LoggerConfiguration() //var logger = new LoggerConfiguration()
// .MinimumLevel.Verbose() // .MinimumLevel.Verbose()
// .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning) // .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning)
// .MinimumLevel.Override("System", Serilog.Events.LogEventLevel.Error) // .MinimumLevel.Override("System", Serilog.Events.LogEventLevel.Error)
// .WriteTo.Seq("http://localhost:5341", apiKey: "Gt8hS9ClGNfOCAdswDlW") // .WriteTo.Seq("http://localhost:5341", apiKey: "Gt8hS9ClGNfOCAdswDlW")
// .WriteTo.ApplicationInsights(configuration.Get<string>("ApplicationInsights:ConnectionString"), // .WriteTo.ApplicationInsights(configuration.Get<string>("ApplicationInsights:ConnectionString"),
// TelemetryConverter.Traces) // TelemetryConverter.Traces)
// .Enrich.FromLogContext() // .Enrich.FromLogContext()
// .Enrich.WithMachineName() // .Enrich.WithMachineName()
// .CreateLogger(); // .CreateLogger();
//Log.Logger = logger; //Log.Logger = logger;
//Log.Logger.Verbose("Is thos work"); //Log.Logger.Verbose("Is thos work");
var builder = new ContainerBuilder(); var builder = new ContainerBuilder();
//builder.Register(c => new SerilogLoggerFactory(logger)) //builder.Register(c => new SerilogLoggerFactory(logger))
// .As<ILoggerFactory>() // .As<ILoggerFactory>()
// .SingleInstance(); // .SingleInstance();
builder.RegisterGeneric(typeof(Logger<>)) builder.RegisterGeneric(typeof(Logger<>))
.As(typeof(ILogger<>)) .As(typeof(ILogger<>))
.SingleInstance(); .SingleInstance();
builder.RegisterModule(new Database.ModuleRegistry.DbPostgreSqlModule builder.RegisterModule(new Database.ModuleRegistry.DbPostgreSqlModule
{ {
ConnectionString = configuration.GetConnectionString("DefaultConnection") ConnectionString = configuration.GetConnectionString("DefaultConnection")
}); });
builder.RegisterModule(new Core.ModuleRegistry.TelemetryModule builder.RegisterModule(new Core.ModuleRegistry.TelemetryModule
{ {
TelemetryConfig = configuration.GetSection("ApplicationInsights").ToObject<Core.ModuleRegistry.TelemetryConfig>() TelemetryConfig = configuration.GetSection("ApplicationInsights").ToObject<Core.ModuleRegistry.TelemetryConfig>()
}); });
ContainerBuilder = builder; ContainerBuilder = builder;
} }
[TestCleanup] [TestCleanup]
public void CleanUp() public void CleanUp()
{ {
Trace.Flush(); Trace.Flush();
var telemetryClient = Container.Resolve<TelemetryClient>(); var telemetryClient = Container.Resolve<TelemetryClient>();
telemetryClient.Flush(); telemetryClient.Flush();
if (Container != null) if (Container != null)
{ {
Container.Dispose(); Container.Dispose();
Container = null; Container = null;
} }
} }
} }
} }

View file

@ -30,6 +30,9 @@
<None Update="appconfiguration.dev.json"> <None Update="appconfiguration.dev.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>
<None Update="ConfigurationTests\appconfiguration.dev.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup> </ItemGroup>
</Project> </Project>