Added web module tests

This commit is contained in:
2025-01-19 16:00:33 +01:00
parent 8d63910aae
commit 80aa650a2c
26 changed files with 587 additions and 71 deletions

View File

@@ -0,0 +1,34 @@
using HopFrame.Core.Config;
using HopFrame.Tests.Core.Models;
using Moq;
namespace HopFrame.Tests.Core.Config;
public class DbContextConfiguratorTests {
[Fact]
public void Table_WithConfigurator_InvokesConfigurator() {
// Arrange
var dbContextConfig = new DbContextConfig(typeof(MockDbContext));
var configurator = new DbContextConfigurator<MockDbContext>(dbContextConfig);
var mockConfigurator = new Mock<Action<TableConfigurator<MockModel>>>();
// Act
configurator.Table<MockModel>(mockConfigurator.Object);
// Assert
mockConfigurator.Verify(c => c.Invoke(It.IsAny<TableConfigurator<MockModel>>()), Times.Once);
}
[Fact]
public void Table_ReturnsCorrectTableConfigurator() {
// Arrange
var dbContextConfig = new DbContextConfig(typeof(MockDbContext));
var configurator = new DbContextConfigurator<MockDbContext>(dbContextConfig);
// Act
var tableConfigurator = configurator.Table<MockModel>();
// Assert
Assert.IsType<TableConfigurator<MockModel>>(tableConfigurator);
}
}

View File

@@ -0,0 +1,80 @@
using HopFrame.Core.Config;
using HopFrame.Tests.Core.Models;
namespace HopFrame.Tests.Core.Config;
public class HopFrameConfiguratorTests {
[Fact]
public void AddDbContext_AddsDbContextToInnerConfig() {
// Arrange
var config = new HopFrameConfig();
var configurator = new HopFrameConfigurator(config);
// Act
var dbContextConfigurator = configurator.AddDbContext<MockDbContext>();
// Assert
Assert.Single(config.Contexts);
Assert.IsType<DbContextConfig>(config.Contexts[0]);
Assert.IsType<DbContextConfigurator<MockDbContext>>(dbContextConfigurator);
}
[Fact]
public void AddDbContext_WithConfigurator_AddsDbContextToInnerConfig() {
// Arrange
var config = new HopFrameConfig();
var configurator = new HopFrameConfigurator(config);
// Act
object dbContextConfigurator = null!;
configurator.AddDbContext<MockDbContext>(context => {
dbContextConfigurator = context;
});
// Assert
Assert.Single(config.Contexts);
Assert.IsType<DbContextConfig>(config.Contexts[0]);
Assert.IsType<DbContextConfigurator<MockDbContext>>(dbContextConfigurator);
}
[Fact]
public void DisplayUserInfo_SetsDisplayUserInfoProperty() {
// Arrange
var config = new HopFrameConfig();
var configurator = new HopFrameConfigurator(config);
// Act
configurator.DisplayUserInfo(false);
// Assert
Assert.False(config.DisplayUserInfo);
}
[Fact]
public void SetBasePolicy_SetsBasePolicyProperty() {
// Arrange
var config = new HopFrameConfig();
var configurator = new HopFrameConfigurator(config);
var basePolicy = "Admin";
// Act
configurator.SetBasePolicy(basePolicy);
// Assert
Assert.Equal(basePolicy, config.BasePolicy);
}
[Fact]
public void SetLoginPage_SetsLoginPageRewriteProperty() {
// Arrange
var config = new HopFrameConfig();
var configurator = new HopFrameConfigurator(config);
var loginPageUrl = "/login";
// Act
configurator.SetLoginPage(loginPageUrl);
// Assert
Assert.Equal(loginPageUrl, config.LoginPageRewrite);
}
}

View File

