This commit is contained in:
Janus C. H. Knudsen 2025-03-07 00:17:08 +01:00
parent 0010a32248
commit ddb6abc14e
14 changed files with 754 additions and 718 deletions

View file

@ -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)
{

View file

@ -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()
@ -58,9 +56,9 @@ public class SetupConfigurationTests : TestFixture
// 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<dynamic>(@"
@ -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
@ -129,8 +127,8 @@ public class SetupConfigurationTests : TestFixture
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()
});

View file

@ -1,18 +1,19 @@
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.X.TDD.ConfigurationTests;
namespace PlanTempus.Tests.ConfigurationTests
{
[TestClass]
public class JsonConfigurationProviderTests : TestFixture
{
const string _testFolder = "ConfigurationTests/";
private const string _testFolder = "ConfigurationTests/";
public JsonConfigurationProviderTests() : base(_testFolder) { }
public JsonConfigurationProviderTests() : base(_testFolder)
{
}
[TestMethod]
@ -45,7 +46,7 @@ namespace PlanTempus.Tests.ConfigurationTests
{
Enabled = true,
RolloutPercentage = 25,
AllowedUserGroups = new() { "beta" }
AllowedUserGroups = new List<string> { "beta" }
};
var builder = new ConfigurationBuilder()
@ -60,8 +61,8 @@ namespace PlanTempus.Tests.ConfigurationTests
// Assert
actualFeature.ShouldBeEquivalentTo(expectedFeature);
actualFeatureObsoleted.ShouldBeEquivalentTo(expectedFeature);
}
[TestMethod]
public void Get_ShouldReturnCorrectValueAsString()
{
@ -78,6 +79,7 @@ namespace PlanTempus.Tests.ConfigurationTests
// Assert
actualFeature.ShouldBeEquivalentTo(expectedFeature);
}
/// <summary>
/// Testing a stupid indexer for compability with Microsoft ConfigurationBuilder
/// </summary>
@ -97,6 +99,7 @@ namespace PlanTempus.Tests.ConfigurationTests
// Assert
actual.ShouldBeEquivalentTo(expected);
}
[TestMethod]
public void Get_ShouldReturnCorrectValueAsInt()
{
@ -113,6 +116,7 @@ namespace PlanTempus.Tests.ConfigurationTests
// Assert
actualFeature.ShouldBe(expectedFeature);
}
[TestMethod]
public void Get_ShouldReturnCorrectValueAsBool()
{
@ -138,5 +142,3 @@ namespace PlanTempus.Tests.ConfigurationTests
public int RolloutPercentage { get; set; }
public List<string> AllowedUserGroups { get; set; }
}
}

View file

@ -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

View file

@ -1,18 +1,17 @@
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.X.TDD.ConfigurationTests;
namespace PlanTempus.Tests.ConfigurationTests
{
[TestClass]
public class SmartConfigProviderTests : TestFixture
{
const string _testFolder = "ConfigurationTests/";
private const string _testFolder = "ConfigurationTests/";
[TestMethod]
public void TrySmartConfigWithOptionsForPostgres()
@ -23,7 +22,6 @@ namespace PlanTempus.Tests.ConfigurationTests
.Build();
var actualFeature = config.Get<bool>("Database:UseSSL");
}
[TestMethod]
@ -43,6 +41,7 @@ namespace PlanTempus.Tests.ConfigurationTests
// Assert
actualFeature.ShouldBe(expectedFeature);
}
[TestMethod]
public void Get_ShouldReturnCorrectValueWhenSelectingIntoValueRowInConfigTable()
{
@ -61,7 +60,6 @@ namespace PlanTempus.Tests.ConfigurationTests
// Assert
actualFeature.ShouldBe(expectedFeature);
actualFeature.ShouldBe(withoutSectionThisAlsoWorks);
}
[TestMethod]
@ -79,8 +77,6 @@ namespace PlanTempus.Tests.ConfigurationTests
using (var conn = connFactory.Create())
{
var result = conn.QuerySql(sql);
}
}
}
}

