Added configurators
All checks were successful
HopFrame CI / build (push) Successful in 2m10s
HopFrame CI / test (push) Successful in 1m27s

This commit is contained in:
2026-02-22 19:32:33 +01:00
parent 79ed400185
commit b2a029d50b
40 changed files with 1837 additions and 1 deletions

View File

@@ -0,0 +1,165 @@
using System.Collections;
using HopFrame.Core.Configuration;
using HopFrame.Core.Configurators;
using HopFrame.Core.Repositories;
using Microsoft.Extensions.DependencyInjection;
namespace HopFrame.Tests.Core.Configurators;
public class HopFrameConfiguratorTests {
private class TestRepository : IHopFrameRepository {
public Task<IEnumerable> LoadPageGenericAsync(int page, int perPage, CancellationToken ct = default) {
throw new NotImplementedException();
}
public Task<int> CountAsync(CancellationToken ct = default) {
throw new NotImplementedException();
}
public Task<IEnumerable> SearchGenericAsync(string searchTerm, int page, int perPage, CancellationToken ct = default) {
throw new NotImplementedException();
}
public Task CreateGenericAsync(object entry, CancellationToken ct) {
throw new NotImplementedException();
}
public Task DeleteGenericAsync(object entry, CancellationToken ct) {
throw new NotImplementedException();
}
}
private HopFrameConfig CreateConfig()
=> new HopFrameConfig { Tables = new List<TableConfig>() };
private TableConfig CreateValidTable<TModel>()
=> new TableConfig {
Identifier = typeof(TModel).Name,
TableType = typeof(TModel),
RepositoryType = typeof(TestRepository),
Route = typeof(TModel).Name.ToLower(),
DisplayName = typeof(TModel).Name,
OrderIndex = 0,
Properties = new List<PropertyConfig> {
new PropertyConfig {
Identifier = "Id",
DisplayName = "Id",
Type = typeof(int),
OrderIndex = 0
}
}
};
// -------------------------------------------------------------
// AddRepository<TRepository, TModel>
// -------------------------------------------------------------
[Fact]
public void AddRepository_AddsTableToConfig() {
var config = CreateConfig();
var services = new ServiceCollection();
var configurator = new HopFrameConfigurator(config, services);
configurator.AddRepository<TestRepository, TestModel>();
Assert.Single(config.Tables);
Assert.Equal(typeof(TestModel), config.Tables[0].TableType);
}
[Fact]
public void AddRepository_RegistersRepositoryInServices() {
var config = CreateConfig();
var services = new ServiceCollection();
var configurator = new HopFrameConfigurator(config, services);
configurator.AddRepository<TestRepository, TestModel>();
Assert.Contains(services, d => d.ServiceType == typeof(TestRepository));
}
[Fact]
public void AddRepository_InvokesConfiguratorAction() {
var config = CreateConfig();
var services = new ServiceCollection();
var configurator = new HopFrameConfigurator(config, services);
bool invoked = false;
configurator.AddRepository<TestRepository, TestModel>(_ => { invoked = true; });
Assert.True(invoked);
}
// -------------------------------------------------------------
// AddTable<TModel>
// -------------------------------------------------------------
[Fact]
public void AddTable_AddsValidTableToConfig() {
var config = CreateConfig();
var services = new ServiceCollection();
var configurator = new HopFrameConfigurator(config, services);
var table = CreateValidTable<TestModel>();
configurator.AddTable<TestModel>(table);
Assert.Single(config.Tables);
Assert.Equal(table, config.Tables[0]);
}
[Fact]
public void AddTable_RegistersRepositoryType() {
var config = CreateConfig();
var services = new ServiceCollection();
var configurator = new HopFrameConfigurator(config, services);
var table = CreateValidTable<TestModel>();
configurator.AddTable<TestModel>(table);
Assert.Contains(services, d => d.ServiceType == typeof(TestRepository));
}
[Fact]
public void AddTable_Throws_WhenTableTypeDoesNotMatch() {
var config = CreateConfig();
var services = new ServiceCollection();
var configurator = new HopFrameConfigurator(config, services);
var table = CreateValidTable<TestModel>();
table.TableType = typeof(string); // falscher Typ
var ex = Assert.Throws<ArgumentException>(() =>
configurator.AddTable<TestModel>(table));
Assert.Contains("does not mach requested type", ex.Message);
}
[Fact]
public void AddTable_Throws_WhenValidationFails() {
var config = CreateConfig();
var services = new ServiceCollection();
var configurator = new HopFrameConfigurator(config, services);
var table = CreateValidTable<TestModel>();
table.DisplayName = null!; // invalid
var ex = Assert.Throws<ArgumentException>(() =>
configurator.AddTable<TestModel>(table));
Assert.Contains("validation errors", ex.Message);
Assert.Contains("DisplayName cannot be null", ex.Message);
}
[Fact]
public void AddTable_InvokesConfiguratorAction() {
var config = CreateConfig();
var services = new ServiceCollection();
var configurator = new HopFrameConfigurator(config, services);
var table = CreateValidTable<TestModel>();
bool invoked = false;
configurator.AddTable<TestModel>(table, _ => { invoked = true; });
Assert.True(invoked);
}
}