@@ -0,0 +1,225 @@
using System.Linq.Expressions;
using HopFrame.Core.Config;
using HopFrame.Tests.Core.Models;
namespace HopFrame.Tests.Core.Config;
public class PropertyConfiguratorTests {
[Fact]
public void SetDisplayName_SetsNameProperty() {
// Arrange
var propertyConfig = new PropertyConfig(typeof(MockModel).GetProperty("Id")!,
new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0), 0);
var configurator = new PropertyConfigurator<int>(propertyConfig);
var displayName = "ID";
// Act
configurator.SetDisplayName(displayName);
// Assert
Assert.Equal(displayName, propertyConfig.Name);
}
[Fact]
public void List_SetsListAndSearchableProperties() {
// Arrange
var propertyConfig = new PropertyConfig(typeof(MockModel).GetProperty("Id")!,
new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0), 0);
var configurator = new PropertyConfigurator<int>(propertyConfig);
// Act
configurator.List(true);
// Assert
Assert.True(propertyConfig.List);
Assert.False(propertyConfig.Searchable);
}
[Fact]
public void IsSortable_SetsSortableProperty() {
// Arrange
var propertyConfig = new PropertyConfig(typeof(MockModel).GetProperty("Id")!,
new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0), 0);
var configurator = new PropertyConfigurator<int>(propertyConfig);
// Act
configurator.IsSortable(true);
// Assert
Assert.True(propertyConfig.Sortable);
}
[Fact]
public void IsSearchable_SetsSearchableProperty() {
// Arrange
var propertyConfig = new PropertyConfig(typeof(MockModel).GetProperty("Id")!,
new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0), 0);
var configurator = new PropertyConfigurator<int>(propertyConfig);
// Act
configurator.IsSearchable(true);
// Assert
Assert.True(propertyConfig.Searchable);
}
[Fact]
public void SetDisplayedProperty_SetsDisplayedProperty() {
// Arrange
var propertyConfig = new PropertyConfig(typeof(MockModel).GetProperty("Id")!,
new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0), 0);
var configurator = new PropertyConfigurator<MockModel>(propertyConfig);
Expression<Func<MockModel, int>> propertyExpression = model => model.Id;
// Act
configurator.SetDisplayedProperty(propertyExpression);
// Assert
Assert.NotNull(propertyConfig.DisplayedProperty);
Assert.Equal("Id", propertyConfig.DisplayedProperty?.Name);
}
[Fact]
public void Format_SetsFormatter() {
// Arrange
var propertyConfig = new PropertyConfig(typeof(MockModel).GetProperty("Id")!,
new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0), 0);
var configurator = new PropertyConfigurator<int>(propertyConfig);
Func<int, IServiceProvider, string> formatter = (val, _) => val.ToString();
// Act
configurator.Format(formatter);
// Assert
Assert.NotNull(propertyConfig.Formatter);
}
[Fact]
public void SetParser_SetsParser() {
// Arrange
var propertyConfig = new PropertyConfig(typeof(MockModel).GetProperty("Id")!,
new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0), 0);
var configurator = new PropertyConfigurator<int>(propertyConfig);
Func<string, IServiceProvider, int> parser = (str, _) => int.Parse(str);
// Act
configurator.SetParser(parser);
// Assert
Assert.NotNull(propertyConfig.Parser);
}
[Fact]
public void SetEditable_SetsEditableProperty() {
// Arrange
var propertyConfig = new PropertyConfig(typeof(MockModel).GetProperty("Id")!,
new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0), 0);
var configurator = new PropertyConfigurator<int>(propertyConfig);
// Act
configurator.SetEditable(true);
// Assert
Assert.True(propertyConfig.Editable);
}
[Fact]
public void SetCreatable_SetsCreatableProperty() {
// Arrange
var propertyConfig = new PropertyConfig(typeof(MockModel).GetProperty("Id")!,
new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0), 0);
var configurator = new PropertyConfigurator<int>(propertyConfig);
// Act
configurator.SetCreatable(true);
// Assert
Assert.True(propertyConfig.Creatable);
}
[Fact]
public void DisplayValue_SetsDisplayValueProperty() {
// Arrange
var propertyConfig = new PropertyConfig(typeof(MockModel).GetProperty("Id")!,
new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0), 0);
var configurator = new PropertyConfigurator<int>(propertyConfig);
// Act
configurator.DisplayValue(true);
// Assert
Assert.True(propertyConfig.DisplayValue);
}
[Fact]
public void IsTextArea_SetsTextAreaProperty() {
// Arrange
var propertyConfig = new PropertyConfig(typeof(MockModel).GetProperty("Id")!,
new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0), 0);
var configurator = new PropertyConfigurator<int>(propertyConfig);
// Act
configurator.IsTextArea(true);
// Assert
Assert.True(propertyConfig.TextArea);
}
[Fact]
public void SetTextAreaRows_SetsTextAreaRowsProperty() {
// Arrange
var propertyConfig = new PropertyConfig(typeof(MockModel).GetProperty("Id")!,
new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0), 0);
var configurator = new PropertyConfigurator<int>(propertyConfig);
var rows = 10;
// Act
configurator.SetTextAreaRows(rows);
// Assert
Assert.Equal(rows, propertyConfig.TextAreaRows);
}
[Fact]
public void SetValidator_SetsValidator() {
// Arrange
var propertyConfig = new PropertyConfig(typeof(MockModel).GetProperty("Id")!,
new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0), 0);
var configurator = new PropertyConfigurator<int>(propertyConfig);
Func<int, IServiceProvider, IEnumerable<string>> validator = (_, _) => new List<string>();
// Act
configurator.SetValidator(validator);
// Assert
Assert.NotNull(propertyConfig.Validator);
}
[Fact]
public void SetOrderIndex_SetsOrderProperty() {
// Arrange
var propertyConfig = new PropertyConfig(typeof(MockModel).GetProperty("Id")!,
new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0), 0);
var configurator = new PropertyConfigurator<int>(propertyConfig);
var orderIndex = 1;
// Act
configurator.SetOrderIndex(orderIndex);
// Assert
Assert.Equal(orderIndex, propertyConfig.Order);
}
[Fact]
public void Constructor_SetsTableProperty() {
// Arrange
var tableConfig = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0);
// Act
var propertyConfig = new PropertyConfig(typeof(MockModel).GetProperty("Id")!, tableConfig, 0);
// Assert
Assert.NotNull(propertyConfig.Table);
Assert.Equal(tableConfig, propertyConfig.Table);
}
}

View File