View file

@ -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
}
}
}
},

View file

@ -1,3 +1,4 @@
using System.Net;
using Autofac;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel;
@ -5,14 +6,14 @@ 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
{
private CancellationTokenSource _cts;
private IMessageChannel<ITelemetry> _messageChannel;
private SeqBackgroundService _service;
private CancellationTokenSource _cts;
[TestInitialize]
public void SetupThis()
@ -34,7 +35,7 @@ namespace PlanTempus.Tests.Logging
{
await _service.StartAsync(_cts.Token);
for (int i = 0; i < 5; i++)
for (var i = 0; i < 5; i++)
{
var eventTelemetry = new EventTelemetry
{
@ -54,7 +55,7 @@ namespace PlanTempus.Tests.Logging
await _service.StopAsync(CancellationToken.None);
bool hasMoreMessages = await _messageChannel.Reader.WaitToReadAsync();
var hasMoreMessages = await _messageChannel.Reader.WaitToReadAsync();
Assert.IsFalse(hasMoreMessages, "Queue should be empty after 5 seconds");
}
@ -64,8 +65,7 @@ namespace PlanTempus.Tests.Logging
HttpRequestMessage request,
CancellationToken cancellationToken)
{
return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK));
}
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
}
}
}

View file

@ -3,14 +3,14 @@ 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
{
private SeqLogger<SeqLoggerTests> _logger;
private SeqHttpClient _httpClient;
private readonly string _testId;
private readonly SeqHttpClient _httpClient;
private readonly SeqLogger<SeqLoggerTests> _logger;
public SeqLoggerTests()
{
@ -34,9 +34,8 @@ namespace PlanTempus.Tests.Logging
// Act
await _logger.LogAsync(traceTelemetry);
}
[TestMethod]
public async Task LogTraceTelemetry_SendsCorrectDataWithWarningLevel()
{
@ -51,8 +50,8 @@ namespace PlanTempus.Tests.Logging
// Act
await _logger.LogAsync(traceTelemetry);
}
[TestMethod]
public async Task LogEventTelemetry_SendsCorrectData()
{
@ -74,13 +73,11 @@ namespace PlanTempus.Tests.Logging
{
try
{
int t = 0;
var t = 0;
var result = 10 / t;
}
catch (Exception e)
{
// Arrange
var exceptionTelemetry = new ExceptionTelemetry(e)
{
@ -121,9 +118,8 @@ namespace PlanTempus.Tests.Logging
{
var telemetryClient = Container.Resolve<TelemetryClient>();
using (Microsoft.ApplicationInsights.Extensibility.IOperationHolder<RequestTelemetry> parent = telemetryClient.StartOperation<RequestTelemetry>("Parent First"))
using (var parent = telemetryClient.StartOperation<RequestTelemetry>("Parent First"))
{
parent.Telemetry.Duration = TimeSpan.FromMilliseconds(250);
parent.Telemetry.Url = new Uri("http://parent.test.com/api/test");
@ -139,10 +135,11 @@ namespace PlanTempus.Tests.Logging
child.Telemetry.Properties.Add("TestId", _testId);
await _logger.LogAsync(child);
};
}
;
await _logger.LogAsync(parent);
}
}
}
}

View file

@ -5,15 +5,15 @@ 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
{
private IMessageChannel<ITelemetry> _messageChannel;
TelemetryClient _telemetryClient;
private SeqBackgroundService _service;
private CancellationTokenSource _cts;
private IMessageChannel<ITelemetry> _messageChannel;
private SeqBackgroundService _service;
private TelemetryClient _telemetryClient;
[TestInitialize]
public void SetupThis()
@ -34,7 +34,7 @@ namespace PlanTempus.Tests.Logging
{
await _service.StartAsync(_cts.Token);
for (int i = 0; i < 5; i++)
for (var i = 0; i < 5; i++)
{
var eventTelemetry = new EventTelemetry
{
@ -54,8 +54,7 @@ namespace PlanTempus.Tests.Logging
await _service.StopAsync(CancellationToken.None);
bool hasMoreMessages = await _messageChannel.Reader.WaitToReadAsync();
var hasMoreMessages = await _messageChannel.Reader.WaitToReadAsync();
Assert.IsFalse(hasMoreMessages, "Queue should be empty after 5 seconds");
}
}
}

View file

@ -1,42 +1,41 @@
using System.Diagnostics;
using Sodium;
using System.Text;
using PlanTempus.Core;
using Sodium;
namespace PlanTempus.X.TDD;
namespace PlanTempus.Tests
{
[TestClass]
public class PasswordHasherTests : TestFixture
{
[TestMethod]
public void MyTestMethod()
{
var stopwatch = Stopwatch.StartNew();
byte[] salt = PasswordHash.ScryptGenerateSalt();
var salt = PasswordHash.ScryptGenerateSalt();
// 2. Konverter password til byte[]
byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes("password123");
var passwordBytes = Encoding.UTF8.GetBytes("password123");
// 3. Kald ScryptHashBinary korrekt
byte[] hash = PasswordHash.ScryptHashBinary(
password: passwordBytes,
salt: salt, // 32-byte array
limit: PasswordHash.Strength.Interactive,
outputLength: 32
var hash = PasswordHash.ScryptHashBinary(
passwordBytes,
salt
);
stopwatch.Stop();
}
[TestMethod]
public void HashPassword_ShouldCreateValidHashFormat()
{
// Arrange
string password = "TestPassword123";
var password = "TestPassword123";
// Act
string hashedPassword = new SecureTokenizer().TokenizeText(password);
string[] parts = hashedPassword.Split('.');
var hashedPassword = new SecureTokenizer().TokenizeText(password);
var parts = hashedPassword.Split('.');
// Assert
Assert.AreEqual(3, parts.Length);
@ -47,11 +46,11 @@ namespace PlanTempus.Tests
public void VerifyPassword_WithCorrectPassword_ShouldReturnTrue()
{
// Arrange
string password = "TestPassword123";
string hashedPassword = new SecureTokenizer().TokenizeText(password);
var password = "TestPassword123";
var hashedPassword = new SecureTokenizer().TokenizeText(password);
// Act
bool result = new SecureTokenizer().VerifyToken(hashedPassword, password);
var result = new SecureTokenizer().VerifyToken(hashedPassword, password);
// Assert
Assert.IsTrue(result);
@ -61,12 +60,12 @@ namespace PlanTempus.Tests
public void VerifyPassword_WithWrongPassword_ShouldReturnFalse()
{
// Arrange
string correctPassword = "TestPassword123";
string wrongPassword = "WrongPassword123";
string hashedPassword = new SecureTokenizer().TokenizeText(correctPassword);
var correctPassword = "TestPassword123";
var wrongPassword = "WrongPassword123";
var hashedPassword = new SecureTokenizer().TokenizeText(correctPassword);
// Act
bool result = new SecureTokenizer().VerifyToken(hashedPassword, wrongPassword);
var result = new SecureTokenizer().VerifyToken(hashedPassword, wrongPassword);
// Assert
Assert.IsFalse(result);
@ -76,14 +75,13 @@ namespace PlanTempus.Tests
public void VerifyPassword_WithInvalidHashFormat_ShouldReturnFalse()
{
// Arrange
string password = "TestPassword123";
string invalidHash = "InvalidHash";
var password = "TestPassword123";
var invalidHash = "InvalidHash";
// Act
bool result = new SecureTokenizer().VerifyToken(invalidHash, password);
var result = new SecureTokenizer().VerifyToken(invalidHash, password);
// Assert
Assert.IsFalse(result);
}
}
}

View file

@ -1,17 +1,16 @@
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.X.TDD;
namespace PlanTempus.Tests
{
[TestClass]
public class PostgresTests : TestFixture
{
IDbConnectionFactory _connFactory;
IDatabaseOperations _databaseOperations;
private IDbConnectionFactory _connFactory;
private IDatabaseOperations _databaseOperations;
[TestInitialize]
public void MyTestMethod()
@ -19,14 +18,16 @@ namespace PlanTempus.Tests
_connFactory = Container.Resolve<IDbConnectionFactory>();
_databaseOperations = Container.Resolve<IDatabaseOperations>();
}
[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]
@ -46,6 +47,7 @@ namespace PlanTempus.Tests
throw;
}
}
[TestMethod]
public async Task TestScopeConnectionWithErrorLogging()
{
@ -53,7 +55,7 @@ namespace PlanTempus.Tests
try
{
var user = await db.Connection.QuerySqlAsync<string>(
"SELECT tablename FROM pg_tabless limit 5");
"SELECT tablename FROM pg_tables limit 5");
db.Success();
}
@ -62,6 +64,47 @@ namespace PlanTempus.Tests
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<dynamic>(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()
{
@ -72,13 +115,13 @@ namespace PlanTempus.Tests
return await connection.QuerySqlAsync<string>(
"SELECT tablename FROM pg_tables limit 5");
}, nameof(TestSimpleDatabaseOperation));
}
catch (Exception ex)
{
throw;
}
}
[TestMethod]
public void SetupPostgresql_LISTEN()
{
@ -92,4 +135,3 @@ namespace PlanTempus.Tests
// });
}
}
}

View file

@ -1,6 +1 @@
namespace PlanTempus.Tests
{
}
namespace PlanTempus.X.TDD;

View file

@ -1,21 +1,36 @@
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;
/// <summary>
/// Act as base class for tests. Avoids duplication of test setup code
/// </summary>
[TestClass]
public abstract partial class TestFixture
public abstract class TestFixture
{
private readonly string _configurationFilePath;
protected TestFixture() : this(null)
{
}
public TestFixture(string configurationFilePath)
{
if (configurationFilePath is not null)
_configurationFilePath = configurationFilePath?.TrimEnd('/') + "/";
CreateContainerBuilder();
Container = ContainerBuilder.Build();
}
protected IContainer Container { get; private set; }
protected ContainerBuilder ContainerBuilder { get; private set; }
@ -28,18 +43,9 @@ namespace PlanTempus.Tests
return configuration;
}
protected TestFixture() : this(null) { }
public TestFixture(string configurationFilePath)
{
if (configurationFilePath is not null)
_configurationFilePath = configurationFilePath?.TrimEnd('/') + "/";
CreateContainerBuilder();
Container = ContainerBuilder.Build();
}
protected virtual void CreateContainerBuilder()
{
IConfigurationRoot configuration = Configuration();
var configuration = Configuration();
//var logger = new LoggerConfiguration()
// .MinimumLevel.Verbose()
@ -59,7 +65,7 @@ namespace PlanTempus.Tests
.SingleInstance();
builder.RegisterModule(new Database.ModuleRegistry.DbPostgreSqlModule
builder.RegisterModule(new DbPostgreSqlModule
{
ConnectionString = configuration.GetConnectionString("DefaultConnection")
});
@ -70,8 +76,7 @@ namespace PlanTempus.Tests
});
builder.RegisterModule(new SeqLoggingModule
{
SeqConfiguration = configuration.GetSection("SeqConfiguration").ToObject<Core.Logging.SeqConfiguration>()
SeqConfiguration = configuration.GetSection("SeqConfiguration").ToObject<SeqConfiguration>()
});
@ -91,6 +96,4 @@ namespace PlanTempus.Tests
Container = null;
}
}
}
}