View File

@@ -0,0 +1,249 @@
using System.Reflection;
using HopFrame.Core.Configuration;
using HopFrame.Core.Helpers;
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
namespace HopFrame.Tests.Core.Helpers;
public class ConfigurationHelperTests {
private HopFrameConfig CreateGlobal(params TableConfig[] tables)
=> new HopFrameConfig { Tables = tables.ToList() };
private TableConfig CreateValidTable()
=> new TableConfig {
Identifier = "Test",
TableType = typeof(string),
RepositoryType = typeof(string),
Route = "/test",
DisplayName = "Test Table",
Properties = new List<PropertyConfig> {
new PropertyConfig {
Identifier = "Prop1",
DisplayName = "Property 1",
Type = typeof(int)
}
}
};
private TableConfig CreateDummyTable(string identifier)
=> new TableConfig {
Identifier = identifier,
TableType = typeof(object),
RepositoryType = typeof(object),
Route = identifier.ToLower(),
DisplayName = identifier,
OrderIndex = 0
};
[Fact]
public void InitializeTable_UsesModelNameAsIdentifier_WhenUnique() {
var global = CreateGlobal();
var config = ConfigurationHelper.InitializeTable(global, typeof(string), typeof(TestModel));
Assert.Equal("TestModel", config.Identifier);
}
[Fact]
public void InitializeTable_GeneratesGuid_WhenIdentifierAlreadyExists() {
var existing = CreateDummyTable("TestModel");
var global = CreateGlobal(existing);
var config = ConfigurationHelper.InitializeTable(global, typeof(string), typeof(TestModel));
Assert.NotEqual("TestModel", config.Identifier);
Assert.True(Guid.TryParse(config.Identifier, out _));
}
[Fact]
public void InitializeTable_SetsBasicFieldsCorrectly() {
var global = CreateGlobal();
var config = ConfigurationHelper.InitializeTable(global, typeof(string), typeof(TestModel));
Assert.Equal(typeof(string), config.RepositoryType);
Assert.Equal(typeof(TestModel), config.TableType);
Assert.Equal("testmodel", config.Route);
Assert.Equal("TestModel", config.DisplayName);
Assert.Equal(0, config.OrderIndex);
}
[Fact]
public void InitializeTable_SetsOrderIndex_ToCurrentTableCount() {
var global = CreateGlobal(
CreateDummyTable("A"),
CreateDummyTable("B")
);
var config = ConfigurationHelper.InitializeTable(global, typeof(string), typeof(TestModel));
Assert.Equal(2, config.OrderIndex);
}
[Fact]
public void InitializeTable_CreatesPropertyConfigs_ForAllModelProperties() {
var global = CreateGlobal();
var config = ConfigurationHelper.InitializeTable(global, typeof(string), typeof(TestModel));
Assert.Equal(2, config.Properties.Count);
Assert.Contains(config.Properties, p => p.Identifier == "Id");
Assert.Contains(config.Properties, p => p.Identifier == "Name");
}
[Fact]
public void InitializeProperty_UsesPropertyNameAsIdentifier_WhenUnique() {
var table = CreateDummyTable("T");
var property = typeof(TestModel).GetProperty(nameof(TestModel.Id))!;
var config = InvokeInitializeProperty(table, property);
Assert.Equal("Id", config.Identifier);
}
[Fact]
public void InitializeProperty_GeneratesGuid_WhenIdentifierAlreadyExists() {
var table = CreateDummyTable("T");
table.Properties.Add(new PropertyConfig
{ Identifier = "Id", Type = typeof(int), DisplayName = "Id", OrderIndex = 0 });
var property = typeof(TestModel).GetProperty(nameof(TestModel.Id))!;
var config = InvokeInitializeProperty(table, property);
Assert.NotEqual("Id", config.Identifier);
Assert.True(Guid.TryParse(config.Identifier, out _));
}
[Fact]
public void InitializeProperty_SetsBasicFieldsCorrectly() {
var table = CreateDummyTable("T");
var property = typeof(TestModel).GetProperty(nameof(TestModel.Name))!;
var config = InvokeInitializeProperty(table, property);
Assert.Equal("Name", config.DisplayName);
Assert.Equal(typeof(string), config.Type);
Assert.Equal(0, config.OrderIndex);
}
[Fact]
public void InitializeProperty_SetsOrderIndex_ToCurrentPropertyCount() {
var table = CreateDummyTable("T");
table.Properties.Add(new PropertyConfig
{ Identifier = "X", Type = typeof(int), DisplayName = "X", OrderIndex = 0 });
var property = typeof(TestModel).GetProperty(nameof(TestModel.Name))!;
var config = InvokeInitializeProperty(table, property);
Assert.Equal(1, config.OrderIndex);
}
private PropertyConfig InvokeInitializeProperty(TableConfig table, PropertyInfo property) {
var method = typeof(ConfigurationHelper)
.GetMethod("InitializeProperty", BindingFlags.NonPublic | BindingFlags.Static)!;
return (PropertyConfig)method.Invoke(null, [table, property])!;
}
[Fact]
public void ValidateTable_ReturnsError_WhenIdentifierNotUnique() {
var config = CreateValidTable();
var global = CreateGlobal(new TableConfig {
Identifier = "Test",
DisplayName = null,
TableType = null,
RepositoryType = null,
Route = null
});
var result = ConfigurationHelper.ValidateTable(global, config).ToList();
Assert.Contains("Table identifier 'Test' is not unique", result);
}
[Fact]
public void ValidateTable_ReturnsError_WhenTableTypeIsNull() {
var config = CreateValidTable();
config.TableType = null;
var result = ConfigurationHelper.ValidateTable(CreateGlobal(), config).ToList();
Assert.Contains("TableType cannot be null", result);
}
[Fact]
public void ValidateTable_ReturnsError_WhenRepositoryTypeIsNull() {
var config = CreateValidTable();
config.RepositoryType = null;
var result = ConfigurationHelper.ValidateTable(CreateGlobal(), config).ToList();
Assert.Contains("RepositoryType cannot be null", result);
}
[Fact]
public void ValidateTable_ReturnsError_WhenRouteIsNull() {
var config = CreateValidTable();
config.Route = null;
var result = ConfigurationHelper.ValidateTable(CreateGlobal(), config).ToList();
Assert.Contains("Route cannot be null", result);
}
[Fact]
public void ValidateTable_ReturnsError_WhenDisplayNameIsNull() {
var config = CreateValidTable();
config.DisplayName = null;
var result = ConfigurationHelper.ValidateTable(CreateGlobal(), config).ToList();
Assert.Contains("DisplayName cannot be null", result);
}
[Fact]
public void ValidateTable_ReturnsError_WhenPropertyIdentifierNotUnique() {
var config = CreateValidTable();
config.Properties.Add(new PropertyConfig {
Identifier = "Prop1",
DisplayName = "Duplicate",
Type = typeof(int)
});
var result = ConfigurationHelper.ValidateTable(CreateGlobal(), config).ToList();
Assert.Contains("Property identifier 'Prop1' is not unique", result);
}
[Fact]
public void ValidateTable_ReturnsError_WhenPropertyDisplayNameIsNull() {
var config = CreateValidTable();
config.Properties[0].DisplayName = null;
var result = ConfigurationHelper.ValidateTable(CreateGlobal(), config).ToList();
Assert.Contains("Property 'Prop1': DisplayName cannot be null", result);
}
[Fact]
public void ValidateTable_ReturnsError_WhenPropertyTypeIsNull() {
var config = CreateValidTable();
config.Properties[0].Type = null;
var result = ConfigurationHelper.ValidateTable(CreateGlobal(), config).ToList();
Assert.Contains("Property 'Prop1': Type cannot be null", result);
}
[Fact]
public void ValidateTable_ReturnsNoErrors_WhenConfigIsValid() {
var config = CreateValidTable();
var result = ConfigurationHelper.ValidateTable(CreateGlobal(), config).ToList();
Assert.Empty(result);
}
}