@@ -0,0 +1,211 @@
using System.Linq.Expressions;
using HopFrame.Core.Config;
using HopFrame.Tests.Core.Models;
namespace HopFrame.Tests.Core.Config;
public class TableConfiguratorTests {
[Fact]
public void Ignore_SetsIgnoredProperty() {
// Arrange
var tableConfig =
new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0);
var configurator = new TableConfigurator<MockModel>(tableConfig);
// Act
configurator.Ignore(true);
// Assert
Assert.True(tableConfig.Ignored);
}
[Fact]
public void Property_ReturnsCorrectPropertyConfigurator() {
// Arrange
var tableConfig = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0);
var configurator = new TableConfigurator<MockModel>(tableConfig);
Expression<Func<MockModel, int>> propertyExpression = model => model.Id;
// Act
var propertyConfigurator = configurator.Property(propertyExpression);
// Assert
Assert.IsType<PropertyConfigurator<int>>(propertyConfigurator);
}
public void Property_WithConfigurator_ReturnsCorrectPropertyConfigurator() {
// Arrange
var tableConfig = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0);
var configurator = new TableConfigurator<MockModel>(tableConfig);
Expression<Func<MockModel, int>> propertyExpression = model => model.Id;
// Act
object propertyConfigurator = null!;
configurator.Property(propertyExpression, c => {
propertyConfigurator = c;
});
// Assert
Assert.IsType<PropertyConfigurator<int>>(propertyConfigurator);
}
[Fact]
public void AddVirtualProperty_AddsVirtualPropertyToConfig() {
// Arrange
var tableConfig = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0);
var configurator = new TableConfigurator<MockModel>(tableConfig);
Func<MockModel, IServiceProvider, string> template = (model, _) => model.Name!;
// Act
var propertyConfigurator = configurator.AddVirtualProperty("VirtualName", template);
// Assert
var virtualProperty = tableConfig.Properties.SingleOrDefault(p => p.Name == "VirtualName");
Assert.NotNull(virtualProperty);
Assert.NotNull(propertyConfigurator);
Assert.True(virtualProperty.IsListingProperty);
Assert.Equal("VirtualName", virtualProperty.Name);
}
[Fact]
public void AddVirtualProperty_WithConfigurator_AddsVirtualPropertyToConfig() {
// Arrange
var tableConfig = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0);
var configurator = new TableConfigurator<MockModel>(tableConfig);
Func<MockModel, IServiceProvider, string> template = (model, _) => model.Name!;
// Act
object propertyConfigurator = null!;
configurator.AddVirtualProperty("VirtualName", template, c => {
propertyConfigurator = c;
});
// Assert
var virtualProperty = tableConfig.Properties.SingleOrDefault(p => p.Name == "VirtualName");
Assert.NotNull(virtualProperty);
Assert.NotNull(propertyConfigurator);
Assert.True(virtualProperty.IsListingProperty);
Assert.Equal("VirtualName", virtualProperty.Name);
}
[Fact]
public void SetDisplayName_SetsDisplayNameProperty() {
// Arrange
var tableConfig = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0);
var configurator = new TableConfigurator<MockModel>(tableConfig);
var displayName = "Mock Model Display Name";
// Act
configurator.SetDisplayName(displayName);
// Assert
Assert.Equal(displayName, tableConfig.DisplayName);
}
[Fact]
public void SetDescription_SetsDescriptionProperty() {
// Arrange
var tableConfig = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0);
var configurator = new TableConfigurator<MockModel>(tableConfig);
var description = "Mock Model Description";
// Act
configurator.SetDescription(description);
// Assert
Assert.Equal(description, tableConfig.Description);
}
[Fact]
public void SetOrderIndex_SetsOrderIndexProperty() {
// Arrange
var tableConfig = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0);
var configurator = new TableConfigurator<MockModel>(tableConfig);
var orderIndex = 1;
// Act
configurator.SetOrderIndex(orderIndex);
// Assert
Assert.Equal(orderIndex, tableConfig.Order);
}
[Fact]
public void SetViewPolicy_SetsViewPolicyProperty() {
// Arrange
var tableConfig = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0);
var configurator = new TableConfigurator<MockModel>(tableConfig);
var policy = "ViewPolicy";
// Act
configurator.SetViewPolicy(policy);
// Assert
Assert.Equal(policy, tableConfig.ViewPolicy);
}
[Fact]
public void SetUpdatePolicy_SetsUpdatePolicyProperty() {
// Arrange
var tableConfig = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0);
var configurator = new TableConfigurator<MockModel>(tableConfig);
var policy = "UpdatePolicy";
// Act
configurator.SetUpdatePolicy(policy);
// Assert
Assert.Equal(policy, tableConfig.UpdatePolicy);
}
[Fact]
public void SetCreatePolicy_SetsCreatePolicyProperty() {
// Arrange
var tableConfig = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0);
var configurator = new TableConfigurator<MockModel>(tableConfig);
var policy = "CreatePolicy";
// Act
configurator.SetCreatePolicy(policy);
// Assert
Assert.Equal(policy, tableConfig.CreatePolicy);
}
[Fact]
public void SetDeletePolicy_SetsDeletePolicyProperty() {
// Arrange
var tableConfig = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "MockModels", 0);
var configurator = new TableConfigurator<MockModel>(tableConfig);
var policy = "DeletePolicy";
// Act
configurator.SetDeletePolicy(policy);
// Assert
Assert.Equal(policy, tableConfig.DeletePolicy);
}
[Fact]
public void Constructor_WithKeyProperty_DisablesEdit() {
// Act
var tableConfig = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel2), "Models2", 0);
var prop = tableConfig.Properties.SingleOrDefault(prop => prop.Info.Name == nameof(MockModel2.Id));
// Assert
Assert.NotNull(prop);
Assert.False(prop.Editable);
}
[Fact]
public void Constructor_WithGeneratedProperty_DisablesEditAndCreate() {
// Act
var tableConfig = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel2), "Models2", 0);
var prop = tableConfig.Properties.SingleOrDefault(prop => prop.Info.Name == nameof(MockModel2.Number));
// Assert
Assert.NotNull(prop);
Assert.False(prop.Editable);
Assert.False(prop.Creatable);
}
}