View File

@@ -0,0 +1,44 @@
using System.Linq.Expressions;
using HopFrame.Core.Helpers;
namespace HopFrame.Tests.Core.Helpers;
public class ExpressionHelperTests {
[Fact]
public void GetPropertyInfo_ReturnsPropertyInfo_WhenExpressionIsValid() {
Expression<Func<TestModel, int>> expr = x => x.Id;
var prop = ExpressionHelper.GetPropertyInfo(expr);
Assert.Equal(nameof(TestModel.Id), prop.Name);
Assert.Equal(typeof(int), prop.PropertyType);
}
[Fact]
public void GetPropertyInfo_Throws_WhenExpressionRefersToMethod() {
Expression<Func<TestModel, int>> expr = x => x.Method();
var ex = Assert.Throws<ArgumentException>(() => ExpressionHelper.GetPropertyInfo(expr));
Assert.Contains("refers to a method", ex.Message);
}
[Fact]
public void GetPropertyInfo_Throws_WhenExpressionRefersToField() {
Expression<Func<TestModel, int>> expr = x => x.FieldBacking;
var ex = Assert.Throws<ArgumentException>(() => ExpressionHelper.GetPropertyInfo(expr));
Assert.Contains("refers to a field", ex.Message);
}
[Fact]
public void GetPropertyInfo_Throws_WhenExpressionBodyIsNotMemberExpression() {
Expression<Func<TestModel, int>> expr = x => 5;
var ex = Assert.Throws<ArgumentException>(() => ExpressionHelper.GetPropertyInfo(expr));
Assert.Contains("refers to a method, not a property", ex.Message);
}
}