View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.2"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="9.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1"/>
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="xunit" Version="2.9.2"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2"/>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\HopFrame.Core\HopFrame.Core.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,13 @@
using Microsoft.EntityFrameworkCore;
namespace HopFrame.Tests.Core.Models;
// A mock DbContext for testing purposes
public class MockDbContext : DbContext {
public DbSet<MockModel> Models { get; set; }
public DbSet<MockModel2> Models2 { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
optionsBuilder.UseInMemoryDatabase(nameof(MockDbContext));
}
}

View File

@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace HopFrame.Tests.Core.Models;
// A mock model for testing purposes
public class MockModel {
public int Id { get; set; }
public string? Name { get; set; }
[ForeignKey("other")]
public List<MockModel2> Model2 { get; set; }
}

View File

@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace HopFrame.Tests.Core.Models;
public class MockModel2 {
[Key]
public required string Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Number { get; set; }
}

View File

@@ -0,0 +1,129 @@
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Query;
namespace HopFrame.Tests.Core.Models;
// A mock implementation for async query provider
internal class TestAsyncQueryProvider<TEntity> : IAsyncQueryProvider {
private readonly IQueryProvider _inner;
internal TestAsyncQueryProvider(IQueryProvider inner) {
_inner = inner;
}
public IQueryable CreateQuery(Expression expression) {
return new TestAsyncEnumerable<TEntity>(expression);
}
public IQueryable<TElement> CreateQuery<TElement>(Expression expression) {
return new TestAsyncEnumerable<TElement>(expression);
}
public object Execute(Expression expression) {
return _inner.Execute(expression);
}
public TResult Execute<TResult>(Expression expression) {
return _inner.Execute<TResult>(expression);
}
public TResult ExecuteAsync<TResult>(Expression expression,
CancellationToken cancellationToken = new CancellationToken()) {
return _inner.Execute<TResult>(expression);
}
public IAsyncEnumerable<TResult> ExecuteAsync<TResult>(Expression expression) {
return new TestAsyncEnumerable<TResult>(expression);
}
}
internal class TestAsyncEnumerable<T> : EnumerableQuery<T>, IAsyncEnumerable<T>, IQueryable<T> {
public TestAsyncEnumerable(IEnumerable<T> enumerable) : base(enumerable) { }
public TestAsyncEnumerable(Expression expression) : base(expression) { }
public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default) {
return new TestAsyncEnumerator<T>(this.AsEnumerable().GetEnumerator());
}
IQueryProvider IQueryable.Provider => new TestAsyncQueryProvider<T>(this);
}
internal class TestAsyncEnumerator<T> : IAsyncEnumerator<T> {
private readonly IEnumerator<T> _inner;
public TestAsyncEnumerator(IEnumerator<T> inner) {
_inner = inner ?? throw new ArgumentNullException(nameof(inner));
}
public T Current => _inner.Current;
public ValueTask DisposeAsync() {
_inner.Dispose();
return new ValueTask();
}
public ValueTask<bool> MoveNextAsync() {
return new ValueTask<bool>(_inner.MoveNext());
}
}
/*// A mock implementation for async query provider
internal class TestAsyncQueryProvider<TEntity> : IAsyncQueryProvider {
private readonly IQueryProvider _inner;
internal TestAsyncQueryProvider(IQueryProvider inner) {
_inner = inner;
}
public IQueryable CreateQuery(Expression expression) {
return new TestAsyncEnumerable<TEntity>(expression);
}
public IQueryable<TElement> CreateQuery<TElement>(Expression expression) {
return new TestAsyncEnumerable<TElement>(expression);
}
public object? Execute(Expression expression) {
return _inner.Execute(expression);
}
public TResult Execute<TResult>(Expression expression) {
return _inner.Execute<TResult>(expression);
}
public TResult ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken) {
return _inner.Execute<TResult>(expression);
}
public IAsyncEnumerable<TResult> ExecuteAsync<TResult>(Expression expression) {
return new TestAsyncEnumerable<TResult>(expression);
}
}
internal class TestAsyncEnumerable<T> : EnumerableQuery<T>, IAsyncEnumerable<T>, IQueryable<T> {
public TestAsyncEnumerable(IEnumerable<T> enumerable) : base(enumerable) { }
public TestAsyncEnumerable(Expression expression) : base(expression) { }
public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default) {
return new TestAsyncEnumerator<T>(this.AsEnumerable().GetEnumerator());
}
IQueryProvider IQueryable.Provider => new TestAsyncQueryProvider<T>(this);
}
internal class TestAsyncEnumerator<T>(IEnumerator<T> inner) : IAsyncEnumerator<T> {
private readonly IEnumerator<T> _inner = inner ?? throw new ArgumentNullException(nameof(inner));
public T Current => _inner.Current;
public ValueTask DisposeAsync() {
_inner.Dispose();
return new ValueTask();
}
public ValueTask<bool> MoveNextAsync() {
return new ValueTask<bool>(_inner.MoveNext());
}
}*/

View File

@@ -0,0 +1,221 @@
using HopFrame.Core.Config;
using HopFrame.Core.Services.Implementations;
using HopFrame.Tests.Core.Models;
using Microsoft.Extensions.Logging;
using Moq;
namespace HopFrame.Tests.Core.Services;
public class ContextExplorerTests {
[Fact]
public void GetTables_ReturnsNonIgnoredTables() {
// Arrange
var config = new HopFrameConfig();
var contextConfig = new DbContextConfig(typeof(MockDbContext));
var tableConfig1 = contextConfig.Tables[0];
var tableConfig2 = contextConfig.Tables[1];
config.Contexts.Add(contextConfig);
tableConfig2.Ignored = true;
var provider = new Mock<IServiceProvider>();
var contextExplorer = new ContextExplorer(config, provider.Object, new Logger<ContextExplorer>(new LoggerFactory()));
// Act
var tables = contextExplorer.GetTables().ToList();
// Assert
Assert.Single(tables);
Assert.Contains(tableConfig1, tables);
Assert.DoesNotContain(tableConfig2, tables);
}
[Fact]
public void GetTable_ByDisplayName_ReturnsCorrectTable() {
// Arrange
var config = new HopFrameConfig();
var contextConfig = new DbContextConfig(typeof(MockDbContext));
var tableConfig = contextConfig.Tables[0];
config.Contexts.Add(contextConfig);
tableConfig.DisplayName = "TestTable";
var provider = new Mock<IServiceProvider>();
provider.Setup(p => p.GetService(typeof(MockDbContext))).Returns(new MockDbContext());
var contextExplorer = new ContextExplorer(config, provider.Object, new Logger<ContextExplorer>(new LoggerFactory()));
// Act
var result = contextExplorer.GetTable("TestTable");
// Assert
Assert.NotNull(result);
Assert.Equal(tableConfig, result);
}
[Fact]
public void GetTable_ByDisplayName_ReturnsNullIfTableNotFound() {
// Arrange
var config = new HopFrameConfig();
var contextConfig = new DbContextConfig(typeof(MockDbContext));
var tableConfig = contextConfig.Tables[0];
config.Contexts.Add(contextConfig);
tableConfig.DisplayName = "TestTable";
var provider = new Mock<IServiceProvider>();
provider.Setup(p => p.GetService(typeof(MockDbContext))).Returns(new MockDbContext());
var contextExplorer = new ContextExplorer(config, provider.Object, new Logger<ContextExplorer>(new LoggerFactory()));
// Act
var result = contextExplorer.GetTable("InvalidTable");
// Assert
Assert.Null(result);
}
[Fact]
public void GetTable_ByType_ReturnsCorrectTable() {
// Arrange
var config = new HopFrameConfig();
var contextConfig = new DbContextConfig(typeof(MockDbContext));
var tableConfig = contextConfig.Tables[0];
config.Contexts.Add(contextConfig);
var provider = new Mock<IServiceProvider>();
provider.Setup(p => p.GetService(typeof(MockDbContext))).Returns(new MockDbContext());
var contextExplorer = new ContextExplorer(config, provider.Object, new Logger<ContextExplorer>(new LoggerFactory()));
// Act
var result = contextExplorer.GetTable(typeof(MockModel));
// Assert
Assert.NotNull(result);
Assert.Equal(tableConfig, result);
}
[Fact]
public void GetTable_ByType_ReturnsNullIfTableNotFound() {
// Arrange
var config = new HopFrameConfig();
var contextConfig = new DbContextConfig(typeof(MockDbContext));
var tableConfig = contextConfig.Tables[0];
config.Contexts.Add(contextConfig);
var provider = new Mock<IServiceProvider>();
provider.Setup(p => p.GetService(typeof(MockDbContext))).Returns(new MockDbContext());
var contextExplorer = new ContextExplorer(config, provider.Object, new Logger<ContextExplorer>(new LoggerFactory()));
// Act
var result = contextExplorer.GetTable(typeof(ContextExplorerTests));
// Assert
Assert.Null(result);
}
[Fact]
public void GetTableManager_ReturnsCorrectTableManager() {
// Arrange
var config = new HopFrameConfig();
var contextConfig = new DbContextConfig(typeof(MockDbContext));
var tableConfig = new TableConfig(contextConfig, typeof(MockModel), "Models", 0);
contextConfig.Tables.Add(tableConfig);
config.Contexts.Add(contextConfig);
var dbContext = new MockDbContext();
var provider = new Mock<IServiceProvider>();
provider.Setup(p => p.GetService(typeof(MockDbContext))).Returns(dbContext);
var contextExplorer = new ContextExplorer(config, provider.Object, new Logger<ContextExplorer>(new LoggerFactory()));
// Act
var tableManager = contextExplorer.GetTableManager("Models");
// Assert
Assert.NotNull(tableManager);
Assert.IsType<TableManager<MockModel>>(tableManager);
}
[Fact]
public void GetTableManager_ReturnsNullIfDbContextNotFound() {
// Arrange
var config = new HopFrameConfig();
var contextConfig = new DbContextConfig(typeof(MockDbContext));
var tableConfig = new TableConfig(contextConfig, typeof(MockModel), "MockModels", 0);
contextConfig.Tables.Add(tableConfig);
config.Contexts.Add(contextConfig);
var provider = new Mock<IServiceProvider>();
var contextExplorer = new ContextExplorer(config, provider.Object, new Logger<ContextExplorer>(new LoggerFactory()));
// Act
var tableManager = contextExplorer.GetTableManager("Models");
// Assert
Assert.Null(tableManager);
}
[Fact]
public void GetTableManager_ReturnsNullIfTableNotFound() {
// Arrange
var config = new HopFrameConfig();
var contextConfig = new DbContextConfig(typeof(MockDbContext));
var tableConfig = new TableConfig(contextConfig, typeof(MockModel), "Models", 0);
contextConfig.Tables.Add(tableConfig);
config.Contexts.Add(contextConfig);
var dbContext = new MockDbContext();
var provider = new Mock<IServiceProvider>();
provider.Setup(p => p.GetService(typeof(MockDbContext))).Returns(dbContext);
var contextExplorer = new ContextExplorer(config, provider.Object, new Logger<ContextExplorer>(new LoggerFactory()));
// Act
var tableManager = contextExplorer.GetTableManager("InvalidTable");
// Assert
Assert.Null(tableManager);
}
[Fact]
public void SeedTableData_SetsTableSeededFlag() {
// Arrange
var config = new HopFrameConfig();
var contextConfig = new DbContextConfig(typeof(MockDbContext));
var tableConfig = contextConfig.Tables[0];
config.Contexts.Add(contextConfig);
var provider = new Mock<IServiceProvider>();
provider.Setup(p => p.GetService(typeof(MockDbContext))).Returns(new MockDbContext());
var contextExplorer = new ContextExplorer(config, provider.Object, new Logger<ContextExplorer>(new LoggerFactory()));
// Act
contextExplorer.GetTable("Models");
// Assert
Assert.True(tableConfig.Seeded);
}
[Fact]
public void SeedTableData_SetsTablePropertiesCorrectly() {
// Arrange
var config = new HopFrameConfig();
var contextConfig = new DbContextConfig(typeof(MockDbContext));
var tableConfig = contextConfig.Tables[0];
var tableConfig2 = contextConfig.Tables[1];
config.Contexts.Add(contextConfig);
var provider = new Mock<IServiceProvider>();
provider.Setup(p => p.GetService(typeof(MockDbContext))).Returns(new MockDbContext());
var contextExplorer = new ContextExplorer(config, provider.Object, new Logger<ContextExplorer>(new LoggerFactory()));
// Act
contextExplorer.GetTable("Models");
contextExplorer.GetTable("Models2");
// Assert
var relationProp = tableConfig.Properties.SingleOrDefault(prop => prop.Info.Name == nameof(MockModel.Model2));
var keyProp = tableConfig2.Properties.SingleOrDefault(prop => prop.Info.Name == nameof(MockModel2.Id));
Assert.NotNull(relationProp);
Assert.NotNull(keyProp);
Assert.True(relationProp.IsRelation);
Assert.True(relationProp.IsEnumerable);
Assert.True(keyProp.IsRequired);
Assert.False(keyProp.IsRelation);
Assert.False(keyProp.IsEnumerable);
}
}