View File

@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1"/>
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="xunit" Version="2.9.3"/>
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4"/>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\HopFrame.Core\HopFrame.Core.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,98 @@
using HopFrame.Core.Repositories;
using Moq;
namespace HopFrame.Tests.Core.Repositories;
public class HopFrameRepositoryTests {
private Mock<HopFrameRepository<TestModel>> CreateMock()
=> new(MockBehavior.Strict);
// -------------------------------------------------------------
// LoadPageGenericAsync
// -------------------------------------------------------------
[Fact]
public async Task LoadPageGenericAsync_DelegatesToTypedMethod() {
var mock = CreateMock();
var expected = new List<TestModel> { new TestModel { Id = 1 } };
mock.Setup(r => r.LoadPageAsync(2, 10, It.IsAny<CancellationToken>()))
.ReturnsAsync(expected);
var result = await mock.Object.LoadPageGenericAsync(2, 10);
Assert.Equal(expected, result);
}
// -------------------------------------------------------------
// SearchGenericAsync
// -------------------------------------------------------------
[Fact]
public async Task SearchGenericAsync_DelegatesToTypedMethod() {
var mock = CreateMock();
var expected = new List<TestModel> { new TestModel { Id = 5 } };
mock.Setup(r => r.SearchAsync("abc", 1, 20, It.IsAny<CancellationToken>()))
.ReturnsAsync(expected);
var result = await mock.Object.SearchGenericAsync("abc", 1, 20);
Assert.Equal(expected, result);
}
// -------------------------------------------------------------
// CreateGenericAsync
// -------------------------------------------------------------
[Fact]
public async Task CreateGenericAsync_CastsAndDelegates() {
var mock = CreateMock();
var model = new TestModel { Id = 99 };
mock.Setup(r => r.CreateAsync(model, It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
await mock.Object.CreateGenericAsync(model, CancellationToken.None);
mock.Verify(r => r.CreateAsync(model, It.IsAny<CancellationToken>()), Times.Once);
}
// -------------------------------------------------------------
// DeleteGenericAsync
// -------------------------------------------------------------
[Fact]
public async Task DeleteGenericAsync_CastsAndDelegates() {
var mock = CreateMock();
var model = new TestModel { Id = 42 };
mock.Setup(r => r.DeleteAsync(model, It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
await mock.Object.DeleteGenericAsync(model, CancellationToken.None);
mock.Verify(r => r.DeleteAsync(model, It.IsAny<CancellationToken>()), Times.Once);
}
// -------------------------------------------------------------
// CountAsync (direct abstract method)
// -------------------------------------------------------------
[Fact]
public async Task CountAsync_CanBeMockedAndReturnsValue() {
var mock = CreateMock();
mock.Setup(r => r.CountAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(123);
var result = await mock.Object.CountAsync();
Assert.Equal(123, result);
}
}

View File

@@ -0,0 +1,160 @@
using System.Collections;
using HopFrame.Core.Configuration;
using HopFrame.Core.Repositories;
using HopFrame.Core.Services.Implementation;
using Microsoft.Extensions.DependencyInjection;
using Moq;
namespace HopFrame.Tests.Core.Services.Implementation;
public class ConfigAccessorTests {
private class TestRepository : IHopFrameRepository {
public Task<IEnumerable> LoadPageGenericAsync(int page, int perPage, CancellationToken ct = default) {
throw new NotImplementedException();
}
public Task<int> CountAsync(CancellationToken ct = default) {
throw new NotImplementedException();
}
public Task<IEnumerable> SearchGenericAsync(string searchTerm, int page, int perPage, CancellationToken ct = default) {
throw new NotImplementedException();
}
public Task CreateGenericAsync(object entry, CancellationToken ct) {
throw new NotImplementedException();
}
public Task DeleteGenericAsync(object entry, CancellationToken ct) {
throw new NotImplementedException();
}
}
private TableConfig CreateTable(string id, string route, Type type)
=> new TableConfig {
Identifier = id,
Route = route,
TableType = type,
RepositoryType = typeof(TestRepository),
DisplayName = id,
OrderIndex = 0,
Properties = new List<PropertyConfig> {
new PropertyConfig {
Identifier = "Id",
DisplayName = "Id",
Type = typeof(int),
OrderIndex = 0
}
}
};
private HopFrameConfig CreateConfig(params TableConfig[] tables)
=> new HopFrameConfig { Tables = new List<TableConfig>(tables) };
// -------------------------------------------------------------
// GetTableByIdentifier
// -------------------------------------------------------------
[Fact]
public void GetTableByIdentifier_ReturnsCorrectTable() {
var table = CreateTable("A", "a", typeof(TestModel));
var config = CreateConfig(table);
var accessor = new ConfigAccessor(config, Mock.Of<IServiceProvider>());
var result = accessor.GetTableByIdentifier("A");
Assert.Equal(table, result);
}
[Fact]
public void GetTableByIdentifier_ReturnsNull_WhenNotFound() {
var config = CreateConfig();
var accessor = new ConfigAccessor(config, Mock.Of<IServiceProvider>());
var result = accessor.GetTableByIdentifier("missing");
Assert.Null(result);
}
// -------------------------------------------------------------
// GetTableByRoute
// -------------------------------------------------------------
[Fact]
public void GetTableByRoute_ReturnsCorrectTable() {
var table = CreateTable("A", "routeA", typeof(TestModel));
var config = CreateConfig(table);
var accessor = new ConfigAccessor(config, Mock.Of<IServiceProvider>());
var result = accessor.GetTableByRoute("routeA");
Assert.Equal(table, result);
}
[Fact]
public void GetTableByRoute_ReturnsNull_WhenNotFound() {
var config = CreateConfig();
var accessor = new ConfigAccessor(config, Mock.Of<IServiceProvider>());
var result = accessor.GetTableByRoute("missing");
Assert.Null(result);
}
// -------------------------------------------------------------
// GetTableByType
// -------------------------------------------------------------
[Fact]
public void GetTableByType_ReturnsCorrectTable() {
var table = CreateTable("A", "a", typeof(TestModel));
var config = CreateConfig(table);
var accessor = new ConfigAccessor(config, Mock.Of<IServiceProvider>());
var result = accessor.GetTableByType(typeof(TestModel));
Assert.Equal(table, result);
}
[Fact]
public void GetTableByType_ReturnsNull_WhenNotFound() {
var config = CreateConfig();
var accessor = new ConfigAccessor(config, Mock.Of<IServiceProvider>());
var result = accessor.GetTableByType(typeof(TestModel));
Assert.Null(result);
}
// -------------------------------------------------------------
// LoadRepository
// -------------------------------------------------------------
[Fact]
public void LoadRepository_ResolvesRepositoryFromServiceProvider() {
var table = CreateTable("A", "a", typeof(TestModel));
var repo = new TestRepository();
var providerMock = new Mock<IServiceProvider>();
providerMock
.Setup(p => p.GetService(typeof(TestRepository)))
.Returns(repo);
var accessor = new ConfigAccessor(CreateConfig(table), providerMock.Object);
var result = accessor.LoadRepository(table);
Assert.Equal(repo, result);
}
[Fact]
public void LoadRepository_Throws_WhenServiceNotRegistered() {
var table = CreateTable("A", "a", typeof(TestModel));
var provider = new ServiceCollection().BuildServiceProvider();
var accessor = new ConfigAccessor(CreateConfig(table), provider);
Assert.Throws<InvalidOperationException>(() => accessor.LoadRepository(table));
}
}

View File

@@ -0,0 +1,10 @@
namespace HopFrame.Tests.Core;
public class TestModel {
public int Id { get; set; }
public string Name { get; set; }
public int Method() => 42;
public int FieldBacking;
}