View File

@@ -0,0 +1,41 @@
using HopFrame.Core.Services.Implementations;
namespace HopFrame.Tests.Core.Services;
public class DefaultAuthHandlerTests {
[Fact]
public async Task IsAuthenticatedAsync_ReturnsTrue() {
// Arrange
var authHandler = new DefaultAuthHandler();
// Act
var result = await authHandler.IsAuthenticatedAsync(null);
// Assert
Assert.True(result);
}
[Fact]
public async Task IsAuthenticatedAsync_WithPolicy_ReturnsTrue() {
// Arrange
var authHandler = new DefaultAuthHandler();
// Act
var result = await authHandler.IsAuthenticatedAsync("TestPolicy");
// Assert
Assert.True(result);
}
[Fact]
public async Task GetCurrentUserDisplayNameAsync_ReturnsEmptyString() {
// Arrange
var authHandler = new DefaultAuthHandler();
// Act
var result = await authHandler.GetCurrentUserDisplayNameAsync();
// Assert
Assert.Equal(string.Empty, result);
}
}

View File

@@ -0,0 +1,199 @@
using HopFrame.Core.Config;
using HopFrame.Core.Services;
using HopFrame.Core.Services.Implementations;
using HopFrame.Tests.Core.Models;
using Microsoft.EntityFrameworkCore;
using Moq;
namespace HopFrame.Tests.Core.Services;
public class DisplayPropertyTests {
private readonly Mock<IServiceProvider> _providerMock;
private readonly Mock<IContextExplorer> _explorerMock;
private readonly TableConfig _config;
private readonly TableManager<object> _tableManager;
public DisplayPropertyTests() {
var contextMock = new Mock<DbContext>();
_providerMock = new Mock<IServiceProvider>();
_explorerMock = new Mock<IContextExplorer>();
_config = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "Models", 0);
_tableManager =
new TableManager<object>(contextMock.Object, _config, _explorerMock.Object, _providerMock.Object);
}
[Fact]
public void DisplayProperty_ReturnsEmptyString_WhenItemIsNull() {
// Arrange
var prop = new PropertyConfig(typeof(string).GetProperty("Length")!, _config, 0);
// Act
var result = _tableManager.DisplayProperty(null, prop);
// Assert
Assert.Equal(string.Empty, result);
}
[Fact]
public void DisplayProperty_UsesFormatter_WhenListingProperty() {
// Arrange
var item = "test";
var prop = new PropertyConfig(typeof(string).GetProperty("Length")!, _config, 0) {
IsListingProperty = true,
Formatter = (obj, provider) => ((string)obj).ToUpper()
};
// Act
var result = _tableManager.DisplayProperty(item, prop);
// Assert
Assert.Equal("TEST", result);
}
[Fact]
public void DisplayProperty_UsesValueFormatter_WhenNotListingProperty() {
// Arrange
var item = "test";
var prop = new PropertyConfig(typeof(string).GetProperty("Length")!, _config, 0) {
Formatter = (obj, provider) => ((int)obj).ToString("D4")
};
// Act
var result = _tableManager.DisplayProperty(item, prop);
// Assert
Assert.Equal("0004", result);
}
[Fact]
public void DisplayProperty_ReturnsValueAsString_WhenNoFormatter() {
// Arrange
var item = "test";
var prop = new PropertyConfig(typeof(string).GetProperty("Length")!, _config, 0);
// Act
var result = _tableManager.DisplayProperty(item, prop);
// Assert
Assert.Equal("4", result);
}
[Fact]
public void DisplayProperty_ReturnsEnumerableCount_WhenEnumerableProperty() {
// Arrange
var item = new { List = new List<int> { 1, 2, 3 } };
var prop = new PropertyConfig(item.GetType().GetProperty("List")!, _config, 0) {
IsEnumerable = true
};
// Act
var result = _tableManager.DisplayProperty(item, prop);
// Assert
Assert.Equal("3", result);
}
[Fact]
public void DisplayProperty_UsesDisplayedProperty_WhenNoDirectFormatter() {
// Arrange
var item = new { Inner = new { Key = 42 } };
var innerPropInfo = item.Inner.GetType().GetProperty("Key");
var innerPropConfig = new PropertyConfig(innerPropInfo!, _config, 0);
var propInfo = item.GetType().GetProperty("Inner");
var prop = new PropertyConfig(propInfo!, _config, 0) {
DisplayedProperty = innerPropInfo
};
_explorerMock
.Setup(e => e.GetTable(item.Inner.GetType()))
.Returns(new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "Models", 0) {
Properties = { innerPropConfig }
});
// Act
var result = _tableManager.DisplayProperty(item, prop);
// Assert
Assert.Equal("42", result);
}
[Fact]
public void DisplayProperty_ReturnsEmptyString_WhenPropValueIsNull() {
// Arrange
var item = new { Name = (string?)null };
var prop = new PropertyConfig(item.GetType().GetProperty("Name")!, _config, 0);
// Act
var result = _tableManager.DisplayProperty(item, prop);
// Assert
Assert.Equal(string.Empty, result);
}
[Fact]
public void DisplayProperty_UsesEnumerableFormatter_WhenEnumerableAndValueProvided() {
// Arrange
var item = new { List = new List<int> { 1, 2, 3 } };
var prop = new PropertyConfig(item.GetType().GetProperty("List")!, _config, 0) {
IsEnumerable = true,
EnumerableFormatter = (obj, provider) => string.Join(",", ((IEnumerable<int>)obj))
};
// Act
var result = _tableManager.DisplayProperty(item, prop, item.List);
// Assert
Assert.Equal("1,2,3", result);
}
[Fact]
public void DisplayProperty_ReturnsEmptyString_WhenDisplayedPropertyAndInnerConfigIsNull() {
// Arrange
var item = new { Inner = new { Key = 42 } };
var innerPropInfo = item.Inner.GetType().GetProperty("Key");
var propInfo = item.GetType().GetProperty("Inner");
var prop = new PropertyConfig(propInfo!, _config, 0) {
DisplayedProperty = innerPropInfo
};
_explorerMock
.Setup(e => e.GetTable(item.Inner.GetType()))
.Returns((TableConfig?)null);
// Act
var result = _tableManager.DisplayProperty(item, prop);
// Assert
Assert.Equal("{ Key = 42 }", result); // Returns the value as string if inner config is null
}
[Fact]
public void DisplayProperty_ReturnsKeyValue_WhenDisplayedPropertyIsNull() {
// Arrange
var item = new { Inner = new { Key = 42 } };
var propInfo = item.GetType().GetProperty("Inner");
var prop = new PropertyConfig(propInfo!, _config, 0);
var keyProperty = item.Inner.GetType().GetProperty("Key");
// Act
var result = _tableManager.DisplayProperty(item, prop);
// Assert
Assert.Equal("{ Key = 42 }", result); // Returns key value as string if DisplayedProperty is null
}
[Fact]
public void DisplayProperty_ReturnsToStringValue_WhenNoKeyOrDisplayedProperty() {
// Arrange
var item = new { Inner = new { Name = "Test" } };
var propInfo = item.GetType().GetProperty("Inner");
var prop = new PropertyConfig(propInfo!, _config, 0);
// Act
var result = _tableManager.DisplayProperty(item, prop);
// Assert
Assert.Equal("{ Name = Test }", result); // Returns ToString value of inner property
}
}

View File

@@ -0,0 +1,192 @@
// ReSharper disable GenericEnumeratorNotDisposed
using HopFrame.Core.Config;
using HopFrame.Core.Services;
using HopFrame.Core.Services.Implementations;
using HopFrame.Tests.Core.Models;
using Microsoft.EntityFrameworkCore;
using Moq;
namespace HopFrame.Tests.Core.Services;
public class TableManagerTests {
private Mock<DbContext> CreateMockDbContext<TModel>(List<TModel> data) where TModel : class {
var dbContext = new Mock<DbContext>();
var dbSet = CreateMockDbSet(data);
dbContext.Setup(m => m.Set<TModel>()).Returns(dbSet.Object);
dbContext.Setup(m => m.Entry(It.IsAny<MockModel>())).Returns<MockModel>(entry => new MockDbContext().Entry(entry));
return dbContext;
}
private Mock<DbSet<TModel>> CreateMockDbSet<TModel>(List<TModel> data) where TModel : class {
var queryableData = data.AsQueryable();
var dbSet = new Mock<DbSet<TModel>>();
dbSet.As<IQueryable<TModel>>().Setup(m => m.Provider)
.Returns(new TestAsyncQueryProvider<TModel>(queryableData.Provider));
dbSet.As<IQueryable<TModel>>().Setup(m => m.Expression).Returns(queryableData.Expression);
dbSet.As<IQueryable<TModel>>().Setup(m => m.ElementType).Returns(queryableData.ElementType);
dbSet.As<IQueryable<TModel>>().Setup(m => m.GetEnumerator()).Returns(queryableData.GetEnumerator());
dbSet.As<IAsyncEnumerable<TModel>>().Setup(m => m.GetAsyncEnumerator(It.IsAny<CancellationToken>()))
.Returns(new TestAsyncEnumerator<TModel>(queryableData.GetEnumerator()));
dbSet.As<IQueryable<TModel>>().Setup(m => m.Provider)
.Returns(new TestAsyncQueryProvider<TModel>(queryableData.Provider));
dbSet.Setup(m => m.FindAsync(It.IsAny<object[]>())).ReturnsAsync((object[] ids) =>
data.FirstOrDefault(d => ids.Contains(d.GetType().GetProperty("Id")!.GetValue(d, null))));
return dbSet;
}
[Fact]
public void LoadPage_ReturnsPagedData() {
// Arrange
var data = new List<MockModel> {
new MockModel { Id = 1, Name = "Item1" },
new MockModel { Id = 2, Name = "Item2" },
new MockModel { Id = 3, Name = "Item3" }
};
var dbContext = CreateMockDbContext(data);
var config = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "Models", 0);
var explorer = new Mock<IContextExplorer>();
var provider = new Mock<IServiceProvider>();
var manager = new TableManager<MockModel>(dbContext.Object, config, explorer.Object, provider.Object);
// Act
var result = manager.LoadPage(1, 2).ToList();
// Assert
Assert.Single(result);
Assert.Equal("Item3", ((MockModel)result[0]).Name);
}
[Fact]
public async Task Search_ReturnsMatchingData() {
// Arrange
var data = new List<MockModel> {
new MockModel { Id = 1, Name = "Item1" },
new MockModel { Id = 2, Name = "Item2" },
new MockModel { Id = 3, Name = "TestItem" }
};
var dbContext = CreateMockDbContext(data);
var config = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "Models", 0);
config.Properties.Add(new PropertyConfig(typeof(MockModel).GetProperty("Name")!, config, 0)
{ Searchable = true });
var explorer = new Mock<IContextExplorer>();
var provider = new Mock<IServiceProvider>();
var manager = new TableManager<MockModel>(dbContext.Object, config, explorer.Object, provider.Object);
// Act
var (result, totalPages) = await manager.Search("Test", 0, 2);
// Assert
var collection = result as object[] ?? result.ToArray();
Assert.Single(collection);
Assert.Equal("TestItem", ((MockModel)collection.First()).Name);
Assert.Equal(1, totalPages);
}
[Fact]
public async Task TotalPages_ReturnsCorrectPageCount() {
// Arrange
var data = new List<MockModel> {
new MockModel { Id = 1, Name = "Item1" },
new MockModel { Id = 2, Name = "Item2" },
new MockModel { Id = 3, Name = "Item3" }
};
var dbContext = new MockDbContext();
var config = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "Models", 0);
var explorer = new Mock<IContextExplorer>();
var provider = new Mock<IServiceProvider>();
var manager = new TableManager<MockModel>(dbContext, config, explorer.Object, provider.Object);
await dbContext.Models.AddRangeAsync(data);
await dbContext.SaveChangesAsync();
// Act
var totalPages = await manager.TotalPages(2);
// Assert
Assert.Equal(2, totalPages);
}
[Fact]
public async Task DeleteItem_RemovesItemFromDbSet() {
// Arrange
var data = new List<MockModel> {
new MockModel { Id = 1, Name = "Item1" },
new MockModel { Id = 2, Name = "Item2" }
};
var dbContext = CreateMockDbContext(data);
var config = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "Models", 0);
var explorer = new Mock<IContextExplorer>();
var provider = new Mock<IServiceProvider>();
var manager = new TableManager<MockModel>(dbContext.Object, config, explorer.Object, provider.Object);
var item = data.First();
// Act
await manager.DeleteItem(item);
// Assert
dbContext.Verify(m => m.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
dbContext.Verify(m => m.Set<MockModel>().Remove(item), Times.Once);
}
[Fact]
public async Task EditItem_SavesChanges() {
// Arrange
var data = new List<MockModel> {
new MockModel { Id = 1, Name = "Item1" }
};
var dbContext = CreateMockDbContext(data);
var config = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "Models", 0);
var explorer = new Mock<IContextExplorer>();
var provider = new Mock<IServiceProvider>();
var manager = new TableManager<MockModel>(dbContext.Object, config, explorer.Object, provider.Object);
// Act
await manager.EditItem(data.First());
// Assert
dbContext.Verify(m => m.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task AddItem_AddsItemToDbSet() {
// Arrange
var data = new List<MockModel>();
var dbContext = CreateMockDbContext(data);
var config = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "Models", 0);
var explorer = new Mock<IContextExplorer>();
var provider = new Mock<IServiceProvider>();
var manager = new TableManager<MockModel>(dbContext.Object, config, explorer.Object, provider.Object);
var newItem = new MockModel { Id = 3, Name = "NewItem" };
// Act
await manager.AddItem(newItem);
// Assert
dbContext.Verify(m => m.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
dbContext.Verify(m => m.Set<MockModel>().AddAsync(newItem, It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task RevertChanges_ReloadsItem() {
// Arrange
var data = new List<MockModel> {
new MockModel { Id = 1, Name = "Item1" }
};
var dbContext = CreateMockDbContext(data);
var config = new TableConfig(new DbContextConfig(typeof(MockDbContext)), typeof(MockModel), "Models", 0);
var explorer = new Mock<IContextExplorer>();
var provider = new Mock<IServiceProvider>();
var manager = new TableManager<MockModel>(dbContext.Object, config, explorer.Object, provider.Object);
var item = data.First();
// Act
await manager.RevertChanges(item);
// Assert
dbContext.Verify(m => m.Entry(item), Times.Once);
}
}