diff --git a/src/.editorconfig b/src/.editorconfig index dcf65efd1..ee1c896a8 100644 --- a/src/.editorconfig +++ b/src/.editorconfig @@ -10,7 +10,7 @@ indent_style = space charset = utf-8-bom trim_trailing_whitespace = true insert_final_newline = true -max_line_length = 180 +max_line_length = 160 # Microsoft .NET properties csharp_preserve_single_line_blocks = true diff --git a/src/Application/Framework.Application.Tests/Framework.Application.Tests.csproj b/src/Application/Framework.Application.Tests/Framework.Application.Tests.csproj index f6403c8e1..7395050bc 100644 --- a/src/Application/Framework.Application.Tests/Framework.Application.Tests.csproj +++ b/src/Application/Framework.Application.Tests/Framework.Application.Tests.csproj @@ -10,7 +10,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Application/Framework.Application.Tests/PeriodTests.cs b/src/Application/Framework.Application.Tests/PeriodTests.cs index 87c5cff45..be6feb93e 100644 --- a/src/Application/Framework.Application.Tests/PeriodTests.cs +++ b/src/Application/Framework.Application.Tests/PeriodTests.cs @@ -41,10 +41,10 @@ public void GetFinancialYear_MonthOutOfRange_ThrowArgumentOutOfRangeException(in var service = new FinancialYearCalculator(new FinancialYearServiceSettings()); // Act - Action action = () => service.GetFinancialYear(2017, month); + var ex = Record.Exception(() => service.GetFinancialYear(2017, month)); // Assert - Assert.Throws(action); + Assert.IsType(ex); } /// @@ -61,9 +61,9 @@ public void GetFinancialYear_YearOutOfRange_ThrowArgumentOutOfRangeException(int var service = new FinancialYearCalculator(new FinancialYearServiceSettings()); // Act - Action action = () => service.GetFinancialYear(year, month); + var ex = Record.Exception(() => service.GetFinancialYear(year, month)); // Assert - Assert.Throws(action); + Assert.IsType(ex); } } diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment.LegacyContext/Framework.AutomationCore.ServiceEnvironment.LegacyContext.csproj b/src/AutomationCore/Framework.AutomationCore.Legacy/Framework.AutomationCore.Legacy.csproj similarity index 72% rename from src/AutomationCore/Framework.AutomationCore.ServiceEnvironment.LegacyContext/Framework.AutomationCore.ServiceEnvironment.LegacyContext.csproj rename to src/AutomationCore/Framework.AutomationCore.Legacy/Framework.AutomationCore.Legacy.csproj index e9e84160c..bb3f58337 100644 --- a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment.LegacyContext/Framework.AutomationCore.ServiceEnvironment.LegacyContext.csproj +++ b/src/AutomationCore/Framework.AutomationCore.Legacy/Framework.AutomationCore.Legacy.csproj @@ -1,7 +1,7 @@  - Luxoft.Framework.AutomationCore.ServiceEnvironment.LegacyContext + Luxoft.Framework.AutomationCore.Legacy Framework.AutomationCore @@ -15,7 +15,7 @@ - + diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment.LegacyContext/IntegrationTestBase.cs b/src/AutomationCore/Framework.AutomationCore.Legacy/IntegrationTestBase.cs similarity index 79% rename from src/AutomationCore/Framework.AutomationCore.ServiceEnvironment.LegacyContext/IntegrationTestBase.cs rename to src/AutomationCore/Framework.AutomationCore.Legacy/IntegrationTestBase.cs index ceb3b13a1..825b8b09f 100644 --- a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment.LegacyContext/IntegrationTestBase.cs +++ b/src/AutomationCore/Framework.AutomationCore.Legacy/IntegrationTestBase.cs @@ -3,7 +3,6 @@ using Framework.Application; using Framework.Application.Repository; using Framework.AutomationCore.RootServiceProviderContainer; -using Framework.AutomationCore.ServiceProviderPool; using Framework.BLL.DTOMapping.Domain; using Framework.Configuration.BLL; using Framework.Configuration.Domain; @@ -18,15 +17,14 @@ namespace Framework.AutomationCore; -public abstract class IntegrationTestBase(IServiceProviderPool rootServiceProviderPool) - : IntegrationTestBase(rootServiceProviderPool), IRootServiceProviderContainer +public abstract class IntegrationTestBase(IServiceProvider rootServiceProvider) : RootServiceProviderContainer(rootServiceProvider) where TBLLContext : IServiceProviderContainer { public Task EvaluateAsync( DBSessionMode sessionMode, UserCredential? customUserCredential, Func> getResult) => - this.RootServiceProvider.GetRequiredService>().EvaluateAsync(sessionMode, customUserCredential, getResult); + rootServiceProvider.GetRequiredService>().EvaluateAsync(sessionMode, customUserCredential, getResult); protected IConfigurationBLLContext GetConfigurationBLLContext(TBLLContext context) => context.ServiceProvider.GetRequiredService(); @@ -34,7 +32,7 @@ public Task EvaluateAsync( /// /// Отчистка списка нотифицаций /// - public override void ClearNotifications() => + public virtual void ClearNotifications() => this.EvaluateWrite(context => this.GetConfigurationBLLContext(context).Logics.DomainObjectNotification.Pipe(bll => bll.GetFullList().ForEach(bll.Remove))); /// @@ -46,12 +44,12 @@ protected virtual List> GetModifications() => this.GetConfigurationBLLContext(context).Logics.DomainObjectModification.GetFullList() .ToList(mod => new ObjectModificationInfoDTO - { - Identity = mod.DomainObjectId, - ModificationType = mod.Type, - Revision = mod.Revision, - TypeInfoDescription = new TypeInfoDescriptionDTO { Name = mod.DomainType.Name, Namespace = mod.DomainType.Namespace } - })); + { + Identity = mod.DomainObjectId, + ModificationType = mod.Type, + Revision = mod.Revision, + TypeInfoDescription = new TypeInfoDescriptionDTO { Name = mod.DomainType.Name, Namespace = mod.DomainType.Namespace } + })); /// /// Отчистка списка модификаций @@ -62,7 +60,7 @@ protected virtual void ClearModifications() => /// /// Отчистка интеграционных евентов /// - public override void ClearIntegrationEvents() + public virtual void ClearIntegrationEvents() { this.ClearModifications(); diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment.LegacyContext/RootServiceProviderContainer/ContextEvaluatorExtensions.cs b/src/AutomationCore/Framework.AutomationCore.Legacy/RootServiceProviderContainer/ContextEvaluatorExtensions.cs similarity index 100% rename from src/AutomationCore/Framework.AutomationCore.ServiceEnvironment.LegacyContext/RootServiceProviderContainer/ContextEvaluatorExtensions.cs rename to src/AutomationCore/Framework.AutomationCore.Legacy/RootServiceProviderContainer/ContextEvaluatorExtensions.cs diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment.LegacyContext/RootServiceProviderContainer/ContextEvaluatorWithMappingExtensions.cs b/src/AutomationCore/Framework.AutomationCore.Legacy/RootServiceProviderContainer/ContextEvaluatorWithMappingExtensions.cs similarity index 100% rename from src/AutomationCore/Framework.AutomationCore.ServiceEnvironment.LegacyContext/RootServiceProviderContainer/ContextEvaluatorWithMappingExtensions.cs rename to src/AutomationCore/Framework.AutomationCore.Legacy/RootServiceProviderContainer/ContextEvaluatorWithMappingExtensions.cs diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment.LegacyContext/RootServiceProviderContainer/IRootServiceProviderContainer.cs b/src/AutomationCore/Framework.AutomationCore.Legacy/RootServiceProviderContainer/IRootServiceProviderContainer.cs similarity index 100% rename from src/AutomationCore/Framework.AutomationCore.ServiceEnvironment.LegacyContext/RootServiceProviderContainer/IRootServiceProviderContainer.cs rename to src/AutomationCore/Framework.AutomationCore.Legacy/RootServiceProviderContainer/IRootServiceProviderContainer.cs diff --git a/src/AutomationCore/Framework.AutomationCore.Legacy/RootServiceProviderContainer/RootServiceProviderContainer.cs b/src/AutomationCore/Framework.AutomationCore.Legacy/RootServiceProviderContainer/RootServiceProviderContainer.cs new file mode 100644 index 000000000..7e236216c --- /dev/null +++ b/src/AutomationCore/Framework.AutomationCore.Legacy/RootServiceProviderContainer/RootServiceProviderContainer.cs @@ -0,0 +1,3 @@ +namespace Framework.AutomationCore.RootServiceProviderContainer; + +public class RootServiceProviderContainer(IServiceProvider rootServiceProvider) : RootServiceProviderContainer(rootServiceProvider), IRootServiceProviderContainer; diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment.LegacyContext/RootServiceProviderContainer/RootServiceProviderContainer.cs b/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment.LegacyContext/RootServiceProviderContainer/RootServiceProviderContainer.cs deleted file mode 100644 index f13c8b40f..000000000 --- a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment.LegacyContext/RootServiceProviderContainer/RootServiceProviderContainer.cs +++ /dev/null @@ -1,4 +0,0 @@ -namespace Framework.AutomationCore.RootServiceProviderContainer; - -public abstract class RootServiceProviderContainer(IServiceProvider rootServiceProvider) - : RootServiceProviderContainer(rootServiceProvider), IRootServiceProviderContainer; diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/Framework.AutomationCore.ServiceEnvironment.csproj b/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/Framework.AutomationCore.ServiceEnvironment.csproj deleted file mode 100644 index d413da5e6..000000000 --- a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/Framework.AutomationCore.ServiceEnvironment.csproj +++ /dev/null @@ -1,21 +0,0 @@ - - - - Luxoft.Framework.AutomationCore.ServiceEnvironment - Framework.AutomationCore - - - - - - - - - - - - - - - - diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/IntegrationTestBase.cs b/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/IntegrationTestBase.cs deleted file mode 100644 index a0bcb5cf1..000000000 --- a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/IntegrationTestBase.cs +++ /dev/null @@ -1,82 +0,0 @@ -using Framework.AutomationCore.Enums; -using Framework.AutomationCore.ServiceEnvironment.Services; -using Framework.AutomationCore.ServiceProviderPool; -using Framework.AutomationCore.Utils.DatabaseUtils; - -using Microsoft.Extensions.DependencyInjection; - -using Anch.SecuritySystem.Testing; - -namespace Framework.AutomationCore; - -public abstract class IntegrationTestBase(IServiceProviderPool rootServiceProviderPool) - : RootServiceProviderContainer.RootServiceProviderContainer(rootServiceProviderPool.Get()) -{ - public virtual void Initialize() - { - this.ReattachDatabase(); - this.ClearNotifications(); - this.ClearIntegrationEvents(); - this.ResetServices(); - } - - public virtual void Cleanup() - { - try - { - this.DropDatabaseAfterTest(); - this.CleanupTestEnvironment(); - } - finally - { - this.ReleaseServiceProvider(); - } - } - - protected virtual void ResetServices() - { - this.RootServiceProvider.GetService()?.Reset(); - this.RootServiceProvider.GetService()?.Reset(); - } - - protected virtual void DropDatabaseAfterTest() - { - if (this.AutomationFrameworkSettings.UseLocalDb || this.AutomationFrameworkSettings.TestRunMode == TestRunMode.DefaultRunModeOnEmptyDatabase) - { - AssemblyInitializeAndCleanupBase.RunAction("Drop Database", this.DatabaseContext.Drop); - } - } - - protected virtual void ReleaseServiceProvider() - => rootServiceProviderPool.Release(this.RootServiceProvider); - - protected virtual void ReattachDatabase() - { - switch (this.AutomationFrameworkSettings.TestRunMode) - { - case TestRunMode.DefaultRunModeOnEmptyDatabase: - case TestRunMode.RestoreDatabaseUsingAttach: - AssemblyInitializeAndCleanupBase.RunAction("Drop Database", this.DatabaseContext.Drop); - AssemblyInitializeAndCleanupBase.RunAction("Restore Databases", this.DatabaseContext.AttachDatabase); - break; - } - } - - protected virtual void CleanupTestEnvironment() - { - } - - /// - /// Отчистка списка нотифицаций - /// - public virtual void ClearNotifications() - { - } - - /// - /// Отчистка интеграционных евентов - /// - public virtual void ClearIntegrationEvents() - { - } -} diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/RootServiceProviderContainer/IRootServiceProviderContainer.cs b/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/RootServiceProviderContainer/IRootServiceProviderContainer.cs deleted file mode 100644 index ed88e6f66..000000000 --- a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/RootServiceProviderContainer/IRootServiceProviderContainer.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Framework.AutomationCore.RootServiceProviderContainer; - -public interface IRootServiceProviderContainer -{ - IServiceProvider RootServiceProvider { get; } -} diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/RootServiceProviderContainer/RootServiceProviderContainer.cs b/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/RootServiceProviderContainer/RootServiceProviderContainer.cs deleted file mode 100644 index 461122bdb..000000000 --- a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/RootServiceProviderContainer/RootServiceProviderContainer.cs +++ /dev/null @@ -1,28 +0,0 @@ -using Framework.Application.FinancialYear; -using Framework.AutomationCore.ServiceEnvironment; -using Framework.AutomationCore.Settings; -using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; - -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.DependencyInjection; - -using Anch.SecuritySystem; - -namespace Framework.AutomationCore.RootServiceProviderContainer; - -public abstract class RootServiceProviderContainer(IServiceProvider rootServiceProvider) : IRootServiceProviderContainer -{ - public virtual IServiceProvider RootServiceProvider { get; } = rootServiceProvider; - - public AutomationFrameworkSettings AutomationFrameworkSettings => this.GetAutomationFrameworkSettings(); - - public TimeProvider TimeProvider => this.GetTimeProvider(); - - public IFinancialYearService FinancialYearService => this.RootServiceProvider.GetRequiredService(); - - public IDatabaseContext DatabaseContext => this.GetDatabaseContext(); - - public virtual ControllerEvaluator GetControllerEvaluator(UserCredential? userCredential = null) - where TController : ControllerBase => - this.RootServiceProvider.GetDefaultControllerEvaluator(userCredential); -} diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/TestInitializeAndCleanup.cs b/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/TestInitializeAndCleanup.cs deleted file mode 100644 index 8a26d3115..000000000 --- a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/TestInitializeAndCleanup.cs +++ /dev/null @@ -1,62 +0,0 @@ -using Framework.AutomationCore.Enums; -using Framework.AutomationCore.ServiceEnvironment.Services; -using Framework.AutomationCore.Settings; -using Framework.AutomationCore.Utils.DatabaseUtils; -using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; - -using Microsoft.Extensions.Options; - -using Anch.SecuritySystem.Testing; - -namespace Framework.AutomationCore; - -public class TestInitializeAndCleanup( - IOptions settings, - IDatabaseContext databaseContext, - IntegrationTestTimeProvider timeProvider, - RootImpersonateServiceState rootImpersonateServiceState) -{ - private readonly AutomationFrameworkSettings settings = settings.Value; - - public virtual async Task InitializeAsync() - { - this.ReattachDatabase(); - this.ResetServices(); - } - - public virtual async Task CleanupAsync() - { - this.DropDatabaseAfterTest(); - this.CleanupTestEnvironment(); - } - - protected virtual void ResetServices() - { - timeProvider.Reset(); - rootImpersonateServiceState.Reset(); - } - - protected virtual void DropDatabaseAfterTest() - { - if (this.settings.UseLocalDb || this.settings.TestRunMode == TestRunMode.DefaultRunModeOnEmptyDatabase || this.settings.TestsParallelize) - { - AssemblyInitializeAndCleanupBase.RunAction("Drop Database", databaseContext.Drop); - } - } - - protected virtual void ReattachDatabase() - { - switch (this.settings.TestRunMode) - { - case TestRunMode.DefaultRunModeOnEmptyDatabase: - case TestRunMode.RestoreDatabaseUsingAttach: - AssemblyInitializeAndCleanupBase.RunAction("Drop Database", databaseContext.Drop); - AssemblyInitializeAndCleanupBase.RunAction("Restore Databases", databaseContext.AttachDatabase); - break; - } - } - - protected virtual void CleanupTestEnvironment() - { - } -} diff --git a/src/AutomationCore/Framework.AutomationCore.Xunit/AutomationCoreFrameworkInitializer.cs b/src/AutomationCore/Framework.AutomationCore.Xunit/AutomationCoreFrameworkInitializer.cs index f0dad9dc1..28d2e226f 100644 --- a/src/AutomationCore/Framework.AutomationCore.Xunit/AutomationCoreFrameworkInitializer.cs +++ b/src/AutomationCore/Framework.AutomationCore.Xunit/AutomationCoreFrameworkInitializer.cs @@ -1,73 +1,73 @@ -using Bss.Testing.Xunit.Interfaces; +//using Bss.Testing.Xunit.Interfaces; -using Framework.AutomationCore.Extensions; -using Framework.AutomationCore.Settings; -using Framework.AutomationCore.Utils.DatabaseUtils; -using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; -using Framework.AutomationCore.Xunit.ServiceProviderPool; +//using Framework.AutomationCore.Extensions; +//using Framework.AutomationCore.Settings; +//using Framework.AutomationCore.Utils.DatabaseUtils; +//using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; +//using Framework.AutomationCore.Xunit.ServiceProviderPool; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Options; +//using Microsoft.Extensions.Configuration; +//using Microsoft.Extensions.DependencyInjection; +//using Microsoft.Extensions.DependencyInjection.Extensions; +//using Microsoft.Extensions.Options; -namespace Framework.AutomationCore.Xunit; +//namespace Framework.AutomationCore.Xunit; -public abstract class AutomationCoreFrameworkInitializer : IFrameworkInitializer -{ - public abstract IServiceCollection ConfigureFramework(IServiceCollection services); +//public abstract class AutomationCoreFrameworkInitializer : IFrameworkInitializer +//{ +// public abstract IServiceCollection ConfigureFramework(IServiceCollection services); - public abstract IServiceProvider ConfigureTestEnvironment(IServiceCollection services, IConfiguration configuration); +// public abstract IServiceProvider ConfigureTestEnvironment(IServiceCollection services, IConfiguration configuration); - public IServiceProvider GetFrameworkServiceProvider() - { - var frameworkServices = new ServiceCollection(); - AddSettings(frameworkServices); - this.ConfigureFramework(frameworkServices); +// public IServiceProvider GetFrameworkServiceProvider() +// { +// var frameworkServices = new ServiceCollection(); +// AddSettings(frameworkServices); +// this.ConfigureFramework(frameworkServices); - frameworkServices.TryAddSingleton(); - frameworkServices.TryAddSingleton(); +// frameworkServices.TryAddSingleton(); +// frameworkServices.TryAddSingleton(); - frameworkServices.AddSingleton( - sp => new ServiceProviderPoolFunc(this.GetPoolServiceProviderFunc(sp))); +// frameworkServices.AddSingleton( +// sp => new ServiceProviderPoolFunc(this.GetPoolServiceProviderFunc(sp))); - return frameworkServices.BuildServiceProvider( - new ServiceProviderOptions - { - ValidateScopes = true, - ValidateOnBuild = true - }); - } +// return frameworkServices.BuildServiceProvider( +// new ServiceProviderOptions +// { +// ValidateScopes = true, +// ValidateOnBuild = true +// }); +// } - private Func GetPoolServiceProviderFunc(IServiceProvider frameworkSp) - { - var rootConfiguration = frameworkSp.GetRequiredService(); - var automationFrameworkSettings = frameworkSp.GetRequiredService>(); +// private Func GetPoolServiceProviderFunc(IServiceProvider frameworkSp) +// { +// var rootConfiguration = frameworkSp.GetRequiredService(); +// var automationFrameworkSettings = frameworkSp.GetRequiredService>(); - return () => - { - var databaseContext = new DatabaseContext(rootConfiguration, automationFrameworkSettings); - var configuration = rootConfiguration.BuildFromRootWithConnectionStrings(databaseContext); +// return () => +// { +// var databaseContext = new DatabaseContext(rootConfiguration, automationFrameworkSettings); +// var configuration = rootConfiguration.BuildFromRootWithConnectionStrings(databaseContext); - var environmentServices = new ServiceCollection() - .AddSingleton(databaseContext) - .AddSingleton(configuration) - .AddSingleton(automationFrameworkSettings); +// var environmentServices = new ServiceCollection() +// .AddSingleton(databaseContext) +// .AddSingleton(configuration) +// .AddSingleton(automationFrameworkSettings); - return this.ConfigureTestEnvironment(environmentServices, configuration); - }; - } +// return this.ConfigureTestEnvironment(environmentServices, configuration); +// }; +// } - private static void AddSettings(IServiceCollection services) - { - services.AddOptions(); - services.AddSingleton>( - s => - { - return new ConfigureOptions( - opt => s.GetRequiredService() - .Bind(nameof(AutomationFrameworkSettings), opt)); - }); - } -} +// private static void AddSettings(IServiceCollection services) +// { +// services.AddOptions(); +// services.AddSingleton>( +// s => +// { +// return new ConfigureOptions( +// opt => s.GetRequiredService() +// .Bind(nameof(AutomationFrameworkSettings), opt)); +// }); +// } +//} diff --git a/src/AutomationCore/Framework.AutomationCore.Xunit/DependencyInjection.cs b/src/AutomationCore/Framework.AutomationCore.Xunit/DependencyInjection.cs index 30a09ccfb..fd1f43432 100644 --- a/src/AutomationCore/Framework.AutomationCore.Xunit/DependencyInjection.cs +++ b/src/AutomationCore/Framework.AutomationCore.Xunit/DependencyInjection.cs @@ -1,17 +1,17 @@ -using Bss.Testing.Xunit.Interfaces; +//using Bss.Testing.Xunit.Interfaces; -using Framework.AutomationCore.ServiceEnvironment; -using Framework.AutomationCore.Settings; -using Framework.AutomationCore.Xunit.ServiceEnvironment; +//using Framework.AutomationCore.ServiceEnvironment; +//using Framework.AutomationCore.Settings; +//using Framework.AutomationCore.Xunit.ServiceEnvironment; -using Microsoft.Extensions.DependencyInjection; +//using Microsoft.Extensions.DependencyInjection; -namespace Framework.AutomationCore.Xunit; +//namespace Framework.AutomationCore.Xunit; -public static class DependencyInjection -{ - public static IServiceCollection AddXunitIntegrationTests(this IServiceCollection services, Action? setup = null) => - services - .AddSingleton() - .AddIntegrationTests(setup); -} +//public static class DependencyInjection +//{ +// public static IServiceCollection AddXunitIntegrationTests(this IServiceCollection services, Action? setup = null) => +// services +// .AddSingleton() +// .AddIntegrationTests(setup); +//} diff --git a/src/AutomationCore/Framework.AutomationCore.Xunit/Framework.AutomationCore.Xunit.csproj b/src/AutomationCore/Framework.AutomationCore.Xunit/Framework.AutomationCore.Xunit.csproj index d92a0413a..995539b25 100644 --- a/src/AutomationCore/Framework.AutomationCore.Xunit/Framework.AutomationCore.Xunit.csproj +++ b/src/AutomationCore/Framework.AutomationCore.Xunit/Framework.AutomationCore.Xunit.csproj @@ -8,12 +8,4 @@ - - - - - - - - diff --git a/src/AutomationCore/Framework.AutomationCore.Xunit/ServiceEnvironment/DiAssemblyInitializeAndCleanup.cs b/src/AutomationCore/Framework.AutomationCore.Xunit/ServiceEnvironment/DiAssemblyInitializeAndCleanup.cs deleted file mode 100644 index a578f2d4a..000000000 --- a/src/AutomationCore/Framework.AutomationCore.Xunit/ServiceEnvironment/DiAssemblyInitializeAndCleanup.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Bss.Testing.Xunit.Interfaces; - -using Framework.AutomationCore.Settings; -using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; - -using Microsoft.Extensions.Options; - -namespace Framework.AutomationCore.Xunit.ServiceEnvironment; - -public class DiAssemblyInitializeAndCleanup( - IOptions settings, - ITestDatabaseGenerator databaseGenerator) - : AssemblyInitializeAndCleanupBase, IAssemblyInitializeAndCleanup -{ - private readonly AutomationFrameworkSettings settings = settings.Value; - - public async Task EnvironmentInitializeAsync() => await this.InitializeAsync(this.settings, databaseGenerator); - - public async Task EnvironmentCleanupAsync() => await this.CleanupAsync(this.settings, databaseGenerator); -} diff --git a/src/AutomationCore/Framework.AutomationCore.Xunit/ServiceEnvironment/DiTestInitializeAndCleanup.cs b/src/AutomationCore/Framework.AutomationCore.Xunit/ServiceEnvironment/DiTestInitializeAndCleanup.cs deleted file mode 100644 index 0abbf7997..000000000 --- a/src/AutomationCore/Framework.AutomationCore.Xunit/ServiceEnvironment/DiTestInitializeAndCleanup.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Bss.Testing.Xunit.Interfaces; - -using Framework.AutomationCore.ServiceEnvironment.Services; -using Framework.AutomationCore.Settings; -using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; - -using Microsoft.Extensions.Options; - -using Anch.SecuritySystem.Testing; - -namespace Framework.AutomationCore.Xunit.ServiceEnvironment; - -public class DiTestInitializeAndCleanup( - IOptions settings, - IDatabaseContext databaseContext, - IntegrationTestTimeProvider timeProvider, - RootImpersonateServiceState rootImpersonateServiceState) - : TestInitializeAndCleanup(settings, databaseContext, timeProvider, rootImpersonateServiceState), - ITestInitializeAndCleanup; diff --git a/src/AutomationCore/Framework.AutomationCore.Xunit/ServiceProviderPool/DiServiceProviderPool.cs b/src/AutomationCore/Framework.AutomationCore.Xunit/ServiceProviderPool/DiServiceProviderPool.cs deleted file mode 100644 index 879bf7ce8..000000000 --- a/src/AutomationCore/Framework.AutomationCore.Xunit/ServiceProviderPool/DiServiceProviderPool.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Collections.Concurrent; - -using Bss.Testing.Xunit.Interfaces; - -namespace Framework.AutomationCore.Xunit.ServiceProviderPool; - -public class DiServiceProviderPool(ServiceProviderPoolFunc createServiceProviderFunc) : ITestServiceProviderPool -{ - private readonly Func createServiceProviderFunc = createServiceProviderFunc.Value; - private readonly ConcurrentBag providersCache = []; - - public IServiceProvider Get() => - this.providersCache.TryTake(out var provider) ? provider : this.createServiceProviderFunc.Invoke(); - - public void Release(IServiceProvider serviceProvider) => this.providersCache.Add(serviceProvider); -} diff --git a/src/AutomationCore/Framework.AutomationCore.Xunit/ServiceProviderPool/ServiceProviderPoolFunc.cs b/src/AutomationCore/Framework.AutomationCore.Xunit/ServiceProviderPool/ServiceProviderPoolFunc.cs deleted file mode 100644 index 15409c654..000000000 --- a/src/AutomationCore/Framework.AutomationCore.Xunit/ServiceProviderPool/ServiceProviderPoolFunc.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Framework.AutomationCore.Xunit.ServiceProviderPool; - -public class ServiceProviderPoolFunc(Func func) -{ - public readonly Func Value = func; -} diff --git a/src/AutomationCore/Framework.AutomationCore/AssemblyInitializeAndCleanup.cs b/src/AutomationCore/Framework.AutomationCore/AssemblyInitializeAndCleanup.cs deleted file mode 100644 index e20aa7a52..000000000 --- a/src/AutomationCore/Framework.AutomationCore/AssemblyInitializeAndCleanup.cs +++ /dev/null @@ -1,56 +0,0 @@ -using Framework.AutomationCore.Settings; -using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; - -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Options; - -namespace Framework.AutomationCore; - -public class AssemblyInitializeAndCleanup( - Func getServiceProviderAction, - Action releaseServiceProviderAction) - : AssemblyInitializeAndCleanupBase -{ - public async Task EnvironmentInitializeAsync() - { - var serviceProvider = getServiceProviderAction.Invoke(); - - try - { - await this.InitializeAsync(serviceProvider); - } - finally - { - releaseServiceProviderAction(serviceProvider); - } - } - - public async Task EnvironmentCleanupAsync() - { - var serviceProvider = getServiceProviderAction.Invoke(); - try - { - await this.CleanupAsync(serviceProvider); - } - finally - { - releaseServiceProviderAction(serviceProvider); - } - } - - protected async Task CleanupAsync(IServiceProvider serviceProvider) - { - var settings = serviceProvider.GetRequiredService>(); - var databaseGenerator = serviceProvider.GetRequiredService(); - - await this.CleanupAsync(settings.Value, databaseGenerator); - } - - protected async Task InitializeAsync(IServiceProvider serviceProvider) - { - var settings = serviceProvider.GetRequiredService>(); - var databaseGenerator = serviceProvider.GetRequiredService(); - - await this.InitializeAsync(settings.Value, databaseGenerator); - } -} diff --git a/src/AutomationCore/Framework.AutomationCore/AssemblyInitializeAndCleanupBase.cs b/src/AutomationCore/Framework.AutomationCore/AssemblyInitializeAndCleanupBase.cs deleted file mode 100644 index 84a8a1fe6..000000000 --- a/src/AutomationCore/Framework.AutomationCore/AssemblyInitializeAndCleanupBase.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System.Diagnostics; - -using Framework.AutomationCore.Enums; -using Framework.AutomationCore.Settings; -using Framework.AutomationCore.Utils.DatabaseUtils; -using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; - -namespace Framework.AutomationCore; - -public class AssemblyInitializeAndCleanupBase -{ - public static void RunAction(string name, Action action) - { - var watch = new Stopwatch(); - - Console.WriteLine(name); - - watch.Start(); - action(); - watch.Stop(); - - Console.WriteLine("Elapsed time - {0}", watch.Elapsed); - Console.WriteLine(); - Console.WriteLine(); - } - - protected virtual async Task CleanupAsync(AutomationFrameworkSettings settings, ITestDatabaseGenerator databaseGenerator) - { - switch (settings.TestRunMode) - { - case TestRunMode.DefaultRunModeOnEmptyDatabase: - await databaseGenerator.CheckTestDatabaseAsync(); - databaseGenerator.DatabaseContext.Drop(); - databaseGenerator.DeleteDetachedFiles(); - databaseGenerator.DeleteLocalDb(); - break; - - default: - databaseGenerator.DeleteLocalDb(); - break; - } - } - - - protected virtual async Task InitializeAsync(AutomationFrameworkSettings settings, ITestDatabaseGenerator databaseGenerator) - { - switch (settings.TestRunMode) - { - case TestRunMode.RestoreDatabaseUsingAttach: - databaseGenerator.CreateLocalDb(); - await databaseGenerator.CheckTestDatabaseAsync(); - await databaseGenerator.CheckAndCreateDetachedFilesAsync(); - databaseGenerator.DatabaseContext.Drop(); - break; - case TestRunMode.GenerateTestDataOnExistingDatabase: - break; - default: - databaseGenerator.CreateLocalDb(); - await databaseGenerator.CheckTestDatabaseAsync(); - databaseGenerator.DeleteDetachedFiles(); - databaseGenerator.DatabaseContext.ReCreate(); - await databaseGenerator.GenerateDatabasesAsync(); - databaseGenerator.ExecuteInsertsForDatabases(); - await databaseGenerator.GenerateTestDataAsync(); - databaseGenerator.DatabaseContext.CopyDetachedFiles(); - databaseGenerator.DatabaseContext.Drop(); - break; - } - } -} diff --git a/src/AutomationCore/Framework.AutomationCore/BssDatabaseFilePathExtractor.cs b/src/AutomationCore/Framework.AutomationCore/BssDatabaseFilePathExtractor.cs new file mode 100644 index 000000000..09e256e77 --- /dev/null +++ b/src/AutomationCore/Framework.AutomationCore/BssDatabaseFilePathExtractor.cs @@ -0,0 +1,69 @@ +using Anch.Core; +using Anch.DependencyInjection; +using Anch.Testing; +using Anch.Testing.Database; +using Anch.Testing.Database.DependencyInjection; + +using Framework.AutomationCore.ServiceEnvironment; +using Framework.AutomationCore.Settings; +using Framework.AutomationCore.TestingProvider; +using Framework.Core; +using Framework.Database; +using Framework.Database.ConnectionStringSource; + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace Framework.AutomationCore; + +public abstract class BssTestEnvironment : ITestEnvironment +{ + protected abstract IConfiguration Configuration { get; } + + private AutomationFrameworkSettings Settings => field ??= new AutomationFrameworkSettings().Self(this.Configuration.Bind); + + protected virtual string DefaultConnectionStringName => "DefaultConnection"; + + protected virtual string DefaultConnectionString => field ??= this.Configuration.GetConnectionString(this.DefaultConnectionStringName) + ?? throw new InvalidOperationException( + $"{this.DefaultConnectionStringName} connection string is not configured."); + + private TestDatabaseSettings TestDatabaseSettings => + field ??= new TestDatabaseSettings { InitMode = this.Settings.DatabaseInitMode, DefaultConnectionString = new(this.DefaultConnectionString) }; + + public bool AllowParallelization => this.Settings.TestsParallelize; + + protected virtual void InitServices(IServiceCollection services) + { + + } + + protected virtual void InitInitializers(IDatabaseTestingSetup setup) + { + + } + + public IServiceProvider BuildServiceProvider(IServiceCollection services) + { + services.AddOptions(); + + return services.AddSingleton(this.Configuration) + + .Self(this.InitServices) + + .AddIntegrationTests() + + .AddDatabaseTesting(dts => dts + .SetProvider() + .Self(this.InitInitializers) + .SetSettings(this.TestDatabaseSettings) + .RebindActualConnection(connectionString => + new ManualDefaultConnectionStringSource(connectionString.Value))) + + .Pipe(this.InternalBuildServiceProvider); + } + + protected virtual IServiceProvider InternalBuildServiceProvider(IServiceCollection services) => + services.AddValidator() + .BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true }); +} diff --git a/src/AutomationCore/Framework.AutomationCore/Enums/TestRunMode.cs b/src/AutomationCore/Framework.AutomationCore/Enums/TestRunMode.cs deleted file mode 100644 index 60ce04af9..000000000 --- a/src/AutomationCore/Framework.AutomationCore/Enums/TestRunMode.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Framework.AutomationCore.Enums; - -public enum TestRunMode -{ - DefaultRunModeOnEmptyDatabase = 0, - - RestoreDatabaseUsingAttach = 1, - - GenerateTestDataOnExistingDatabase = 2, -} diff --git a/src/AutomationCore/Framework.AutomationCore/Environment/TestEnvironment.cs b/src/AutomationCore/Framework.AutomationCore/Environment/TestEnvironment.cs deleted file mode 100644 index 2475bd399..000000000 --- a/src/AutomationCore/Framework.AutomationCore/Environment/TestEnvironment.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Framework.AutomationCore.ServiceProviderPool; - -namespace Framework.AutomationCore.Environment; - -public class TestEnvironment -{ - public readonly AssemblyInitializeAndCleanup AssemblyInitializeAndCleanup; - - public readonly IServiceProviderPool ServiceProviderPool; - - internal TestEnvironment(IServiceProviderPool serviceProviderPool, AssemblyInitializeAndCleanup assemblyInitializeAndCleanup) - { - this.AssemblyInitializeAndCleanup = assemblyInitializeAndCleanup; - this.ServiceProviderPool = serviceProviderPool; - } -} diff --git a/src/AutomationCore/Framework.AutomationCore/Environment/TestEnvironmentBuilder.cs b/src/AutomationCore/Framework.AutomationCore/Environment/TestEnvironmentBuilder.cs deleted file mode 100644 index 21d93ee64..000000000 --- a/src/AutomationCore/Framework.AutomationCore/Environment/TestEnvironmentBuilder.cs +++ /dev/null @@ -1,169 +0,0 @@ -using Anch.DependencyInjection; - -using Framework.AutomationCore.Extensions; -using Framework.AutomationCore.ServiceProviderPool; -using Framework.AutomationCore.Settings; -using Framework.AutomationCore.Utils.DatabaseUtils; -using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; - -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Options; - -namespace Framework.AutomationCore.Environment; - -public class TestEnvironmentBuilder -{ - private IConfiguration? withConfiguration; - - private Func? withServiceProviderBuildFunc; - - private Action withServiceProvAfterBuildAction = _ => { }; - - private Action withAutomationFrameworkSettings = _ => { }; - - private Type? withDatabaseGenerator; - - public TestEnvironmentBuilder WithConfiguration(IConfiguration rootConfiguration) - { - this.withConfiguration = rootConfiguration; - - return this; - } - - public TestEnvironmentBuilder WithDefaultConfiguration( - string environmentVariablesPrefix = "", - string settingsFileName = "appsettings.json") - { - this.withConfiguration = new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile(settingsFileName, false) - .AddJsonFile($@"{System.Environment.MachineName}.{settingsFileName}", true) - .AddEnvironmentVariables(environmentVariablesPrefix) - .Build(); - - return this; - } - - public TestEnvironmentBuilder WithAutomationFrameworkSettings(Action settings) - { - this.withAutomationFrameworkSettings = settings; - - return this; - } - - public TestEnvironmentBuilder WithServiceProviderBuildFunc(Func buildFunc) - { - this.withServiceProviderBuildFunc = buildFunc; - - return this; - } - - public TestEnvironmentBuilder WithServiceProviderAfterBuildAction(Action afterBuildAction) - { - this.withServiceProvAfterBuildAction = afterBuildAction; - - return this; - } - - public TestEnvironmentBuilder WithDatabaseGenerator() where T: ITestDatabaseGenerator - { - this.withDatabaseGenerator = typeof(T); - - return this; - } - - public TestEnvironment Build() - { - if (this.withConfiguration == null) - { - this.WithDefaultConfiguration(); - } - - if (this.withDatabaseGenerator == null) - { - throw new ArgumentException("Please provide DatabaseGenerator via '.WithDatabaseGenerator()'"); - } - - if (this.withServiceProviderBuildFunc == null) - { - throw new ArgumentException("Please provide ServiceProvider build function via '.WithServiceProviderBuildFunc()'"); - } - - var serviceProviderPool = this.GetServiceProviderPool( - this.withConfiguration!, - this.withServiceProviderBuildFunc, - this.withServiceProvAfterBuildAction, - this.withDatabaseGenerator, - this.withAutomationFrameworkSettings); - - return new TestEnvironment( - serviceProviderPool, - this.GetAssemblyInitializeAndCleanup(serviceProviderPool)); - } - - protected virtual AssemblyInitializeAndCleanup GetAssemblyInitializeAndCleanup( - IServiceProviderPool serviceProviderPool) => - new( - serviceProviderPool.Get, - serviceProviderPool.Release); - - protected virtual IServiceProvider BuildServiceProvider(IServiceCollection serviceCollection) => - serviceCollection - .AddValidator() - .Validate() - .BuildServiceProvider( - new ServiceProviderOptions { ValidateOnBuild = true, ValidateScopes = true }); - - protected virtual IServiceProviderPool GetServiceProviderPool( - IConfiguration rootConfiguration, - Func serviceProviderBuildFunc, - Action serviceProviderAfterBuildAction, - Type databaseGenerator, - Action settingsAction) => - new ServiceProviderPool.ServiceProviderPool( - () => this.ServiceProviderGenerationFunc( - serviceProviderBuildFunc, - serviceProviderAfterBuildAction, - rootConfiguration, - databaseGenerator, - settingsAction), - rootConfiguration.GetValue("TestsParallelize"), - rootConfiguration.GetValue("DisableServiceProviderPoolLimiter")); - - private IServiceProvider ServiceProviderGenerationFunc( - Func serviceProviderBuildFunc, - Action serviceProviderAfterBuildAction, - IConfiguration rootConfiguration, - Type databaseGeneratorType, - Action settingsAction) - { - var settings = GetSettings(rootConfiguration, settingsAction); - var databaseContext = new DatabaseContext(rootConfiguration, settings); - - var cfg = rootConfiguration.BuildFromRootWithConnectionStrings(databaseContext); - - var environmentServices = new ServiceCollection(); - serviceProviderBuildFunc.Invoke(cfg, environmentServices); - environmentServices.TryAddSingleton(settings); - environmentServices.TryAddSingleton(databaseContext); - environmentServices.AddSingleton(cfg) - .AddSingleton(typeof(ITestDatabaseGenerator), databaseGeneratorType); - - var environmentServiceProvider = this.BuildServiceProvider(environmentServices); - - serviceProviderAfterBuildAction(environmentServiceProvider); - - return environmentServiceProvider; - } - - private static IOptions GetSettings(IConfiguration configuration, Action action) - { - var settings = new AutomationFrameworkSettings(); - configuration.GetSection(nameof(AutomationFrameworkSettings)).Bind(settings); - action(settings); - - return Options.Create(settings); - } -} diff --git a/src/AutomationCore/Framework.AutomationCore/Extensions/ConfigurationExtensions.cs b/src/AutomationCore/Framework.AutomationCore/Extensions/ConfigurationExtensions.cs deleted file mode 100644 index 3fa66d88a..000000000 --- a/src/AutomationCore/Framework.AutomationCore/Extensions/ConfigurationExtensions.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; - -using Microsoft.Extensions.Configuration; - -namespace Framework.AutomationCore.Extensions; - -public static class ConfigurationExtensions -{ - public static IConfiguration BuildFromRootWithConnectionStrings( - this IConfiguration rootConfiguration, - IDatabaseContext databaseContext) => - new ConfigurationBuilder() - .AddConfiguration(rootConfiguration) - .AddInMemoryCollection( - rootConfiguration.GetSection("ConnectionStrings") - .GetChildren() - .ToDictionary(x => $"ConnectionStrings:{x.Key}", _ => databaseContext.Main.ConnectionString)) - .Build(); -} diff --git a/src/AutomationCore/Framework.AutomationCore/Extensions/Excel/Column.cs b/src/AutomationCore/Framework.AutomationCore/Extensions/Excel/Column.cs deleted file mode 100644 index 551701f63..000000000 --- a/src/AutomationCore/Framework.AutomationCore/Extensions/Excel/Column.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Framework.AutomationCore.Extensions.Excel; - -[AttributeUsage(AttributeTargets.All)] -public class Column : Attribute -{ - public string Name { get; set; } - - public int? Index { get; } - - public Column(string name) => this.Name = name; - - public Column(int index) => this.Index = index; -} diff --git a/src/AutomationCore/Framework.AutomationCore/Extensions/ObjectExtensions.cs b/src/AutomationCore/Framework.AutomationCore/Extensions/ObjectExtensions.cs deleted file mode 100644 index 2b6b6a7aa..000000000 --- a/src/AutomationCore/Framework.AutomationCore/Extensions/ObjectExtensions.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.ComponentModel; -using System.Reflection; - -namespace Framework.AutomationCore.Extensions; - -public static class ObjectExtensions -{ - public static string GetDescription(this Enum obj, string propertyName) - { - var propertyInfo = obj.GetType().GetProperty(propertyName); - var attr = propertyInfo?.GetCustomAttribute(typeof(DescriptionAttribute)); - - return attr != null - ? ((DescriptionAttribute)attr).Description - : propertyName; - } -} diff --git a/src/AutomationCore/Framework.AutomationCore/Extensions/StreamExtensions.cs b/src/AutomationCore/Framework.AutomationCore/Extensions/StreamExtensions.cs deleted file mode 100644 index fd55604d5..000000000 --- a/src/AutomationCore/Framework.AutomationCore/Extensions/StreamExtensions.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Framework.AutomationCore.Extensions; - -public static class StreamExtensions -{ - public static void Save(this Stream stream, string folder, string? fileName = null, string extension = "xlsx") - { - fileName = fileName != null ? $"{fileName}.{extension}" : $"report_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.{extension}"; - var filePath = Path.Combine(folder, fileName); - - using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write); - stream.CopyTo(fileStream); - stream.Close(); - fileStream.Close(); - } -} diff --git a/src/AutomationCore/Framework.AutomationCore/Framework.AutomationCore.csproj b/src/AutomationCore/Framework.AutomationCore/Framework.AutomationCore.csproj index 8d54dbe86..ed91a75b5 100644 --- a/src/AutomationCore/Framework.AutomationCore/Framework.AutomationCore.csproj +++ b/src/AutomationCore/Framework.AutomationCore/Framework.AutomationCore.csproj @@ -9,24 +9,17 @@ - - + + + - + - - - - - - - - - + diff --git a/src/AutomationCore/Framework.AutomationCore/Helpers/DatabaseHelper.cs b/src/AutomationCore/Framework.AutomationCore/Helpers/DatabaseHelper.cs deleted file mode 100644 index 0ca7568ac..000000000 --- a/src/AutomationCore/Framework.AutomationCore/Helpers/DatabaseHelper.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Reflection; - -using Dapper; -using Dapper.Contrib.Extensions; - -using Microsoft.Data.SqlClient; - -namespace Framework.AutomationCore.Helpers; - -public static class DatabaseHelper -{ - public static List GetAll(string connectionString) - where T : class - { - var tableName = GetTableName(typeof(T)); - - using (var connection = new SqlConnection(connectionString)) - { - connection.Open(); - return connection.Query($"SELECT * FROM {tableName}").ToList(); - } - } - - private static string GetTableName(Type type) - { - var tableAttrName = - type.GetCustomAttribute(false)?.Name - ?? (type.GetCustomAttributes(false).FirstOrDefault(attr => attr.GetType().Name == "TableAttribute") as dynamic)?.Name; - - if (tableAttrName != null) - { - return tableAttrName; - } - - throw new Exception($"Table name for '{type.Name}' not found"); - } -} diff --git a/src/AutomationCore/Framework.AutomationCore/RootServiceProviderContainer/IRootServiceProviderContainer.cs b/src/AutomationCore/Framework.AutomationCore/RootServiceProviderContainer/IRootServiceProviderContainer.cs new file mode 100644 index 000000000..d23a71ac3 --- /dev/null +++ b/src/AutomationCore/Framework.AutomationCore/RootServiceProviderContainer/IRootServiceProviderContainer.cs @@ -0,0 +1,16 @@ +using Anch.SecuritySystem; + +using Framework.AutomationCore.ServiceEnvironment; + +using Microsoft.AspNetCore.Mvc; + +namespace Framework.AutomationCore.RootServiceProviderContainer; + +public interface IRootServiceProviderContainer +{ + IServiceProvider RootServiceProvider { get; } + + ControllerEvaluator GetControllerEvaluator(UserCredential? userCredential = null) + where TController : ControllerBase => + this.RootServiceProvider.GetDefaultControllerEvaluator(userCredential); +} diff --git a/src/AutomationCore/Framework.AutomationCore/RootServiceProviderContainer/RootServiceProviderContainer.cs b/src/AutomationCore/Framework.AutomationCore/RootServiceProviderContainer/RootServiceProviderContainer.cs new file mode 100644 index 000000000..652eacd57 --- /dev/null +++ b/src/AutomationCore/Framework.AutomationCore/RootServiceProviderContainer/RootServiceProviderContainer.cs @@ -0,0 +1,16 @@ +using Anch.SecuritySystem; + +using Framework.AutomationCore.ServiceEnvironment; + +using Microsoft.AspNetCore.Mvc; + +namespace Framework.AutomationCore.RootServiceProviderContainer; + +public class RootServiceProviderContainer(IServiceProvider rootServiceProvider) : IRootServiceProviderContainer +{ + public IServiceProvider RootServiceProvider { get; } = rootServiceProvider; + + public virtual ControllerEvaluator GetControllerEvaluator(UserCredential? userCredential = null) + where TController : ControllerBase => + this.RootServiceProvider.GetDefaultControllerEvaluator(userCredential); +} diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/RootServiceProviderContainer/RootServiceProviderContainerExtensions.cs b/src/AutomationCore/Framework.AutomationCore/RootServiceProviderContainer/RootServiceProviderContainerExtensions.cs similarity index 52% rename from src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/RootServiceProviderContainer/RootServiceProviderContainerExtensions.cs rename to src/AutomationCore/Framework.AutomationCore/RootServiceProviderContainer/RootServiceProviderContainerExtensions.cs index f41948f98..6b2ea9c33 100644 --- a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/RootServiceProviderContainer/RootServiceProviderContainerExtensions.cs +++ b/src/AutomationCore/Framework.AutomationCore/RootServiceProviderContainer/RootServiceProviderContainerExtensions.cs @@ -1,10 +1,12 @@ using System.Linq.Expressions; -using Framework.AutomationCore.ServiceEnvironment; +using Framework.Application.FinancialYear; using Framework.AutomationCore.ServiceEnvironment.Services; using Framework.AutomationCore.Settings; using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; +//using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; + using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; @@ -15,20 +17,23 @@ public static class RootServiceProviderContainerExtensions { extension(IRootServiceProviderContainer rootServiceProviderContainer) { - public IDatabaseContext GetDatabaseContext() => rootServiceProviderContainer.RootServiceProvider.GetRequiredService(); + public AutomationFrameworkSettings AutomationFrameworkSettings => rootServiceProviderContainer.RootServiceProvider.GetRequiredService>().Value; + + public TimeProvider TimeProvider => rootServiceProviderContainer.RootServiceProvider.GetRequiredService(); - public AutomationFrameworkSettings GetAutomationFrameworkSettings() => rootServiceProviderContainer.RootServiceProvider.GetRequiredService>().Value; + public IFinancialYearService FinancialYearService => rootServiceProviderContainer.RootServiceProvider.GetRequiredService(); - public TimeProvider GetTimeProvider() => rootServiceProviderContainer.RootServiceProvider.GetRequiredService(); + public IDatabaseContext DatabaseContext => rootServiceProviderContainer.RootServiceProvider.GetRequiredService(); public void SetCurrentDateTime(DateTime newDateTime) => rootServiceProviderContainer.RootServiceProvider.GetRequiredService().SetCurrentDateTime(newDateTime); public TResult EvaluateController(Expression> func) where TController : ControllerBase => - rootServiceProviderContainer.RootServiceProvider.GetDefaultControllerEvaluator().Evaluate(func); + + rootServiceProviderContainer.GetControllerEvaluator().Evaluate(func); public void EvaluateController(Expression> action) where TController : ControllerBase => - rootServiceProviderContainer.RootServiceProvider.GetDefaultControllerEvaluator().Evaluate(action); + rootServiceProviderContainer.GetControllerEvaluator().Evaluate(action); } } diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/ServiceEnvironment/ControllerEvaluator.cs b/src/AutomationCore/Framework.AutomationCore/ServiceEnvironment/ControllerEvaluator.cs similarity index 98% rename from src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/ServiceEnvironment/ControllerEvaluator.cs rename to src/AutomationCore/Framework.AutomationCore/ServiceEnvironment/ControllerEvaluator.cs index 76f61dfc8..b1895ff8e 100644 --- a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/ServiceEnvironment/ControllerEvaluator.cs +++ b/src/AutomationCore/Framework.AutomationCore/ServiceEnvironment/ControllerEvaluator.cs @@ -25,7 +25,7 @@ public void Evaluate(Expression> actionExpr) => this.InternalEvaluateAsync(actionExpr, async c => { actionExpr.Compile().Invoke(c); - return default; + return null; }).GetAwaiter().GetResult(); public T Evaluate(Expression> funcExpr) @@ -39,7 +39,7 @@ public async Task EvaluateAsync(Expression> actionExpr) await this.InternalEvaluateAsync(actionExpr, async c => { await actionExpr.Compile().Invoke(c); - return default; + return null; }); public async Task EvaluateAsync(Expression>> funcExpr) => await this.InternalEvaluateAsync(funcExpr, funcExpr.Compile()); diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/ServiceEnvironment/ServiceProviderExtensions.cs b/src/AutomationCore/Framework.AutomationCore/ServiceEnvironment/ServiceProviderExtensions.cs similarity index 92% rename from src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/ServiceEnvironment/ServiceProviderExtensions.cs rename to src/AutomationCore/Framework.AutomationCore/ServiceEnvironment/ServiceProviderExtensions.cs index 50744997a..e19f039cb 100644 --- a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/ServiceEnvironment/ServiceProviderExtensions.cs +++ b/src/AutomationCore/Framework.AutomationCore/ServiceEnvironment/ServiceProviderExtensions.cs @@ -1,7 +1,6 @@ using System.Reflection; using Anch.Core; -using Anch.Core.Auth; using Anch.DependencyInjection; using Framework.Application.Jobs; @@ -12,13 +11,15 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using Anch.SecuritySystem; using Anch.SecuritySystem.Testing; using Anch.SecuritySystem.Testing.DependencyInjection; +using Framework.AutomationCore.Utils.DatabaseUtils; +using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; + namespace Framework.AutomationCore.ServiceEnvironment; public static class ServiceProviderExtensions @@ -72,7 +73,10 @@ public IServiceCollection AddIntegrationTests(Action() + return services.AddSingleton() + + + .AddSingleton() .ReplaceSingletonFrom() .AddScoped() @@ -81,8 +85,6 @@ public IServiceCollection AddIntegrationTests(Action)) - .Replace(ServiceDescriptor.KeyedSingleton(ICurrentUser.DefaultKey)) - .AddSecuritySystemTesting(b => b.SetEvaluator(typeof(BssTestingEvaluator<>)) .SetTestRootUserInfo(sp => sp.GetRequiredService>() .Pipe(options => new TestRootUserInfo(options.Value.IntegrationTestUserName)))); diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/ServiceEnvironment/Services/BssTestingEvaluator.cs b/src/AutomationCore/Framework.AutomationCore/ServiceEnvironment/Services/BssTestingEvaluator.cs similarity index 100% rename from src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/ServiceEnvironment/Services/BssTestingEvaluator.cs rename to src/AutomationCore/Framework.AutomationCore/ServiceEnvironment/Services/BssTestingEvaluator.cs diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/ServiceEnvironment/Services/IntegrationTestTimeProvider.cs b/src/AutomationCore/Framework.AutomationCore/ServiceEnvironment/Services/IntegrationTestTimeProvider.cs similarity index 100% rename from src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/ServiceEnvironment/Services/IntegrationTestTimeProvider.cs rename to src/AutomationCore/Framework.AutomationCore/ServiceEnvironment/Services/IntegrationTestTimeProvider.cs diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/ServiceEnvironment/TestWebApiCurrentMethodResolver.cs b/src/AutomationCore/Framework.AutomationCore/ServiceEnvironment/TestWebApiCurrentMethodResolver.cs similarity index 100% rename from src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/ServiceEnvironment/TestWebApiCurrentMethodResolver.cs rename to src/AutomationCore/Framework.AutomationCore/ServiceEnvironment/TestWebApiCurrentMethodResolver.cs diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/ServiceEnvironment/TestWebApiExceptionExpander.cs b/src/AutomationCore/Framework.AutomationCore/ServiceEnvironment/TestWebApiExceptionExpander.cs similarity index 100% rename from src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/ServiceEnvironment/TestWebApiExceptionExpander.cs rename to src/AutomationCore/Framework.AutomationCore/ServiceEnvironment/TestWebApiExceptionExpander.cs diff --git a/src/AutomationCore/Framework.AutomationCore/ServiceProviderPool/IServiceProviderPool.cs b/src/AutomationCore/Framework.AutomationCore/ServiceProviderPool/IServiceProviderPool.cs deleted file mode 100644 index bbdb7e2aa..000000000 --- a/src/AutomationCore/Framework.AutomationCore/ServiceProviderPool/IServiceProviderPool.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Framework.AutomationCore.ServiceProviderPool; - -public interface IServiceProviderPool -{ - IServiceProvider Get(); - void Release(IServiceProvider serviceProvider); -} diff --git a/src/AutomationCore/Framework.AutomationCore/ServiceProviderPool/ServiceProviderPool.cs b/src/AutomationCore/Framework.AutomationCore/ServiceProviderPool/ServiceProviderPool.cs deleted file mode 100644 index 36c40979a..000000000 --- a/src/AutomationCore/Framework.AutomationCore/ServiceProviderPool/ServiceProviderPool.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Collections.Concurrent; - -namespace Framework.AutomationCore.ServiceProviderPool; - -public class ServiceProviderPool : IServiceProviderPool -{ - private readonly Func createServiceProviderFunc; - private readonly ConcurrentBag providersCache = []; - private readonly SemaphoreSlim semaphore; - private readonly bool enableLimiter; - - public ServiceProviderPool(Func createServiceProviderFunc, bool parallelExecutionEnabled, bool disableLimiter) - { - this.enableLimiter = !disableLimiter; - if (this.enableLimiter) - { - this.semaphore = parallelExecutionEnabled - ? new SemaphoreSlim(System.Environment.ProcessorCount, System.Environment.ProcessorCount) - : new SemaphoreSlim(1, 1); - } - - this.createServiceProviderFunc = createServiceProviderFunc; - } - - public IServiceProvider Get() - { - if (this.enableLimiter) - { - this.semaphore.Wait(); - } - - try - { - return this.providersCache.TryTake(out var provider) ? provider : this.createServiceProviderFunc.Invoke(); - } - catch (Exception) - { - if (this.enableLimiter) - { - this.semaphore.Release(); - } - - throw; - } - - } - - public void Release(IServiceProvider serviceProvider) - { - this.providersCache.Add(serviceProvider); - if (this.enableLimiter) - { - this.semaphore.Release(); - } - } -} diff --git a/src/AutomationCore/Framework.AutomationCore/Settings/AutomationFrameworkSettings.cs b/src/AutomationCore/Framework.AutomationCore/Settings/AutomationFrameworkSettings.cs index 5804e0638..c923962ba 100644 --- a/src/AutomationCore/Framework.AutomationCore/Settings/AutomationFrameworkSettings.cs +++ b/src/AutomationCore/Framework.AutomationCore/Settings/AutomationFrameworkSettings.cs @@ -1,4 +1,4 @@ -using Framework.AutomationCore.Enums; +using Anch.Testing.Database; namespace Framework.AutomationCore.Settings; @@ -6,7 +6,7 @@ public class AutomationFrameworkSettings { public string IntegrationTestUserName { get; set; } = "IntegrationTestRootUser"; - public TestRunMode TestRunMode { get; set; } = TestRunMode.DefaultRunModeOnEmptyDatabase; + public DatabaseInitMode DatabaseInitMode { get; set; } = DatabaseInitMode.RebuildSnapshot; public bool UseLocalDb { get; set; } @@ -14,14 +14,12 @@ public class AutomationFrameworkSettings public string DatabaseCollation { get; set; } = ""; - public string TestRunServerRootFolder { get; set; } = default!; + public string TestRunServerRootFolder { get; set; } = null!; public string DbDataDirectory => Path.Combine(this.TestRunServerRootFolder, "data"); public string TempFolder => Path.Combine(this.TestRunServerRootFolder, "temp"); - public string ConnectionStringName { get; set; } = "DefaultConnection"; - public string[] SecondaryDatabases { get; set; } = []; public string[] LocalAdmins { get; set; } = []; diff --git a/src/AutomationCore/Framework.AutomationCore/TestingProvider/BssDatabaseFilePathExtractor.cs b/src/AutomationCore/Framework.AutomationCore/TestingProvider/BssDatabaseFilePathExtractor.cs new file mode 100644 index 000000000..65dd18f95 --- /dev/null +++ b/src/AutomationCore/Framework.AutomationCore/TestingProvider/BssDatabaseFilePathExtractor.cs @@ -0,0 +1,28 @@ +using System.Data.Common; + +using Anch.Testing.Database.ConnectionStringManagement; + +namespace Framework.AutomationCore.TestingProvider; + +public class BssDatabaseFilePathExtractor : IDatabaseFilePathExtractor +{ + public string Extract(TestDatabaseConnectionString connectionString) + { + throw new NotImplementedException(); + + var builder = new DbConnectionStringBuilder + { + ConnectionString = connectionString.Value + }; + + if (!builder.TryGetValue("Data Source", out var value)) + throw new InvalidOperationException("Data Source is missing."); + + var dataSource = value?.ToString(); + + if (string.IsNullOrWhiteSpace(dataSource)) + throw new InvalidOperationException("Data Source is empty."); + + return dataSource; + } +} diff --git a/src/AutomationCore/Framework.AutomationCore/TestingProvider/BssDatabaseTestingProvider.cs b/src/AutomationCore/Framework.AutomationCore/TestingProvider/BssDatabaseTestingProvider.cs new file mode 100644 index 000000000..70216cef4 --- /dev/null +++ b/src/AutomationCore/Framework.AutomationCore/TestingProvider/BssDatabaseTestingProvider.cs @@ -0,0 +1,13 @@ +using Anch.Testing.Database.ConnectionStringManagement; +using Anch.Testing.Database.DependencyInjection; + +using Microsoft.Extensions.DependencyInjection; + +namespace Framework.AutomationCore.TestingProvider; + +public class BssDatabaseTestingProvider : IDatabaseTestingProvider +{ + public void AddServices(IServiceCollection services) => + services.AddSingleton() + .AddSingleton(); +} diff --git a/src/AutomationCore/Framework.AutomationCore/TestingProvider/BssTestDatabaseConnectionStringBuilder.cs b/src/AutomationCore/Framework.AutomationCore/TestingProvider/BssTestDatabaseConnectionStringBuilder.cs new file mode 100644 index 000000000..13b26db56 --- /dev/null +++ b/src/AutomationCore/Framework.AutomationCore/TestingProvider/BssTestDatabaseConnectionStringBuilder.cs @@ -0,0 +1,32 @@ +using Anch.Testing.Database; +using Anch.Testing.Database.ConnectionStringManagement; + +namespace Framework.AutomationCore.TestingProvider; + +public class BssTestDatabaseConnectionStringBuilder(TestDatabaseSettings databaseSettings) : ITestDatabaseConnectionStringBuilder +{ + public TestDatabaseConnectionString AddPostfix(string postfix) + { + throw new NotImplementedException(); + + //var builder = new DbConnectionStringBuilder { ConnectionString = databaseSettings.DefaultConnectionString.Value }; + + //var dataSource = builder["Data Source"]?.ToString(); + + //if (string.IsNullOrWhiteSpace(dataSource)) + // throw new InvalidOperationException("Data Source is missing in connection string."); + + //var directory = Path.GetDirectoryName(dataSource); + //var fileName = Path.GetFileNameWithoutExtension(dataSource); + //var extension = Path.GetExtension(dataSource); + + //var newFileName = $"{fileName}{postfix}{extension}"; + //var newDataSource = directory is null + // ? newFileName + // : Path.Combine(directory, newFileName); + + //builder["Data Source"] = newDataSource; + + //return new TestDatabaseConnectionString(builder.ConnectionString); + } +} diff --git a/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/CoreDatabaseUtil.Helper.cs b/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/CoreDatabaseUtil.Helper.cs index 816d7220d..ba172d929 100644 --- a/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/CoreDatabaseUtil.Helper.cs +++ b/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/CoreDatabaseUtil.Helper.cs @@ -14,7 +14,7 @@ public static string CutInitialCatalog(string inputConnectionString) => private static string GetInitialCatalog(string connectionString) => InitialCatalogRegex.Matches(connectionString).First().Value; - private static Table GetTable(this Server server, string databaseName, string tableName) + private static Table? GetTable(this Server server, string databaseName, string tableName) { var database = server.GetDatabase(databaseName); @@ -40,8 +40,8 @@ private static void SetModeRestrictedUser(this Server server, string databaseNam } } - private static void SetModeMultiUser(this Server server, Database database) + private static void SetModeMultiUser(this Server server, Microsoft.SqlServer.Management.Smo.Database database) => ExecuteSql(server.ConnectionContext.SqlConnectionObject, $"ALTER DATABASE [{database.Name}] SET MULTI_USER"); - private static Database GetDatabase(this Server server, string name) => server.Databases.Contains(name) ? server.Databases[name] : null; + private static Microsoft.SqlServer.Management.Smo.Database? GetDatabase(this Server server, string name) => server.Databases.Contains(name) ? server.Databases[name] : null; } diff --git a/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/CoreDatabaseUtil.cs b/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/CoreDatabaseUtil.cs index 89e5e78f0..a13de3ee0 100644 --- a/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/CoreDatabaseUtil.cs +++ b/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/CoreDatabaseUtil.cs @@ -151,7 +151,7 @@ private static void Drop(Server server, string databaseName) } - public static void Drop(this Server server, Database database) + public static void Drop(this Server server, Microsoft.SqlServer.Management.Smo.Database database) { try { @@ -190,7 +190,7 @@ public static void Create(this IDatabaseContext databaseContext) private static void Create(Server server, IDatabaseItem database) { - var db = new Database(server, database.DatabaseName); + var db = new Microsoft.SqlServer.Management.Smo.Database(server, database.DatabaseName); if (!string.IsNullOrEmpty(database.DatabaseCollation)) { db.Collation = database.DatabaseCollation; @@ -201,24 +201,24 @@ private static void Create(Server server, IDatabaseItem database) var fileGroup = new FileGroup(db, "PRIMARY"); var dataFile = new DataFile( - fileGroup, - database.DatabaseName, - database.SourceDataPath) - { - Size = 5.5 * 1024.0, GrowthType = FileGrowthType.KB, Growth = 1.0 * 1024.0 - }; + fileGroup, + database.DatabaseName, + database.SourceDataPath) + { + Size = 5.5 * 1024.0, GrowthType = FileGrowthType.KB, Growth = 1.0 * 1024.0 + }; fileGroup.Files.Add(dataFile); db.FileGroups.Add(fileGroup); var logFile = new LogFile( - db, - database.DatabaseName + "_log", - database.SourceLogPath) - { - Size = 1.0 * 1024.0, GrowthType = FileGrowthType.Percent, Growth = 10.0 - }; + db, + database.DatabaseName + "_log", + database.SourceLogPath) + { + Size = 1.0 * 1024.0, GrowthType = FileGrowthType.Percent, Growth = 10.0 + }; db.LogFiles.Add(logFile); diff --git a/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/DatabaseContext.cs b/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/DatabaseContext.cs index aefdfb771..ac02fb009 100644 --- a/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/DatabaseContext.cs +++ b/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/DatabaseContext.cs @@ -2,9 +2,9 @@ using Framework.AutomationCore.Settings; using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; +using Framework.Database; using Microsoft.Data.SqlClient; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; using Microsoft.SqlServer.Management.Common; using Microsoft.SqlServer.Management.Smo; @@ -20,31 +20,26 @@ static DatabaseContext() => public DatabaseItem Main { get; } - private readonly Server server; - public Dictionary Secondary { get; } public DatabaseContext( - IConfiguration configuration, + IDefaultConnectionStringSource defaultConnectionStringSource, IOptions settings) - : this(configuration, settings.Value) + : this(defaultConnectionStringSource, settings.Value) { } - private DatabaseContext( - IConfiguration configuration, - AutomationFrameworkSettings settings) + private DatabaseContext(IDefaultConnectionStringSource defaultConnectionStringSource, AutomationFrameworkSettings settings) { - var connectionString = this.GetConnectionString(configuration, settings); + var actualConnectionString = GetConnectionString(defaultConnectionStringSource, settings); this.Main = new DatabaseItem( - connectionString, + actualConnectionString, settings.DatabaseCollation, settings.DbDataDirectory, null, settings.TestsParallelize); - if (settings.SecondaryDatabases != null) { this.Secondary = new Dictionary(); foreach (var database in settings.SecondaryDatabases) @@ -52,7 +47,7 @@ private DatabaseContext( this.Secondary.Add( database, new DatabaseItem( - connectionString, + actualConnectionString, settings.DatabaseCollation, settings.DbDataDirectory, database, @@ -60,37 +55,33 @@ private DatabaseContext( } } - this.server = new Server(new ServerConnection(new SqlConnection( - CoreDatabaseUtil.CutInitialCatalog(this.Main.ConnectionString)))); + this.Server = new Server(new ServerConnection(new SqlConnection( + CoreDatabaseUtil.CutInitialCatalog(this.Main.ConnectionString)))); } public Server Server { get { - this.server.Refresh(); - return this.server; + field.Refresh(); + return field; } } - private string GetConnectionString( - IConfiguration configuration, + private static string GetConnectionString( + IDefaultConnectionStringSource defaultConnectionStringSource, AutomationFrameworkSettings settings) { - var connectionString = configuration.GetConnectionString(settings.ConnectionStringName); - if (settings.UseLocalDb) { - connectionString = this.GetLocalDbConnectionString(connectionString, LocalDbInstanceName); + return GetLocalDbConnectionString(defaultConnectionStringSource.ConnectionString, LocalDbInstanceName); } - return connectionString; + return defaultConnectionStringSource.ConnectionString; } - private string GetLocalDbConnectionString(string connectionString, string instanceName) + private static string GetLocalDbConnectionString(string connectionString, string instanceName) => DataSourceRegex.Replace(connectionString, $"Data Source=(localdb)\\{instanceName}"); private static readonly Regex DataSourceRegex = new("Data Source=([^;]*)", RegexOptions.Compiled | RegexOptions.NonBacktracking); } - - diff --git a/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/DatabaseItem.cs b/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/DatabaseItem.cs index def25cdc1..78fccee19 100644 --- a/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/DatabaseItem.cs +++ b/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/DatabaseItem.cs @@ -19,8 +19,8 @@ public DatabaseItem( this.builder = new SqlConnectionStringBuilder(connectionString); initialCatalog ??= this.builder.InitialCatalog; this.DatabaseName = randomizeDatabaseName - ? $"{initialCatalog}{TextRandomizer.RandomString(5)}" - : initialCatalog; + ? $"{initialCatalog}{TextRandomizer.RandomString(5)}" + : initialCatalog; var fileName = $"{this.InstanceName}_{this.DatabaseName}_{TextRandomizer.RandomString(5)}"; @@ -40,8 +40,6 @@ public DatabaseItem( public string Password => this.builder.Password; - public bool IntegratedSecurity => this.builder.IntegratedSecurity; - public string ConnectionString => this.builder.ConnectionString; public string InstanceName => this.builder.DataSource.Split('\\').LastOrDefault(); diff --git a/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/TestDatabaseGenerator.cs b/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/TestDatabaseGenerator.cs index f17c511b3..b8e7c7cf4 100644 --- a/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/TestDatabaseGenerator.cs +++ b/src/AutomationCore/Framework.AutomationCore/Utils/DatabaseUtils/TestDatabaseGenerator.cs @@ -2,7 +2,6 @@ using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; using Microsoft.Extensions.Options; -using Microsoft.SqlServer.Management.Smo; namespace Framework.AutomationCore.Utils.DatabaseUtils; @@ -33,7 +32,7 @@ public virtual void DeleteLocalDb() } public virtual void DropAllDatabases() => - this.DatabaseContext.Server.Databases.Cast() + this.DatabaseContext.Server.Databases .Where(x => x.Name.Equals(this.DatabaseContext.Main.InitialCatalog)) .ToList() .ForEach(x => x.Drop()); diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/WebApi/IntegrationWebApiBase.cs b/src/AutomationCore/Framework.AutomationCore/WebApi/IntegrationWebApiBase.cs similarity index 81% rename from src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/WebApi/IntegrationWebApiBase.cs rename to src/AutomationCore/Framework.AutomationCore/WebApi/IntegrationWebApiBase.cs index f9b8bf7d7..8b0eee642 100644 --- a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/WebApi/IntegrationWebApiBase.cs +++ b/src/AutomationCore/Framework.AutomationCore/WebApi/IntegrationWebApiBase.cs @@ -9,5 +9,5 @@ public abstract class IntegrationWebApiBase(IServiceProvider rootServiceProvider protected abstract string IntegrationUserName { get; } public override ControllerEvaluator GetControllerEvaluator(UserCredential? userCredential = null) => - base.GetControllerEvaluator(userCredential ?? this.IntegrationUserName); + base.GetControllerEvaluator(userCredential ?? this.IntegrationUserName); } diff --git a/src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/WebApi/WebApiBase.cs b/src/AutomationCore/Framework.AutomationCore/WebApi/WebApiBase.cs similarity index 100% rename from src/AutomationCore/Framework.AutomationCore.ServiceEnvironment/WebApi/WebApiBase.cs rename to src/AutomationCore/Framework.AutomationCore/WebApi/WebApiBase.cs diff --git a/src/BLL/Framework.BLL.Abstractions/Extensions/TypeExtensions.cs b/src/BLL/Framework.BLL.Abstractions/Extensions/TypeExtensions.cs index 70fc9851c..741e8fc88 100644 --- a/src/BLL/Framework.BLL.Abstractions/Extensions/TypeExtensions.cs +++ b/src/BLL/Framework.BLL.Abstractions/Extensions/TypeExtensions.cs @@ -2,13 +2,7 @@ public static class TypeExtensions { - internal static bool SafeEquals(this Type t1, Type t2) - { - return t1.IsGenericTypeDefinition == t2.IsGenericTypeDefinition && t1 == t2; - } + internal static bool SafeEquals(this Type t1, Type t2) => t1.IsGenericTypeDefinition == t2.IsGenericTypeDefinition && t1 == t2; - internal static bool SafeIsAssignableFrom(this Type t1, Type t2) - { - return t1.SafeEquals(t2) || t1.IsAssignableFrom(t2); - } + internal static bool SafeIsAssignableFrom(this Type t1, Type t2) => t1.SafeEquals(t2) || t1.IsAssignableFrom(t2); } diff --git a/src/BLL/Framework.BLL.Domain/Extensions/EnumerableExtensions.cs b/src/BLL/Framework.BLL.Domain/Extensions/EnumerableExtensions.cs index 5cc9ed7e8..1685921a1 100644 --- a/src/BLL/Framework.BLL.Domain/Extensions/EnumerableExtensions.cs +++ b/src/BLL/Framework.BLL.Domain/Extensions/EnumerableExtensions.cs @@ -37,7 +37,7 @@ private static Func TryGetNotFoundByNameExceptionFactory(str { if (name == null) throw new ArgumentNullException(nameof(name)); - return raiseIfNotFound ? () => GetNotFoundException(name, nameof(name)) : default(Func); + return raiseIfNotFound ? () => GetNotFoundException(name, nameof(name)) : null; } private static Exception GetNotFoundException(string identity, string identityName) => throw new Exception($"{typeof (TSource).Name} with {identityName} \"{identity}\" not found"); diff --git a/src/BssFramework.slnx b/src/BssFramework.slnx index 16eb0b238..7519c41e2 100644 --- a/src/BssFramework.slnx +++ b/src/BssFramework.slnx @@ -8,8 +8,7 @@ - - + @@ -184,7 +183,6 @@ - diff --git a/src/CodeGeneration/Framework.CodeGeneration.BLLGenerator/Configuration/DefaultValidatorGenerator.cs b/src/CodeGeneration/Framework.CodeGeneration.BLLGenerator/Configuration/DefaultValidatorGenerator.cs index c1493bb23..7448b1d25 100644 --- a/src/CodeGeneration/Framework.CodeGeneration.BLLGenerator/Configuration/DefaultValidatorGenerator.cs +++ b/src/CodeGeneration/Framework.CodeGeneration.BLLGenerator/Configuration/DefaultValidatorGenerator.cs @@ -146,10 +146,7 @@ protected virtual IEnumerable GetPropertyValidators(PropertyI } } - protected virtual bool HasDeepValidation(PropertyInfo property) - { - return property.HasDeepValidation(); - } + protected virtual bool HasDeepValidation(PropertyInfo property) => property.HasDeepValidation(); protected virtual bool IsManyPropertyDynamicClassAttribute(ClassValidatorAttribute attribute) { diff --git a/src/CodeGeneration/Framework.CodeGeneration.DTOGenerator/FileFactory/BaseCodeDomHelper.cs b/src/CodeGeneration/Framework.CodeGeneration.DTOGenerator/FileFactory/BaseCodeDomHelper.cs index ee0aaac6d..0d66eae50 100644 --- a/src/CodeGeneration/Framework.CodeGeneration.DTOGenerator/FileFactory/BaseCodeDomHelper.cs +++ b/src/CodeGeneration/Framework.CodeGeneration.DTOGenerator/FileFactory/BaseCodeDomHelper.cs @@ -56,7 +56,7 @@ public static CodeMemberMethod GenerateIdConstructor(this IFileF public static IEnumerable GenerateStrictConstructors(this IDTOSource source) where TConfiguration : class, IDTOGeneratorConfiguration => source.GetActualStrictConstructorFileTypes() - .Concat([default(MainDTOFileType)]) + .Concat([null]) .Windowed2((fileType, baseFileType) => new[] { false, true}.Select(withoutMappingParameter => source.GenerateStrictConstructor(fileType, baseFileType, withoutMappingParameter))) .SelectMany(); diff --git a/src/Database/Framework.Database.Metadata/MetadataReader.cs b/src/Database/Framework.Database.Metadata/MetadataReader.cs index 6aa75179f..b4e2e1664 100644 --- a/src/Database/Framework.Database.Metadata/MetadataReader.cs +++ b/src/Database/Framework.Database.Metadata/MetadataReader.cs @@ -77,7 +77,7 @@ public static class MetadataReader return null; } var result = f.FieldType.IsDomainType(d.AssemblyMetadata.PersistentDomainObjectBaseType) - ? new ReferenceTypeFieldMetadata(f.Name, f.FieldType, f.GetAttributes(d.DomainType).Cast(), d) : null; + ? new ReferenceTypeFieldMetadata(f.Name, f.FieldType, f.GetAttributes(d.DomainType), d) : null; return result; }; diff --git a/src/Database/Framework.Database.NHibernate.DBGenerator.Tests/Framework.Database.NHibernate.DBGenerator.Tests.csproj b/src/Database/Framework.Database.NHibernate.DBGenerator.Tests/Framework.Database.NHibernate.DBGenerator.Tests.csproj index aed4ece68..bd384e3d7 100644 --- a/src/Database/Framework.Database.NHibernate.DBGenerator.Tests/Framework.Database.NHibernate.DBGenerator.Tests.csproj +++ b/src/Database/Framework.Database.NHibernate.DBGenerator.Tests/Framework.Database.NHibernate.DBGenerator.Tests.csproj @@ -7,7 +7,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Database/Framework.Database.NHibernate.DBGenerator/AuditDBGenerator/AuditDatabaseScriptGenerator.cs b/src/Database/Framework.Database.NHibernate.DBGenerator/AuditDBGenerator/AuditDatabaseScriptGenerator.cs index 9a3ba23a2..3b37a43a5 100644 --- a/src/Database/Framework.Database.NHibernate.DBGenerator/AuditDBGenerator/AuditDatabaseScriptGenerator.cs +++ b/src/Database/Framework.Database.NHibernate.DBGenerator/AuditDBGenerator/AuditDatabaseScriptGenerator.cs @@ -279,7 +279,7 @@ private static IEnumerable CreateForegnKey(AuditTableGenerateContext con .FirstOrDefault(z => string.Equals($"{database.Name}.{z.Schema}.{z.Name}", fqn, StringComparison.InvariantCultureIgnoreCase) || string.Equals($"{z.Schema}.{z.Name}", fqn, StringComparison.InvariantCultureIgnoreCase)); - bool create = true; + var create = true; if (table != null) { @@ -332,7 +332,7 @@ private IEnumerable GetIterateScripts(DatabaseMetadata databaseMetadata, { foreach (var generator in this.IterateGenerators(cfg, dialect)) { - string key = generator.GeneratorKey(); + var key = generator.GeneratorKey(); if (!databaseMetadata.IsSequence(key) && !databaseMetadata.IsTable(key)) { return generator.SqlCreateStrings(dialect); @@ -356,8 +356,8 @@ private IEnumerable IterateGenerators(Configurat { var generators = new Dictionary(); var properties = configuration.Properties; - string defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null); - string defaultSchema = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null); + var defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null); + var defaultSchema = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null); foreach (var pc in configuration.ClassMappings) { diff --git a/src/Database/Framework.Database.NHibernate.DBGenerator/AuditDBGenerator/AuditSqlScriptGenerator.cs b/src/Database/Framework.Database.NHibernate.DBGenerator/AuditDBGenerator/AuditSqlScriptGenerator.cs index a1158e8fb..3886c1159 100644 --- a/src/Database/Framework.Database.NHibernate.DBGenerator/AuditDBGenerator/AuditSqlScriptGenerator.cs +++ b/src/Database/Framework.Database.NHibernate.DBGenerator/AuditDBGenerator/AuditSqlScriptGenerator.cs @@ -29,7 +29,7 @@ public string[] GenerateCreateScripts(AuditTableGenerateContext context) .Append(' ') .Append(context.GetQualifiedTableName()).Append(" ("); - bool identityColumn = table.IdentifierValue != null && table.IdentifierValue.IsIdentityColumn(dialect); + var identityColumn = table.IdentifierValue != null && table.IdentifierValue.IsIdentityColumn(dialect); // try to find out the name of the pk to create it as identity if the // identitygenerator is used @@ -114,14 +114,14 @@ public string[] GenerateCreateScripts(AuditTableGenerateContext context) buf.Append(StringHelper.CommaSpace).Append(table.PrimaryKey.SqlConstraintString(dialect, defaultSchema)); } - foreach (UniqueKey uk in table.UniqueKeyIterator) + foreach (var uk in table.UniqueKeyIterator) { buf.Append(',').Append(uk.SqlConstraintString(dialect)); } if (dialect.SupportsTableCheck) { - foreach (string checkConstraint in table.CheckConstraintsIterator) + foreach (var checkConstraint in table.CheckConstraintsIterator) { buf.Append(", check (").Append(checkConstraint).Append(") "); } diff --git a/src/Database/Framework.Database.NHibernate.DBGenerator/AuditDBGenerator/AuditTableGenerateContext.cs b/src/Database/Framework.Database.NHibernate.DBGenerator/AuditDBGenerator/AuditTableGenerateContext.cs index 68685cff1..3e1dcb778 100644 --- a/src/Database/Framework.Database.NHibernate.DBGenerator/AuditDBGenerator/AuditTableGenerateContext.cs +++ b/src/Database/Framework.Database.NHibernate.DBGenerator/AuditDBGenerator/AuditTableGenerateContext.cs @@ -45,9 +45,9 @@ public string GetQualifiedTableName() { return "( " + this.Table.Subselect + " )"; } - string quotedName = this.GetQuotedName(this.Table.Name); - string usedSchema = this.Table.Schema == null ? this.DefaultSchema : this.GetQuotedName(this.Table.Schema); - string usedCatalog = this.Table.Catalog ?? this.DefaultCatalog; + var quotedName = this.GetQuotedName(this.Table.Name); + var usedSchema = this.Table.Schema == null ? this.DefaultSchema : this.GetQuotedName(this.Table.Schema); + var usedCatalog = this.Table.Catalog ?? this.DefaultCatalog; return this.Dialect.Qualify(usedCatalog, usedSchema, quotedName); } diff --git a/src/Database/Framework.Database.NHibernate.DBGenerator/ScriptGeneratorBuilder/Impl/MigrationDBScriptGeneratorBuilder.cs b/src/Database/Framework.Database.NHibernate.DBGenerator/ScriptGeneratorBuilder/Impl/MigrationDBScriptGeneratorBuilder.cs index 9ebc7454b..63ef247b2 100644 --- a/src/Database/Framework.Database.NHibernate.DBGenerator/ScriptGeneratorBuilder/Impl/MigrationDBScriptGeneratorBuilder.cs +++ b/src/Database/Framework.Database.NHibernate.DBGenerator/ScriptGeneratorBuilder/Impl/MigrationDBScriptGeneratorBuilder.cs @@ -134,19 +134,16 @@ private void Execute(string commandText, IDatabaseScriptGeneratorContext context { try { - using (var connection = context.SqlDatabaseFactory.Server.ConnectionContext.SqlConnectionObject) - { - connection.Open(); - ////var nextCommandText = commandText.Replace("GO", string.Empty); - var replaceTargetDBText = commandText.Replace("$Database", context.DatabaseName.Name); - - context.SqlDatabaseFactory.Server.ConnectionContext.ExecuteNonQuery(replaceTargetDBText); + using var connection = context.SqlDatabaseFactory.Server.ConnectionContext.SqlConnectionObject; + connection.Open(); + ////var nextCommandText = commandText.Replace("GO", string.Empty); + var replaceTargetDBText = commandText.Replace("$Database", context.DatabaseName.Name); - ////var command = new SqlCommand(replaceTargetDBText, connection); - ////command.CommandType = CommandType.Text; - ////command.ExecuteNonQuery(); - } + context.SqlDatabaseFactory.Server.ConnectionContext.ExecuteNonQuery(replaceTargetDBText); + ////var command = new SqlCommand(replaceTargetDBText, connection); + ////command.CommandType = CommandType.Text; + ////command.ExecuteNonQuery(); } catch (Exception e) { @@ -157,20 +154,18 @@ private void Execute(string commandText, IDatabaseScriptGeneratorContext context private List GetExecutedMigrationScripts(IDatabaseScriptGeneratorContext context) { var result = new List(); - using (var connection = context.SqlDatabaseFactory.Server.ConnectionContext.SqlConnectionObject) + using var connection = context.SqlDatabaseFactory.Server.ConnectionContext.SqlConnectionObject; + connection.Open(); + var cmd = $"select name, scheme, version from {context.DatabaseName}.[{this.tableName}]"; + var command = new Microsoft.Data.SqlClient.SqlCommand(cmd, connection); + var sqlResult = command.ExecuteReader(); + + while (sqlResult.Read()) { - connection.Open(); - var cmd = $"select name, scheme, version from {context.DatabaseName}.[{this.tableName}]"; - var command = new Microsoft.Data.SqlClient.SqlCommand(cmd, connection); - var sqlResult = command.ExecuteReader(); - - while (sqlResult.Read()) - { - result.Add(new MigrationDbScriptHeader( - sqlResult.GetString(0), - sqlResult.GetString(1), - sqlResult.GetString(2))); - } + result.Add(new MigrationDbScriptHeader( + sqlResult.GetString(0), + sqlResult.GetString(1), + sqlResult.GetString(2))); } return result; diff --git a/src/Database/Framework.Database.NHibernate.Runtime/Audit/AuditInterceptor.cs b/src/Database/Framework.Database.NHibernate.Runtime/Audit/AuditInterceptor.cs index 995cc8f94..0c2901861 100644 --- a/src/Database/Framework.Database.NHibernate.Runtime/Audit/AuditInterceptor.cs +++ b/src/Database/Framework.Database.NHibernate.Runtime/Audit/AuditInterceptor.cs @@ -15,7 +15,7 @@ internal sealed class AuditInterceptor(IEnumerable createAuditPr public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, IType[] types) { - bool result = false; + var result = false; if (entity is IAuditObject) { result = @@ -29,12 +29,12 @@ public override bool OnFlushDirty(object entity, object id, object[] currentStat public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types) { - bool result = false; + var result = false; if (entity is IAuditObject) { var domainObjectDescription = AuditPropertiesSetter.DomainObjectDescription.Get(entity.GetType(), propertyNames); - bool createSetterRes = this.createSetter.SetAuditFields(domainObjectDescription, ref state); - bool modifySetterRes = this.modifySetter.SetAuditFields(domainObjectDescription, ref state); + var createSetterRes = this.createSetter.SetAuditFields(domainObjectDescription, ref state); + var modifySetterRes = this.modifySetter.SetAuditFields(domainObjectDescription, ref state); result = createSetterRes | modifySetterRes; } diff --git a/src/Database/Framework.Database.NHibernate.Runtime/Audit/AuditPropertiesSetter.cs b/src/Database/Framework.Database.NHibernate.Runtime/Audit/AuditPropertiesSetter.cs index ea2979505..b80635bef 100644 --- a/src/Database/Framework.Database.NHibernate.Runtime/Audit/AuditPropertiesSetter.cs +++ b/src/Database/Framework.Database.NHibernate.Runtime/Audit/AuditPropertiesSetter.cs @@ -62,7 +62,7 @@ private static Func GetSetAuditAction getAuditValue = null; - string domainObjectPropertyName = auditProperty.PropertyExpr.GetMemberName(); + var domainObjectPropertyName = auditProperty.PropertyExpr.GetMemberName(); if (!string.IsNullOrEmpty(domainObjectPropertyName)) { var property = typeof(TDomainObject).GetProperty(domainObjectPropertyName, true); @@ -72,7 +72,7 @@ private static Func GetSetAuditAction { - bool result = false; + var result = false; if (propertyIndex.HasValue) { var auditValue = (getAuditValue != null) ? getAuditValue.Invoke() : default(TProperty); @@ -92,7 +92,7 @@ private static Func GetSetAuditAction GetMapping(PrimitiveTypeFieldMetadata fi var isNullable = !(field.IsVersion && new[] { typeof(int), typeof(long) }.Contains(field.Type) || isPrimaryKey); - string defaultConstraint = field.IsVersion && new[] { typeof(int), typeof(long) }.Contains(field.Type) ? "0" : null; + var defaultConstraint = field.IsVersion && new[] { typeof(int), typeof(long) }.Contains(field.Type) ? "0" : null; yield return new SqlFieldMappingInfo( field.Type.ToDataType(field.Attributes), diff --git a/src/Database/Framework.Tracking.Tests/Framework.Tracking.Tests.csproj b/src/Database/Framework.Tracking.Tests/Framework.Tracking.Tests.csproj index 5590b0e2f..4d40750b7 100644 --- a/src/Database/Framework.Tracking.Tests/Framework.Tracking.Tests.csproj +++ b/src/Database/Framework.Tracking.Tests/Framework.Tracking.Tests.csproj @@ -7,7 +7,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 5baac85f3..1907b7573 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -36,7 +36,7 @@ false true - 1591, CS9107 + 1591, CS9107, CS9124, xUnit1041 true false diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props index 9dfb2dd3a..c8a7bae0e 100644 --- a/src/Directory.Packages.props +++ b/src/Directory.Packages.props @@ -6,10 +6,9 @@ [1.6.2] - - - - + + + @@ -36,7 +35,10 @@ - + + + + @@ -64,13 +66,14 @@ + - + diff --git a/src/Framework.Core/CoreEnumerableExtensions.cs b/src/Framework.Core/CoreEnumerableExtensions.cs index cd1a34fe4..9ac8bb971 100644 --- a/src/Framework.Core/CoreEnumerableExtensions.cs +++ b/src/Framework.Core/CoreEnumerableExtensions.cs @@ -58,21 +58,17 @@ public static void Merge( public static bool SequenceEqual(this IEnumerable first, IEnumerable second, Func compareFunc) { - using (var enumerator1 = first.GetEnumerator()) + using var enumerator1 = first.GetEnumerator(); + using var enumerator2 = second.GetEnumerator(); + while (enumerator1.MoveNext()) { - using (var enumerator2 = second.GetEnumerator()) - { - while (enumerator1.MoveNext()) - { - if (!enumerator2.MoveNext() || !compareFunc(enumerator1.Current, enumerator2.Current)) - return false; - } - - if (enumerator2.MoveNext()) - return false; - } + if (!enumerator2.MoveNext() || !compareFunc(enumerator1.Current, enumerator2.Current)) + return false; } + if (enumerator2.MoveNext()) + return false; + return true; } @@ -97,24 +93,20 @@ public static IEnumerable IfEmpty(this IEnumerable source, Func(this IEnumerable source, Func func) if (source == null) throw new ArgumentNullException(nameof(source)); if (func == null) throw new ArgumentNullException(nameof(func)); - using (var enumerator = source.GetEnumerator()) - { - return enumerator.MoveNext() ? enumerator.Current : func(); - } + using var enumerator = source.GetEnumerator(); + return enumerator.MoveNext() ? enumerator.Current : func(); } public static void Override(this ICollection source, IEnumerable newItems) @@ -169,15 +159,13 @@ public static TSource First(this IEnumerable source, Func> Split(this IEnumerable< if (source == null) throw new ArgumentNullException(nameof(source)); if (size < 1) throw new ArgumentException("count"); - using (var enumerator = source.GetEnumerator()) + using var enumerator = source.GetEnumerator(); + while (enumerator.MoveNext()) { - while (enumerator.MoveNext()) - { - yield return enumerator.InnerSplit(size).ToList(); - } + yield return enumerator.InnerSplit(size).ToList(); } } @@ -406,31 +392,29 @@ public static IEnumerable Skip(this IEnumerable source, T expectedEleme if (source == null) throw new ArgumentNullException(nameof(source)); if (equalityComparer == null) throw new ArgumentNullException(nameof(equalityComparer)); - using (var enumerator = source.GetEnumerator()) + using var enumerator = source.GetEnumerator(); + if (enumerator.MoveNext()) { - if (enumerator.MoveNext()) + if (!equalityComparer.Equals(enumerator.Current, expectedElement)) { - if (!equalityComparer.Equals(enumerator.Current, expectedElement)) + if (raiseIfNotEquals) { - if (raiseIfNotEquals) - { - throw new ArgumentException("Unexpected first element", nameof(source)); - } - - yield return enumerator.Current; + throw new ArgumentException("Unexpected first element", nameof(source)); } - while (enumerator.MoveNext()) - { - yield return enumerator.Current; - } + yield return enumerator.Current; } - else + + while (enumerator.MoveNext()) { - if (raiseIfNotEquals) - { - throw new ArgumentException("EmptyCollection", nameof(source)); - } + yield return enumerator.Current; + } + } + else + { + if (raiseIfNotEquals) + { + throw new ArgumentException("EmptyCollection", nameof(source)); } } } diff --git a/src/Framework.Core/CoreStringExtensions.cs b/src/Framework.Core/CoreStringExtensions.cs index 1e92c8fb2..56010e2ea 100644 --- a/src/Framework.Core/CoreStringExtensions.cs +++ b/src/Framework.Core/CoreStringExtensions.cs @@ -156,7 +156,7 @@ public static IEnumerable GetChartWhile(this string source, char stopChar) [Obsolete("v10 This method will be protected in future")] public static IEnumerable GetCharsAfter(this string source, char afterChar) { - bool isReturn = false; + var isReturn = false; foreach (var s in source) { if (isReturn) diff --git a/src/Framework.Core/CoreTypeExtensions.cs b/src/Framework.Core/CoreTypeExtensions.cs index 8b4ba7ee2..3b6169ea6 100644 --- a/src/Framework.Core/CoreTypeExtensions.cs +++ b/src/Framework.Core/CoreTypeExtensions.cs @@ -235,7 +235,7 @@ public static Func WithLock(this Func func, object? b if (type == null) throw new ArgumentNullException(nameof(type)); if (memberName == null) throw new ArgumentNullException(nameof(memberName)); - return type.GetMemberType(memberName, raiseIfNotFound ? () => new Exception($"Member \"{memberName}\" not found in type \"{type.Name}\"") : default(Func)); + return type.GetMemberType(memberName, raiseIfNotFound ? () => new Exception($"Member \"{memberName}\" not found in type \"{type.Name}\"") : null); } public static Type? GetMemberType(this Type type, string memberName, Func? raiseIfNotFoundException) @@ -277,7 +277,7 @@ public static Func WithLock(this Func func, object? b if (propertyName == null) throw new ArgumentNullException(nameof(propertyName)); return type.GetProperty(propertyName, stringComparison, raiseIfNotFound ? () => new Exception( - $"Property \"{propertyName}\" not found in type \"{type.Name}\"") : default(Func)); + $"Property \"{propertyName}\" not found in type \"{type.Name}\"") : null); } public static PropertyInfo? GetProperty(this Type type, string propertyName, StringComparison stringComparison, Func? raiseIfNotFoundException) @@ -309,7 +309,7 @@ where typeof(T).IsAssignableFrom(prop.PropertyType) if (type == null) throw new ArgumentNullException(nameof(type)); if (propertyName == null) throw new ArgumentNullException(nameof(propertyName)); - return type.GetProperty(propertyName, raiseIfNotFound ? () => new Exception($"Property \"{propertyName}\" not found in type \"{type.Name}\"") : default(Func)); + return type.GetProperty(propertyName, raiseIfNotFound ? () => new Exception($"Property \"{propertyName}\" not found in type \"{type.Name}\"") : null); } public static PropertyInfo? GetProperty(this Type type, string propertyName, Func? raiseIfNotFoundException) @@ -343,7 +343,7 @@ where typeof(T).IsAssignableFrom(prop.PropertyType) if (type == null) throw new ArgumentNullException(nameof(type)); if (methodName == null) throw new ArgumentNullException(nameof(methodName)); - return type.GetMethod(methodName, bindingFlags, raiseIfNotFound ? () => new Exception($"Method \"{methodName}\" not found") : default(Func)); + return type.GetMethod(methodName, bindingFlags, raiseIfNotFound ? () => new Exception($"Method \"{methodName}\" not found") : null); } public static MethodInfo? GetMethod(this Type type, string methodName, BindingFlags bindingFlags, Func? raiseIfNotFoundException) @@ -475,22 +475,20 @@ public static IEnumerable Windowed2(this IEnumerable< if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); - using (var enumerator = source.GetEnumerator()) + using var enumerator = source.GetEnumerator(); + if (enumerator.MoveNext()) { + var prev = enumerator.Current; + if (enumerator.MoveNext()) { - var prev = enumerator.Current; - - if (enumerator.MoveNext()) - { - var next = enumerator.Current; + var next = enumerator.Current; - yield return selector(prev, next); + yield return selector(prev, next); - while (enumerator.MoveNext()) - { - yield return selector(next, next = enumerator.Current); - } + while (enumerator.MoveNext()) + { + yield return selector(next, next = enumerator.Current); } } } @@ -509,7 +507,7 @@ public static IEnumerable Windowed2(this IEnumerable< if (type == null) throw new ArgumentNullException(nameof(type)); if (methodName == null) throw new ArgumentNullException(nameof(methodName)); - return type.GetMethod(methodName, raiseIfNotFound ? () => new Exception($"Method \"{methodName}\" not found") : default(Func)); + return type.GetMethod(methodName, raiseIfNotFound ? () => new Exception($"Method \"{methodName}\" not found") : null); } public static MethodInfo? GetMethod(this Type type, string methodName, Func? raiseIfNotFoundException) diff --git a/src/Framework.Core/ExceptionEvaluator.cs b/src/Framework.Core/ExceptionEvaluator.cs index 8182dedea..b0cb13579 100644 --- a/src/Framework.Core/ExceptionEvaluator.cs +++ b/src/Framework.Core/ExceptionEvaluator.cs @@ -9,10 +9,8 @@ public static TResult Evaluate(this IEnumerable sourc if (selector == null) throw new ArgumentNullException(nameof(selector)); if (getAggregateException == null) throw new ArgumentNullException(nameof(getAggregateException)); - using (var enumerator = source.GetEnumerator()) - { - return enumerator.Evaluate(selector, [], getAggregateException); - } + using var enumerator = source.GetEnumerator(); + return enumerator.Evaluate(selector, [], getAggregateException); } private static TResult Evaluate(this IEnumerator source, Func selector, IEnumerable exceptions, Func, Exception> getAggregateException) diff --git a/src/Framework.Core/Helpers/DataContractSerializerHelper.cs b/src/Framework.Core/Helpers/DataContractSerializerHelper.cs index 68b2808b6..04d5a8b83 100644 --- a/src/Framework.Core/Helpers/DataContractSerializerHelper.cs +++ b/src/Framework.Core/Helpers/DataContractSerializerHelper.cs @@ -12,11 +12,9 @@ public static T Deserialize(string source) { var serializer = new DataContractSerializer(typeof(T)); - using (var textReader = new StringReader (source)) - using (var xmlReader = new XmlTextReader(textReader)) - { - return (T)serializer.ReadObject(xmlReader); - } + using var textReader = new StringReader (source); + using var xmlReader = new XmlTextReader(textReader); + return (T)serializer.ReadObject(xmlReader); } public static string Serialize(T source, Encoding encoding = null) @@ -24,15 +22,13 @@ public static string Serialize(T source, Encoding encoding = null) var serializer = new DataContractSerializer(typeof(T) == typeof(object) ? source.GetType() : typeof(T)); var sb = new StringBuilder(); - using (var stringWriter = new EncodingStringWriter(sb, encoding)) - using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true, Encoding = encoding ?? Encoding.Unicode })) - { - serializer.WriteObject(xmlWriter, source); + using var stringWriter = new EncodingStringWriter(sb, encoding); + using var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true, Encoding = encoding ?? Encoding.Unicode }); + serializer.WriteObject(xmlWriter, source); - xmlWriter.Flush(); + xmlWriter.Flush(); - return sb.ToString(); - } + return sb.ToString(); } @@ -40,31 +36,25 @@ public static T XmlClone(this T source) { var serializer = new DataContractSerializer(typeof(T)); - using (var stream = new MemoryStream()) - { - serializer.WriteObject(stream, source); + using var stream = new MemoryStream(); + serializer.WriteObject(stream, source); - stream.Position = 0; + stream.Position = 0; - return (T)serializer.ReadObject(stream); - } + return (T)serializer.ReadObject(stream); } public static bool XmlEquals(this T source, T other) { var serializer = new DataContractSerializer(typeof(T)); - using (var stream1 = new MemoryStream()) - { - serializer.WriteObject(stream1, source); + using var stream1 = new MemoryStream(); + serializer.WriteObject(stream1, source); - using (var stream2 = new MemoryStream()) - { - serializer.WriteObject(stream2, other); + using var stream2 = new MemoryStream(); + serializer.WriteObject(stream2, other); - return stream1.ToArray().SequenceEqual(stream2.ToArray()); - } - } + return stream1.ToArray().SequenceEqual(stream2.ToArray()); } diff --git a/src/Framework.Core/Serialization/Base85Convert.cs b/src/Framework.Core/Serialization/Base85Convert.cs index 2d77dd67f..862bd99e0 100644 --- a/src/Framework.Core/Serialization/Base85Convert.cs +++ b/src/Framework.Core/Serialization/Base85Convert.cs @@ -20,12 +20,12 @@ public static string Encode(byte[] bytes) throw new ArgumentNullException(nameof(bytes)); // preallocate a StringBuilder with enough room to store the encoded bytes - StringBuilder sb = new StringBuilder(bytes.Length * 5 / 4); + var sb = new StringBuilder(bytes.Length * 5 / 4); // walk the bytes - int count = 0; + var count = 0; uint value = 0; - foreach (byte b in bytes) + foreach (var b in bytes) { // build a 32-bit value from the bytes value |= ((uint)b) << (24 - (count * 8)); @@ -61,77 +61,76 @@ public static byte[] Decode(string encoded) throw new ArgumentNullException(nameof(encoded)); // preallocate a memory stream with enough capacity to hold the decoded data - using (MemoryStream stream = new MemoryStream(encoded.Length * 4 / 5)) + using var stream = new MemoryStream(encoded.Length * 4 / 5); + + // walk the input string + var count = 0; + uint value = 0; + foreach (var ch in encoded) { - // walk the input string - int count = 0; - uint value = 0; - foreach (char ch in encoded) + if (ch == 'z' && count == 0) + { + // handle "z" block specially + DecodeValue(stream, value, 0); + } + else if (ch < CFirstCharacter || ch > CLastCharacter) + { + throw new FormatException($"Invalid character '{ch}' in Ascii85 block."); + } + else { - if (ch == 'z' && count == 0) + // build a 32-bit value from the input characters + try { - // handle "z" block specially - DecodeValue(stream, value, 0); + checked { value += (uint)(SPowersOf85[count] * (ch - CFirstCharacter)); } } - else if (ch < CFirstCharacter || ch > CLastCharacter) + catch (OverflowException ex) { - throw new FormatException($"Invalid character '{ch}' in Ascii85 block."); + throw new FormatException("The current group of characters decodes to a value greater than UInt32.MaxValue.", ex); } - else + + count++; + + // every five characters, convert the characters into the equivalent byte array + if (count == 5) { - // build a 32-bit value from the input characters - try - { - checked { value += (uint)(SPowersOf85[count] * (ch - CFirstCharacter)); } - } - catch (OverflowException ex) - { - throw new FormatException("The current group of characters decodes to a value greater than UInt32.MaxValue.", ex); - } - - count++; - - // every five characters, convert the characters into the equivalent byte array - if (count == 5) - { - DecodeValue(stream, value, 0); - count = 0; - value = 0; - } + DecodeValue(stream, value, 0); + count = 0; + value = 0; } } + } - if (count == 1) - { - throw new FormatException("The final Ascii85 block must contain more than one character."); - } - else if (count > 1) + if (count == 1) + { + throw new FormatException("The final Ascii85 block must contain more than one character."); + } + else if (count > 1) + { + // decode any remaining characters + for (var padding = count; padding < 5; padding++) { - // decode any remaining characters - for (int padding = count; padding < 5; padding++) + try + { + checked { value += 84 * SPowersOf85[padding]; } + } + catch (OverflowException ex) { - try - { - checked { value += 84 * SPowersOf85[padding]; } - } - catch (OverflowException ex) - { - throw new FormatException("The current group of characters decodes to a value greater than UInt32.MaxValue.", ex); - } + throw new FormatException("The current group of characters decodes to a value greater than UInt32.MaxValue.", ex); } - DecodeValue(stream, value, 5 - count); } - - return stream.ToArray(); + DecodeValue(stream, value, 5 - count); } + + return stream.ToArray(); } // Writes the Ascii85 characters for a 32-bit value to a StringBuilder. private static void EncodeValue(StringBuilder sb, uint value, int paddingBytes) { - char[] encoded = new char[5]; + var encoded = new char[5]; - for (int index = 4; index >= 0; index--) + for (var index = 4; index >= 0; index--) { encoded[index] = (char)((value % 85) + CFirstCharacter); value /= 85; diff --git a/src/Framework.Core/XDocumentExtensions.cs b/src/Framework.Core/XDocumentExtensions.cs index 1309eeb1d..be53eb8a2 100644 --- a/src/Framework.Core/XDocumentExtensions.cs +++ b/src/Framework.Core/XDocumentExtensions.cs @@ -29,21 +29,17 @@ public static XmlDocument ToXmlDocument(this XDocument xDocument) { var xmlDocument = new XmlDocument(); - using (var xmlReader = xDocument.CreateReader()) - { - xmlDocument.Load(xmlReader); - } + using var xmlReader = xDocument.CreateReader(); + xmlDocument.Load(xmlReader); return xmlDocument; } public static XDocument ToXDocument(this XmlDocument xmlDocument) { - using (var nodeReader = new XmlNodeReader(xmlDocument)) - { - nodeReader.MoveToContent(); + using var nodeReader = new XmlNodeReader(xmlDocument); + nodeReader.MoveToContent(); - return XDocument.Load(nodeReader); - } + return XDocument.Load(nodeReader); } } diff --git a/src/Framework.ExpressionParsers.Tests/ExpressionParserTests.cs b/src/Framework.ExpressionParsers.Tests/ExpressionParserTests.cs index 5bb7b2df2..2367fd2b4 100644 --- a/src/Framework.ExpressionParsers.Tests/ExpressionParserTests.cs +++ b/src/Framework.ExpressionParsers.Tests/ExpressionParserTests.cs @@ -10,12 +10,11 @@ public sealed class ExpressionParserTests public void Validate_InvalidExpressionAndErrorsUnWrapped_CorrectException() { // Arrange - var call = () => this.parser.Validate("n => blah"); - // Act - var exception = Assert.Throws(call); + var ex = Record.Exception(() => this.parser.Validate("n => blah")); // Assert + var exception = Assert.IsType(ex); Assert.Equal("Can't parse value: \"n => blah\". Expected format: \"Func\"", exception.Message); var innerException = Assert.IsType(exception.InnerException); Assert.Contains("The name 'blah' does not exist in the current context", innerException.Message); diff --git a/src/Framework.ExpressionParsers.Tests/Framework.ExpressionParsers.Tests.csproj b/src/Framework.ExpressionParsers.Tests/Framework.ExpressionParsers.Tests.csproj index 0df487830..3350dd9e4 100644 --- a/src/Framework.ExpressionParsers.Tests/Framework.ExpressionParsers.Tests.csproj +++ b/src/Framework.ExpressionParsers.Tests/Framework.ExpressionParsers.Tests.csproj @@ -6,7 +6,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Framework.ExpressionParsers/CSharp/CSharpNativeExpressionParser.cs b/src/Framework.ExpressionParsers/CSharp/CSharpNativeExpressionParser.cs index 5f9c811ab..6fc171378 100644 --- a/src/Framework.ExpressionParsers/CSharp/CSharpNativeExpressionParser.cs +++ b/src/Framework.ExpressionParsers/CSharp/CSharpNativeExpressionParser.cs @@ -66,7 +66,7 @@ private IEnumerable GetParametersNames(string expression) } var currentResult = new List(); - Func returnFunc = () => + var returnFunc = () => { var result = new string(currentResult.ToArray()); currentResult.Clear(); diff --git a/src/Framework.ExpressionParsers/CSharp/MicrosoftCSharpExpressionParserImplement.cs b/src/Framework.ExpressionParsers/CSharp/MicrosoftCSharpExpressionParserImplement.cs index 71c1b1d74..b986634cb 100644 --- a/src/Framework.ExpressionParsers/CSharp/MicrosoftCSharpExpressionParserImplement.cs +++ b/src/Framework.ExpressionParsers/CSharp/MicrosoftCSharpExpressionParserImplement.cs @@ -29,7 +29,7 @@ public override string ToString() var props = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); var sb = new StringBuilder(); sb.Append("{"); - for (int i = 0; i < props.Length; i++) + for (var i = 0; i < props.Length; i++) { if (i > 0) { @@ -81,7 +81,7 @@ public Signature(IEnumerable properties) { this.Properties = properties.ToArray(); this.HashCode = 0; - foreach (DynamicProperty p in properties) + foreach (var p in properties) { this.HashCode ^= p.Name.GetHashCode() ^ p.Type.GetHashCode(); } @@ -94,7 +94,7 @@ public Signature(IEnumerable properties) public bool Equals(Signature other) { if (this.Properties.Length != other.Properties.Length) return false; - for (int i = 0; i < this.Properties.Length; i++) + for (var i = 0; i < this.Properties.Length; i++) { if (this.Properties[i].Name != other.Properties[i].Name || this.Properties[i].Type != other.Properties[i].Type) return false; } @@ -115,8 +115,8 @@ static ClassFactory() { } // Trigger lazy initialization of static fields private ClassFactory() { - AssemblyName name = new AssemblyName("DynamicClasses"); - AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); + var name = new AssemblyName("DynamicClasses"); + var assembly = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); #if ENABLE_LINQ_PARTIAL_TRUST new ReflectionPermission(PermissionState.Unrestricted).Assert(); #endif @@ -139,7 +139,7 @@ public Type GetDynamicClass(IEnumerable properties) this.rwLock.AcquireReaderLock(Timeout.Infinite); try { - Signature signature = new Signature(properties); + var signature = new Signature(properties); Type type; if (!this.classes.TryGetValue(signature, out type)) { @@ -156,18 +156,18 @@ public Type GetDynamicClass(IEnumerable properties) Type CreateDynamicClass(DynamicProperty[] properties) { - LockCookie cookie = this.rwLock.UpgradeToWriterLock(Timeout.Infinite); + var cookie = this.rwLock.UpgradeToWriterLock(Timeout.Infinite); try { - string typeName = "DynamicClass" + (this.classCount + 1); + var typeName = "DynamicClass" + (this.classCount + 1); #if ENABLE_LINQ_PARTIAL_TRUST new ReflectionPermission(PermissionState.Unrestricted).Assert(); #endif try { - TypeBuilder tb = this.module.DefineType(typeName, TypeAttributes.Class | - TypeAttributes.Public, typeof(DynamicClass)); - FieldInfo[] fields = this.GenerateProperties(tb, properties); + var tb = this.module.DefineType(typeName, TypeAttributes.Class | + TypeAttributes.Public, typeof(DynamicClass)); + var fields = this.GenerateProperties(tb, properties); this.GenerateEquals(tb, fields); this.GenerateGetHashCode(tb, fields); Type result = tb.CreateTypeInfo(); @@ -190,7 +190,7 @@ Type CreateDynamicClass(DynamicProperty[] properties) FieldInfo[] GenerateProperties(TypeBuilder tb, DynamicProperty[] properties) { FieldInfo[] fields = new FieldBuilder[properties.Length]; - for (int i = 0; i < properties.Length; i++) + for (var i = 0; i < properties.Length; i++) { var dp = properties[i]; var fb = tb.DefineField("_" + dp.Name, dp.Type, FieldAttributes.Private); @@ -236,10 +236,10 @@ void GenerateEquals(TypeBuilder tb, FieldInfo[] fields) gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ret); gen.MarkLabel(next); - foreach (FieldInfo field in fields) + foreach (var field in fields) { - Type ft = field.FieldType; - Type ct = typeof(EqualityComparer<>).MakeGenericType(ft); + var ft = field.FieldType; + var ct = typeof(EqualityComparer<>).MakeGenericType(ft); next = gen.DefineLabel(); gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null); gen.Emit(OpCodes.Ldarg_0); @@ -264,10 +264,10 @@ void GenerateGetHashCode(TypeBuilder tb, FieldInfo[] fields) typeof(int), Type.EmptyTypes); var gen = mb.GetILGenerator(); gen.Emit(OpCodes.Ldc_I4_0); - foreach (FieldInfo field in fields) + foreach (var field in fields) { - Type ft = field.FieldType; - Type ct = typeof(EqualityComparer<>).MakeGenericType(ft); + var ft = field.FieldType; + var ct = typeof(EqualityComparer<>).MakeGenericType(ft); gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, field); @@ -550,9 +550,9 @@ void ProcessParameters(ParameterExpression[] parameters) void ProcessValues(object[] values) { - for (int i = 0; i < values.Length; i++) + for (var i = 0; i < values.Length; i++) { - object value = values[i]; + var value = values[i]; if (i == values.Length - 1 && value is IDictionary) { this.externals = (IDictionary)value; @@ -591,8 +591,8 @@ public IEnumerable ParseOrdering() List orderings = []; while (true) { - Expression expr = this.ParseExpression(); - bool ascending = true; + var expr = this.ParseExpression(); + var ascending = true; if (this.TokenIdentifierIs("asc") || this.TokenIdentifierIs("ascending")) { this.NextToken(); @@ -614,15 +614,15 @@ public IEnumerable ParseOrdering() // ?: operator Expression ParseExpression() { - int errorPos = this.token.Pos; - Expression expr = this.ParseLogicalOr(); + var errorPos = this.token.Pos; + var expr = this.ParseLogicalOr(); if (this.token.Id == TokenId.Question) { this.NextToken(); - Expression expr1 = this.ParseExpression(); + var expr1 = this.ParseExpression(); this.ValidateToken(TokenId.Colon, ExpressionParsersResources.ColonExpected); this.NextToken(); - Expression expr2 = this.ParseExpression(); + var expr2 = this.ParseExpression(); expr = this.GenerateConditional(expr, expr1, expr2, errorPos); } return expr; @@ -631,12 +631,12 @@ Expression ParseExpression() // ||, or operator Expression ParseLogicalOr() { - Expression left = this.ParseLogicalAnd(); + var left = this.ParseLogicalAnd(); while (this.token.Id == TokenId.DoubleBar || this.TokenIdentifierIs("or")) { - Token op = this.token; + var op = this.token; this.NextToken(); - Expression right = this.ParseLogicalAnd(); + var right = this.ParseLogicalAnd(); this.CheckAndPromoteOperands(typeof(ILogicalSignatures), op.Text, ref left, ref right, op.Pos); left = Expression.OrElse(left, right); } @@ -646,12 +646,12 @@ Expression ParseLogicalOr() // &&, and operator Expression ParseLogicalAnd() { - Expression left = this.ParseComparison(); + var left = this.ParseComparison(); while (this.token.Id == TokenId.DoubleAmphersand || this.TokenIdentifierIs("and")) { - Token op = this.token; + var op = this.token; this.NextToken(); - Expression right = this.ParseComparison(); + var right = this.ParseComparison(); this.CheckAndPromoteOperands(typeof(ILogicalSignatures), op.Text, ref left, ref right, op.Pos); left = Expression.AndAlso(left, right); } @@ -661,14 +661,14 @@ Expression ParseLogicalAnd() // =, ==, !=, <>, >, >=, <, <= operators Expression ParseComparison() { - Expression left = this.ParseAdditive(); + var left = this.ParseAdditive(); while (this.token.Id == TokenId.Equal || this.token.Id == TokenId.DoubleEqual || this.token.Id == TokenId.ExclamationEqual || this.token.Id == TokenId.LessGreater || this.token.Id == TokenId.GreaterThan || this.token.Id == TokenId.GreaterThanEqual || this.token.Id == TokenId.LessThan || this.token.Id == TokenId.LessThanEqual) { - Token op = this.token; + var op = this.token; this.NextToken(); - Expression right = this.ParseAdditive(); - bool isEquality = op.Id == TokenId.Equal || op.Id == TokenId.DoubleEqual || - op.Id == TokenId.ExclamationEqual || op.Id == TokenId.LessGreater; + var right = this.ParseAdditive(); + var isEquality = op.Id == TokenId.Equal || op.Id == TokenId.DoubleEqual || + op.Id == TokenId.ExclamationEqual || op.Id == TokenId.LessGreater; if (isEquality && !left.Type.IsValueType && !right.Type.IsValueType) { if (left.Type != right.Type) @@ -741,12 +741,12 @@ Expression ParseComparison() // +, -, & operators Expression ParseAdditive() { - Expression left = this.ParseMultiplicative(); + var left = this.ParseMultiplicative(); while (this.token.Id == TokenId.Plus || this.token.Id == TokenId.Minus || this.token.Id == TokenId.Amphersand) { - Token op = this.token; + var op = this.token; this.NextToken(); - Expression right = this.ParseMultiplicative(); + var right = this.ParseMultiplicative(); switch (op.Id) { case TokenId.Plus: @@ -770,12 +770,12 @@ Expression ParseAdditive() // *, /, %, mod operators Expression ParseMultiplicative() { - Expression left = this.ParseUnary(); + var left = this.ParseUnary(); while (this.token.Id == TokenId.Asterisk || this.token.Id == TokenId.Slash || this.token.Id == TokenId.Percent || this.TokenIdentifierIs("mod")) { - Token op = this.token; + var op = this.token; this.NextToken(); - Expression right = this.ParseUnary(); + var right = this.ParseUnary(); this.CheckAndPromoteOperands(typeof(IArithmeticSignatures), op.Text, ref left, ref right, op.Pos); switch (op.Id) { @@ -799,7 +799,7 @@ Expression ParseUnary() { if (this.token.Id == TokenId.Minus || this.token.Id == TokenId.Exclamation || this.TokenIdentifierIs("not")) { - Token op = this.token; + var op = this.token; this.NextToken(); if (op.Id == TokenId.Minus && (this.token.Id == TokenId.IntegerLiteral || this.token.Id == TokenId.RealLiteral)) { @@ -807,7 +807,7 @@ Expression ParseUnary() this.token.Pos = op.Pos; return this.ParsePrimary(); } - Expression expr = this.ParseUnary(); + var expr = this.ParseUnary(); if (op.Id == TokenId.Minus) { this.CheckAndPromoteOperand(typeof(INegationSignatures), op.Text, ref expr, op.Pos); @@ -825,7 +825,7 @@ Expression ParseUnary() Expression ParsePrimary() { - Expression expr = this.ParsePrimaryStart(); + var expr = this.ParsePrimaryStart(); while (true) { if (this.token.Id == TokenId.Dot) @@ -867,12 +867,12 @@ Expression ParsePrimaryStart() Expression ParseStringLiteral() { this.ValidateToken(TokenId.StringLiteral); - char quote = this.token.Text[0]; - string s = this.token.Text.Substring(1, this.token.Text.Length - 2); - int start = 0; + var quote = this.token.Text[0]; + var s = this.token.Text.Substring(1, this.token.Text.Length - 2); + var start = 0; while (true) { - int i = s.IndexOf(quote, start); + var i = s.IndexOf(quote, start); if (i < 0) break; s = s.Remove(i, 1); start = i + 1; @@ -891,7 +891,7 @@ Expression ParseStringLiteral() Expression ParseIntegerLiteral() { this.ValidateToken(TokenId.IntegerLiteral); - string text = this.token.Text; + var text = this.token.Text; if (text[0] != '-') { ulong value; @@ -918,9 +918,9 @@ Expression ParseIntegerLiteral() Expression ParseRealLiteral() { this.ValidateToken(TokenId.RealLiteral); - string text = this.token.Text; + var text = this.token.Text; object value = null; - char last = text[text.Length - 1]; + var last = text[text.Length - 1]; if (last == 'F' || last == 'f') { float f; @@ -947,7 +947,7 @@ Expression ParseRealLiteral() Expression CreateLiteral(object value, string text) { - ConstantExpression expr = Expression.Constant(value); + var expr = Expression.Constant(value); this.literals.Add(expr, text); return expr; } @@ -1013,9 +1013,9 @@ Expression ParseIt() Expression ParseIif() { - int errorPos = this.token.Pos; + var errorPos = this.token.Pos; this.NextToken(); - Expression[] args = this.ParseArgumentList(); + var args = this.ParseArgumentList(); if (args.Length != 3) throw this.ParseError(errorPos, ExpressionParsersResources.IifRequiresThreeArgs); return this.GenerateConditional(args[0], args[1], args[2], errorPos); @@ -1027,8 +1027,8 @@ Expression GenerateConditional(Expression test, Expression expr1, Expression exp throw this.ParseError(errorPos, ExpressionParsersResources.FirstExprMustBeBool); if (expr1.Type != expr2.Type) { - Expression expr1As2 = expr2 != NullLiteral ? this.PromoteExpression(expr1, expr2.Type, true) : null; - Expression expr2As1 = expr1 != NullLiteral ? this.PromoteExpression(expr2, expr1.Type, true) : null; + var expr1As2 = expr2 != NullLiteral ? this.PromoteExpression(expr1, expr2.Type, true) : null; + var expr2As1 = expr1 != NullLiteral ? this.PromoteExpression(expr2, expr1.Type, true) : null; if (expr1As2 != null && expr2As1 == null) { expr1 = expr1As2; @@ -1039,8 +1039,8 @@ Expression GenerateConditional(Expression test, Expression expr1, Expression exp } else { - string type1 = expr1 != NullLiteral ? expr1.Type.Name : "null"; - string type2 = expr2 != NullLiteral ? expr2.Type.Name : "null"; + var type1 = expr1 != NullLiteral ? expr1.Type.Name : "null"; + var type2 = expr2 != NullLiteral ? expr2.Type.Name : "null"; if (expr1As2 != null && expr2As1 != null) throw this.ParseError(errorPos, ExpressionParsersResources.BothTypesConvertToOther, type1, type2); throw this.ParseError(errorPos, ExpressionParsersResources.NeitherTypeConvertsToOther, type1, type2); @@ -1076,8 +1076,8 @@ private Expression ParseDynamicType() var expressions = new List(); while (true) { - int exprPos = this.token.Pos; - Expression expr = this.ParseExpression(); + var exprPos = this.token.Pos; + var expr = this.ParseExpression(); string propName; if (this.TokenIdentifierIs("as")) { @@ -1103,7 +1103,7 @@ private Expression ParseDynamicType() this.NextToken(); var type = CreateClass(properties); var bindings = new MemberBinding[properties.Count]; - for (int i = 0; i < bindings.Length; i++) + for (var i = 0; i < bindings.Length; i++) { bindings[i] = Expression.Bind(type.GetProperty(properties[i].Name), expressions[i]); } @@ -1112,7 +1112,7 @@ private Expression ParseDynamicType() Expression ParseExpressionInvocation(LambdaExpression lambda) { - int errorPos = this.token.Pos; + var errorPos = this.token.Pos; this.NextToken(); var args = this.ParseArgumentList(); if (!(this.FindMethod(lambda.Type, "Invoke", false, args) is FindMethodsResult.SimpleResult)) @@ -1124,7 +1124,7 @@ Expression ParseExpressionInvocation(LambdaExpression lambda) Expression ParseTypeAccess(Type type) { - int errorPos = this.token.Pos; + var errorPos = this.token.Pos; this.NextToken(); if (this.token.Id == TokenId.Question) { @@ -1135,7 +1135,7 @@ Expression ParseTypeAccess(Type type) } if (this.token.Id == TokenId.OpenParen) { - Expression[] args = this.ParseArgumentList(); + var args = this.ParseArgumentList(); var result = this.FindBestMethod(type.GetConstructors(), args); if (result is FindMethodsResult.NoneResult) { @@ -1158,7 +1158,7 @@ Expression ParseTypeAccess(Type type) Expression GenerateConversion(Expression expr, Type type, int errorPos) { - Type exprType = expr.Type; + var exprType = expr.Type; if (exprType == type) return expr; if (exprType.IsValueType && type.IsValueType) { @@ -1263,9 +1263,9 @@ static Type FindGenericType(Type generic, Type type) if (type.IsGenericTypeImplementation(generic)) return type; if (generic.IsInterface) { - foreach (Type intfType in type.GetInterfaces()) + foreach (var intfType in type.GetInterfaces()) { - Type found = FindGenericType(generic, intfType); + var found = FindGenericType(generic, intfType); if (found != null) return found; } } @@ -1278,7 +1278,7 @@ Expression[] ParseArgumentList() { this.ValidateToken(TokenId.OpenParen, ExpressionParsersResources.OpenParenExpected); this.NextToken(); - Expression[] args = this.token.Id != TokenId.CloseParen ? this.ParseArguments() : []; + var args = this.token.Id != TokenId.CloseParen ? this.ParseArguments() : []; this.ValidateToken(TokenId.CloseParen, ExpressionParsersResources.CloseParenOrCommaExpected); this.NextToken(); return args; @@ -1298,17 +1298,17 @@ Expression[] ParseArguments() Expression ParseElementAccess(Expression expr) { - int errorPos = this.token.Pos; + var errorPos = this.token.Pos; this.ValidateToken(TokenId.OpenBracket, ExpressionParsersResources.OpenParenExpected); this.NextToken(); - Expression[] args = this.ParseArguments(); + var args = this.ParseArguments(); this.ValidateToken(TokenId.CloseBracket, ExpressionParsersResources.CloseBracketOrCommaExpected); this.NextToken(); if (expr.Type.IsArray) { if (expr.Type.GetArrayRank() != 1 || args.Length != 1) throw this.ParseError(errorPos, ExpressionParsersResources.CannotIndexMultiDimArray); - Expression index = this.PromoteExpression(args[0], typeof(int), true); + var index = this.PromoteExpression(args[0], typeof(int), true); if (index == null) throw this.ParseError(errorPos, ExpressionParsersResources.InvalidIndex); return Expression.ArrayIndex(expr, index); @@ -1332,7 +1332,7 @@ Expression ParseElementAccess(Expression expr) static bool IsPredefinedType(Type type) { - foreach (Type t in PredefinedTypes) if (t == type) return true; + foreach (var t in PredefinedTypes) if (t == type) return true; return false; } @@ -1342,8 +1342,8 @@ static bool IsPredefinedType(Type type) static string GetTypeName(Type type) { - Type baseType = GetNonNullableType(type); - string s = baseType.Name; + var baseType = GetNonNullableType(type); + var s = baseType.Name; if (type != baseType) s += '?'; return s; } @@ -1409,12 +1409,12 @@ Exception IncompatibleOperandsError(string opName, Expression left, Expression r MemberInfo FindPropertyOrField(Type type, string memberName, bool staticAccess) { - BindingFlags flags = BindingFlags.Public | BindingFlags.DeclaredOnly | - (staticAccess ? BindingFlags.Static : BindingFlags.Instance); - foreach (Type t in SelfAndBaseTypes(type)) + var flags = BindingFlags.Public | BindingFlags.DeclaredOnly | + (staticAccess ? BindingFlags.Static : BindingFlags.Instance); + foreach (var t in SelfAndBaseTypes(type)) { - MemberInfo[] members = t.FindMembers(MemberTypes.Property | MemberTypes.Field, - flags, Type.FilterNameIgnoreCase, memberName); + var members = t.FindMembers(MemberTypes.Property | MemberTypes.Field, + flags, Type.FilterNameIgnoreCase, memberName); if (members.Length != 0) return members[0]; } return null; @@ -1459,7 +1459,7 @@ FindMethodsResult FindMethod(Type type, string methodName, bool staticAccess, Ex FindMethodsResult FindIndexer(Type type, Expression[] args) { - foreach (Type t in SelfAndBaseTypes(type)) + foreach (var t in SelfAndBaseTypes(type)) { var members = t.GetDefaultMembers(); @@ -1506,7 +1506,7 @@ static void AddInterface(List types, Type type) if (!types.Contains(type)) { types.Add(type); - foreach (Type t in type.GetInterfaces()) AddInterface(types, t); + foreach (var t in type.GetInterfaces()) AddInterface(types, t); } } @@ -1549,11 +1549,11 @@ bool IsApplicable(MethodData method, Expression[] args) { if (method.Parameters.Length != args.Length) return false; var promotedArgs = new Expression[args.Length]; - for (int i = 0; i < args.Length; i++) + for (var i = 0; i < args.Length; i++) { - ParameterInfo pi = method.Parameters[i]; + var pi = method.Parameters[i]; if (pi.IsOut) return false; - Expression promoted = this.PromoteExpression(args[i], pi.ParameterType, false); + var promoted = this.PromoteExpression(args[i], pi.ParameterType, false); if (promoted == null) return false; promotedArgs[i] = promoted; } @@ -1566,7 +1566,7 @@ Expression PromoteExpression(Expression expr, Type type, bool exact) if (expr.Type == type) return expr; if (expr is ConstantExpression) { - ConstantExpression ce = (ConstantExpression)expr; + var ce = (ConstantExpression)expr; if (ce == NullLiteral) { if (!type.IsValueType || IsNullableType(type)) @@ -1577,7 +1577,7 @@ Expression PromoteExpression(Expression expr, Type type, bool exact) string text; if (this.literals.TryGetValue(ce, out text)) { - Type target = GetNonNullableType(type); + var target = GetNonNullableType(type); object value = null; switch (Type.GetTypeCode(ce.Type)) { @@ -1663,9 +1663,9 @@ static object ParseEnum(string name, Type type) { if (type.IsEnum) { - MemberInfo[] memberInfos = type.FindMembers(MemberTypes.Field, - BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static, - Type.FilterNameIgnoreCase, name); + var memberInfos = type.FindMembers(MemberTypes.Field, + BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static, + Type.FilterNameIgnoreCase, name); if (memberInfos.Length != 0) return ((FieldInfo)memberInfos[0]).GetValue(null); } return null; @@ -1675,11 +1675,11 @@ static bool IsCompatibleWith(Type source, Type target) { if (source == target) return true; if (!target.IsValueType) return target.IsAssignableFrom(source); - Type st = GetNonNullableType(source); - Type tt = GetNonNullableType(target); + var st = GetNonNullableType(source); + var tt = GetNonNullableType(target); if (st != source && tt == target) return false; - TypeCode sc = st.IsEnum ? TypeCode.Object : Type.GetTypeCode(st); - TypeCode tc = tt.IsEnum ? TypeCode.Object : Type.GetTypeCode(tt); + var sc = st.IsEnum ? TypeCode.Object : Type.GetTypeCode(st); + var tc = tt.IsEnum ? TypeCode.Object : Type.GetTypeCode(tt); switch (sc) { case TypeCode.SByte: @@ -1797,10 +1797,10 @@ static bool IsCompatibleWith(Type source, Type target) static bool IsBetterThan(Expression[] args, MethodData m1, MethodData m2) { - bool better = false; - for (int i = 0; i < args.Length; i++) + var better = false; + for (var i = 0; i < args.Length; i++) { - int c = CompareConversions(args[i].Type, + var c = CompareConversions(args[i].Type, m1.Parameters[i].ParameterType, m2.Parameters[i].ParameterType); if (c < 0) @@ -1823,8 +1823,8 @@ static int CompareConversions(Type s, Type t1, Type t2) if (t1 == t2) return 0; if (s == t1) return 1; if (s == t2) return -1; - bool t1T2 = IsCompatibleWith(t1, t2); - bool t2T1 = IsCompatibleWith(t2, t1); + var t1T2 = IsCompatibleWith(t1, t2); + var t2T1 = IsCompatibleWith(t2, t1); if (t1T2 && !t2T1) return 1; if (t2T1 && !t1T2) return -1; if (IsSignedIntegralType(t1) && IsUnsignedIntegralType(t2)) return 1; @@ -1920,7 +1920,7 @@ void NextToken() this.NextChar(); } TokenId t; - int tokenPos = this.textPos; + var tokenPos = this.textPos; switch (this.currentChar) { case '!': @@ -2054,7 +2054,7 @@ void NextToken() break; case '"': case '\'': - char quote = this.currentChar; + var quote = this.currentChar; do { this.NextChar(); @@ -2128,7 +2128,7 @@ void NextToken() string GetIdentifier() { this.ValidateToken(TokenId.Identifier, ExpressionParsersResources.IdentifierExpected); - string id = this.token.Text; + var id = this.token.Text; if (id.Length > 1 && id[0] == '@') { id = id.Substring(1); diff --git a/src/Framework.ExpressionParsers/CSharp/RoslynCSharpExpressionParser.cs b/src/Framework.ExpressionParsers/CSharp/RoslynCSharpExpressionParser.cs index b1a9e7b7e..a42c389af 100644 --- a/src/Framework.ExpressionParsers/CSharp/RoslynCSharpExpressionParser.cs +++ b/src/Framework.ExpressionParsers/CSharp/RoslynCSharpExpressionParser.cs @@ -64,27 +64,25 @@ public Expression Parse(ParameterExpression[] parameters, Type returnType, strin .AddReferences(references) .AddSyntaxTrees(CSharpSyntaxTree.ParseText(source)); - using (var stream = new MemoryStream()) - { - var compileResult = compilation.Emit(stream); + using var stream = new MemoryStream(); + var compileResult = compilation.Emit(stream); - if (compileResult.Success) - { - stream.Position = 0; + if (compileResult.Success) + { + stream.Position = 0; - var assembly = AssemblyLoadContext.Default.LoadFromStream(stream); + var assembly = AssemblyLoadContext.Default.LoadFromStream(stream); - var expressionParserType = assembly.GetType($"{namespaceName}.{typeName}"); + var expressionParserType = assembly.GetType($"{namespaceName}.{typeName}"); - return expressionParserType.GetMethod(methodName).Invoke(null); - } - else - { + return expressionParserType.GetMethod(methodName).Invoke(null); + } + else + { - var errorTextBuilder = compileResult.Diagnostics.Join(",", d => $"{d.Id}: {d.GetMessage()}"); - var exception = new ParseException(errorTextBuilder, 0); - throw exception; - } + var errorTextBuilder = compileResult.Diagnostics.Join(",", d => $"{d.Id}: {d.GetMessage()}"); + var exception = new ParseException(errorTextBuilder, 0); + throw exception; } } } diff --git a/src/Framework.ExpressionParsers/CSharp/ScriptEngineService.cs b/src/Framework.ExpressionParsers/CSharp/ScriptEngineService.cs index 2030df9c5..53caf1f8d 100644 --- a/src/Framework.ExpressionParsers/CSharp/ScriptEngineService.cs +++ b/src/Framework.ExpressionParsers/CSharp/ScriptEngineService.cs @@ -160,7 +160,7 @@ private IEnumerable GetParametersNames(string expression) } var currentResult = new List(); - Func returnFunc = () => + var returnFunc = () => { var result = new string(currentResult.ToArray()); currentResult.Clear(); diff --git a/src/Infrastructure/Framework.Infrastructure.Hangfire/Framework.Infrastructure.Hangfire.csproj b/src/Infrastructure/Framework.Infrastructure.Hangfire/Framework.Infrastructure.Hangfire.csproj index 1b7209e19..9efd93148 100644 --- a/src/Infrastructure/Framework.Infrastructure.Hangfire/Framework.Infrastructure.Hangfire.csproj +++ b/src/Infrastructure/Framework.Infrastructure.Hangfire/Framework.Infrastructure.Hangfire.csproj @@ -13,6 +13,7 @@ + diff --git a/src/Projection/Framework.Projection.Runtime/Lambda/ProjectionLambdaEnvironment.cs b/src/Projection/Framework.Projection.Runtime/Lambda/ProjectionLambdaEnvironment.cs index 41300a382..c94829a56 100644 --- a/src/Projection/Framework.Projection.Runtime/Lambda/ProjectionLambdaEnvironment.cs +++ b/src/Projection/Framework.Projection.Runtime/Lambda/ProjectionLambdaEnvironment.cs @@ -55,10 +55,7 @@ private ITypeResolver CreateProjectionTypeResolver(IProjectionSourc return TypeResolverHelper.Create(this.projections.ToDictionary(projection => projection, this.ProjectionTypeResolver.Resolve)); } - public Type GetSecurityProjectionType(Type sourceType) - { - return this.ProjectionTypeResolver.Resolve(this.projections.TryGetSecurityProjection(sourceType)!); - } + public Type GetSecurityProjectionType(Type sourceType) => this.ProjectionTypeResolver.Resolve(this.projections.TryGetSecurityProjection(sourceType)!); /// /// Получение типа свойства из ссылки на тип diff --git a/src/Validation/Framework.Validation.Tests/Framework.Validation.Tests.csproj b/src/Validation/Framework.Validation.Tests/Framework.Validation.Tests.csproj index 38eaac1ee..ff6a13808 100644 --- a/src/Validation/Framework.Validation.Tests/Framework.Validation.Tests.csproj +++ b/src/Validation/Framework.Validation.Tests/Framework.Validation.Tests.csproj @@ -8,7 +8,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/_Authorization/Framework.Authorization.TestGenerate/Framework.Authorization.TestGenerate.csproj b/src/_Authorization/Framework.Authorization.TestGenerate/Framework.Authorization.TestGenerate.csproj index 54bba630f..9ab77be06 100644 --- a/src/_Authorization/Framework.Authorization.TestGenerate/Framework.Authorization.TestGenerate.csproj +++ b/src/_Authorization/Framework.Authorization.TestGenerate/Framework.Authorization.TestGenerate.csproj @@ -6,7 +6,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/_Configuration/Framework.Configuration.TestGenerate/Framework.Configuration.TestGenerate.csproj b/src/_Configuration/Framework.Configuration.TestGenerate/Framework.Configuration.TestGenerate.csproj index 2a4eb0a91..65f51ee5d 100644 --- a/src/_Configuration/Framework.Configuration.TestGenerate/Framework.Configuration.TestGenerate.csproj +++ b/src/_Configuration/Framework.Configuration.TestGenerate/Framework.Configuration.TestGenerate.csproj @@ -6,7 +6,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/_Configuration/Framework.Configuration.TestGenerate/ServerGenerators.cs b/src/_Configuration/Framework.Configuration.TestGenerate/ServerGenerators.cs index 1d7d376a3..ec3159588 100644 --- a/src/_Configuration/Framework.Configuration.TestGenerate/ServerGenerators.cs +++ b/src/_Configuration/Framework.Configuration.TestGenerate/ServerGenerators.cs @@ -11,10 +11,7 @@ namespace Framework.Configuration.TestGenerate; public partial class ServerGenerators { [Fact] - public void GenerateMainTest() - { - this.GenerateMain().ToList(); - } + public void GenerateMainTest() => this.GenerateMain().ToList(); public IEnumerable GenerateMain() => this.GenerateBLLCore() diff --git a/src/_Configuration/Framework.Configuration.WebApi/Impl/QueueService.cs b/src/_Configuration/Framework.Configuration.WebApi/Impl/QueueService.cs index 6ca1de455..c56b86b72 100644 --- a/src/_Configuration/Framework.Configuration.WebApi/Impl/QueueService.cs +++ b/src/_Configuration/Framework.Configuration.WebApi/Impl/QueueService.cs @@ -20,7 +20,7 @@ public int ProcessModifications(int limit) context.Authorization.SecuritySystem.CheckAccessAsync(SecurityRole.SystemIntegration, this.HttpContext.RequestAborted).GetAwaiter().GetResult(); - return context.Logics.DomainObjectModification.Process(limit == default(int) ? 1000 : limit); + return context.Logics.DomainObjectModification.Process(limit == 0 ? 1000 : limit); }); return result.Match(v => v, ex => throw ex); diff --git a/src/_SampleSystem/SampleSystem.WebApiCore/Services/IntegrationEventProcessor.cs b/src/_SampleSystem/SampleSystem.WebApiCore/Services/IntegrationEventProcessor.cs index f124c218f..b870d0b9b 100644 --- a/src/_SampleSystem/SampleSystem.WebApiCore/Services/IntegrationEventProcessor.cs +++ b/src/_SampleSystem/SampleSystem.WebApiCore/Services/IntegrationEventProcessor.cs @@ -17,6 +17,6 @@ public Task ProcessAsync(IIntegrationEvent @event, CancellationToken cancellatio async x => { await x.GetRequiredService().Publish(@event, cancellationToken); - return default!; + return null!; }); } diff --git a/src/_SampleSystem/_Tests/SampleSystem.CheckGenTests/CsprojPackageIdTests.cs b/src/_SampleSystem/_Tests/SampleSystem.CheckGenTests/CsprojPackageIdTests.cs index b692d2b18..c19cf4712 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.CheckGenTests/CsprojPackageIdTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.CheckGenTests/CsprojPackageIdTests.cs @@ -118,15 +118,9 @@ private static HashSet LoadSlnxProjects(string slnxPath) .ToHashSet(StringComparer.OrdinalIgnoreCase); } - private static string ToRelativePath(string root, string file) - { - return NormalizePath(Path.GetRelativePath(root, file)); - } + private static string ToRelativePath(string root, string file) => NormalizePath(Path.GetRelativePath(root, file)); - private static string NormalizePath(string path) - { - return path.Replace('\\', '/').TrimStart('/'); - } + private static string NormalizePath(string path) => path.Replace('\\', '/').TrimStart('/'); private static string FindSolutionRoot() { diff --git a/src/_SampleSystem/_Tests/SampleSystem.CheckGenTests/SampleSystem.CheckGenTests.csproj b/src/_SampleSystem/_Tests/SampleSystem.CheckGenTests/SampleSystem.CheckGenTests.csproj index 04d220bc4..a9d425e4e 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.CheckGenTests/SampleSystem.CheckGenTests.csproj +++ b/src/_SampleSystem/_Tests/SampleSystem.CheckGenTests/SampleSystem.CheckGenTests.csproj @@ -6,7 +6,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/_SampleSystem/_Tests/SampleSystem.CodeGenerate/SampleSystem.CodeGenerate.csproj b/src/_SampleSystem/_Tests/SampleSystem.CodeGenerate/SampleSystem.CodeGenerate.csproj index ed496d254..1d70df975 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.CodeGenerate/SampleSystem.CodeGenerate.csproj +++ b/src/_SampleSystem/_Tests/SampleSystem.CodeGenerate/SampleSystem.CodeGenerate.csproj @@ -5,7 +5,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/_SampleSystem/_Tests/SampleSystem.DbGenerate.NHibernate/SampleSystem.DbGenerate.NHibernate.csproj b/src/_SampleSystem/_Tests/SampleSystem.DbGenerate.NHibernate/SampleSystem.DbGenerate.NHibernate.csproj index b6386c9f6..0ed7653da 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.DbGenerate.NHibernate/SampleSystem.DbGenerate.NHibernate.csproj +++ b/src/_SampleSystem/_Tests/SampleSystem.DbGenerate.NHibernate/SampleSystem.DbGenerate.NHibernate.csproj @@ -8,7 +8,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AsyncControllerTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AsyncControllerTests.cs index ebb2d7c04..195e27915 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AsyncControllerTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AsyncControllerTests.cs @@ -1,10 +1,10 @@ using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.WebApiCore.Controllers.Main; namespace SampleSystem.IntegrationTests; -public class AsyncControllerTests : TestBase +public class AsyncControllerTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public async Task TestSaveLocation_LocationSaved() @@ -34,8 +34,9 @@ public async Task TestSaveLocationWithWriteException_ExceptionRaised() var saveDto = new LocationStrictDTO { Name = Guid.NewGuid().ToString(), CloseDate = 30, Code = 12345 }; // Act - Func saveTask = () => asyncControllerEvaluator.EvaluateAsync(c => c.AsyncSaveLocationWithWriteException(saveDto, default)); + var ex = await Record.ExceptionAsync(() => asyncControllerEvaluator.EvaluateAsync(c => c.AsyncSaveLocationWithWriteException(saveDto, default))); - await Assert.ThrowsAsync(saveTask); + // Assert + Assert.IsType(ex); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AuditTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AuditTests.cs index 82820a277..a6588bb9c 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AuditTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AuditTests.cs @@ -6,7 +6,7 @@ using SampleSystem.Domain.Employee; using SampleSystem.Domain.Inline; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.WebApiCore.Controllers.Audit; using SampleSystem.WebApiCore.Controllers.Main; @@ -14,7 +14,7 @@ namespace SampleSystem.IntegrationTests; -public class AuditTests : TestBase +public class AuditTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void GetObjectRevisions_CheckCount_Correct() @@ -35,7 +35,7 @@ public void GetObjectRevisions_CheckCount_Correct() var employeeIdentity = employeeController.Evaluate(c => c.SaveEmployee(employeeStrictDto)); - for (int q = 0; q < testCount; q++) + for (var q = 0; q < testCount; q++) { var employeeFull = employeeController.Evaluate(c => c.GetFullEmployee(employeeIdentity)); var employeeStrict = employeeFull.ToStrict(); @@ -68,7 +68,7 @@ public void GetObjectByRevision_CheckState_Correct() var employeeIdentity = employeeController.Evaluate(c => c.SaveEmployee(employeeStrictDto)); - for (int q = 0; q < testCount; q++) + for (var q = 0; q < testCount; q++) { var employeeFull = employeeController.Evaluate(c => c.GetFullEmployee(employeeIdentity)); var employeeStrict = employeeFull.ToStrict(); @@ -143,7 +143,7 @@ public void GetObjectPropertyRevisions_ChangePrimitiveProperty_CorrectRevisions( var employeeIdentity = employeeController.Evaluate(c => c.SaveEmployee(employeeStrictDto)); - for (int q = 0; q < testCount; q++) + for (var q = 0; q < testCount; q++) { var employeeFull = employeeController.Evaluate(c => c.GetFullEmployee(employeeIdentity)); var employeeStrict = employeeFull.ToStrict(); @@ -188,7 +188,7 @@ public void GetObjectPropertyRevisions_CheckFirstRevisioins_HasAddedState() var employeeIdentity = employeeController.Evaluate(c => c.SaveEmployee(employeeStrictDto)); - for (int q = 0; q < testCount; q++) + for (var q = 0; q < testCount; q++) { var employeeFull = employeeController.Evaluate(c => c.GetFullEmployee(employeeIdentity)); var employeeStrict = employeeFull.ToStrict(); @@ -233,7 +233,7 @@ public void GetObjectPropertyRevisions_CheckAfterFirstRevisioins_AllModifiedStat var employeeIdentity = employeeController.Evaluate(c => c.SaveEmployee(employeeStrictDto)); - for (int q = 0; q < testCount; q++) + for (var q = 0; q < testCount; q++) { var employeeFull = employeeController.Evaluate(c => c.GetFullEmployee(employeeIdentity)); var employeeStrict = employeeFull.ToStrict(); @@ -268,7 +268,7 @@ public void CrateNewBu_AuditBuLoadedFromCustomMapping() this.AuthManager.For(testUser).LoginAs(); // Act - var newBu = this.DataHelper.SaveBusinessUnit(); + var newBu = this.DataManager.SaveBusinessUnit(); // Assert diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/Auth/PrincipalTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/Auth/PrincipalTests.cs index 33da392c6..cd837f2e0 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/Auth/PrincipalTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/Auth/PrincipalTests.cs @@ -1,17 +1,18 @@ using Framework.Authorization.Generated.DTO; using Framework.BLL.Exceptions; -using SampleSystem.IntegrationTests.__Support.TestData; using SampleSystem.Security; using SampleSystem.WebApiCore.Controllers.Main; using Anch.SecuritySystem; +using SampleSystem.IntegrationTests._Environment.TestData; + using DelegateToItemModelStrictDTO = Framework.Authorization.Generated.DTO.DelegateToItemModelStrictDTO; namespace SampleSystem.IntegrationTests.Auth; -public class PrincipalTests : TestBase +public class PrincipalTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private const string Name = "luxoft\\Login"; private const string NewName = "luxoft\\ChangeLogin"; @@ -21,7 +22,7 @@ public void AddPermission_CheckAddition() { // Arrange var authorizationController = this.GetAuthControllerEvaluator(); - var currentUser = this.DataHelper.GetCurrentEmployee(); + var currentUser = this.DataManager.GetCurrentEmployee(); var businessRoleIdentity = authorizationController.Evaluate(c => c.GetSimpleBusinessRoleByName(SampleSystemSecurityRole.SecretariatNotification.Name)).Identity; @@ -44,7 +45,7 @@ public void SavePrincipal_CheckCreateon() { // Arrange var authorizationController = this.GetAuthControllerEvaluator(); - var currentUser = this.DataHelper.GetCurrentEmployee(); + var currentUser = this.DataManager.GetCurrentEmployee(); var businessRoleIdentity = authorizationController.Evaluate(c => c.GetSimpleBusinessRoleByName(SampleSystemSecurityRole.SecretariatNotification.Name)).Identity; @@ -70,7 +71,7 @@ public void SavePrincipal_CheckCreateon() public void SavePrincipal_CheckPrincipalChanges() { // Arrange - var currentUser = this.DataHelper.GetCurrentEmployee(); + var currentUser = this.DataManager.GetCurrentEmployee(); var principalStrict = new PrincipalStrictDTO { Name = Name }; this.GetAuthControllerEvaluator().Evaluate(c => c.SavePrincipal(principalStrict)); @@ -93,7 +94,7 @@ public void SavePrincipal_CheckPrincipalChanges() public void PermissionDelegate_CheckChanges() { // Arrange - var currentUser = this.DataHelper.GetCurrentEmployee(); + var currentUser = this.DataManager.GetCurrentEmployee(); var businessRoleIdentity = this.GetAuthControllerEvaluator().Evaluate(c => c.GetSimpleBusinessRoleByName(SampleSystemSecurityRole.SecretariatNotification.Name)).Identity; @@ -150,10 +151,11 @@ public void RemovePermission_CheckRemoval() // Act this.GetAuthControllerEvaluator().Evaluate(c => c.RemovePermission(permissionIdentity)); - Action call = () => this.GetAuthControllerEvaluator().Evaluate(c => c.GetSimplePermission(permissionIdentity)); + var ex = Record.Exception(() => this.GetAuthControllerEvaluator().Evaluate(c => c.GetSimplePermission(permissionIdentity))); // Assert - Assert.Matches("^Permission with id = \".*\" not found$", Assert.Throws>(call).Message); + var notFoundException = Assert.IsType>(ex); + Assert.Matches("^Permission with id = \".*\" not found$", notFoundException.Message); } [Fact] @@ -163,10 +165,11 @@ public void RemovePrincipalWithRole_CheckException() var principalIdentity = this.GetAuthControllerEvaluator().Evaluate(c => c.GetCurrentPrincipal()).Identity; // Act - var call = () => this.GetAuthControllerEvaluator().Evaluate(c => c.RemovePrincipal(principalIdentity)); + var ex = Record.Exception(() => this.GetAuthControllerEvaluator().Evaluate(c => c.RemovePrincipal(principalIdentity))); // Assert - Assert.Matches("^Removing principal \".*\" must be empty$", Assert.Throws(call).Message); + var securityException = Assert.IsType(ex); + Assert.Matches("^Removing principal \".*\" must be empty$", securityException.Message); } [Fact] @@ -179,9 +182,10 @@ public void RemovePrincipal_CheckRemoval() // Act this.GetAuthControllerEvaluator().Evaluate(c => c.RemovePrincipal(principalIdentity)); - var call = () => this.GetAuthControllerEvaluator().Evaluate(c => c.GetSimplePrincipal(principalIdentity)); + var ex = Record.Exception(() => this.GetAuthControllerEvaluator().Evaluate(c => c.GetSimplePrincipal(principalIdentity))); // Assert - Assert.Matches("^Principal with id = \".*\" not found$", Assert.Throws>(call).Message); + var notFoundException = Assert.IsType>(ex); + Assert.Matches("^Principal with id = \".*\" not found$", notFoundException.Message); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AuthPerfomanceTest.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AuthPerfomanceTest.cs index 84bdd1bd9..d7b7247bf 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AuthPerfomanceTest.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AuthPerfomanceTest.cs @@ -10,14 +10,15 @@ using SampleSystem.Domain.Employee; using SampleSystem.Domain.MU; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; using SampleSystem.Security; using Anch.SecuritySystem; +using SampleSystem.IntegrationTests._Environment.TestData; + namespace SampleSystem.IntegrationTests; -public class AuthPerformanceTest : TestBase +public class AuthPerformanceTest(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private IReadOnlyCollection fbuSource; @@ -31,19 +32,19 @@ public class AuthPerformanceTest : TestBase private static readonly int Size = 5; - public AuthPerformanceTest() + protected override async ValueTask InitializeAsync(CancellationToken ct) { - this.fbuSource = [null, .. Enumerable.Range(0, Size - 1).Select(_ => (BusinessUnitIdentityDTO?)this.DataHelper.SaveBusinessUnit())]; + this.fbuSource = [null, .. Enumerable.Range(0, Size - 1).Select(_ => (BusinessUnitIdentityDTO?)this.DataManager.SaveBusinessUnit())]; - this.mbuSource = [null, .. Enumerable.Range(0, Size - 1).Select(_ => (ManagementUnitIdentityDTO?)this.DataHelper.SaveManagementUnit())]; + this.mbuSource = [null, .. Enumerable.Range(0, Size - 1).Select(_ => (ManagementUnitIdentityDTO?)this.DataManager.SaveManagementUnit())]; - this.locationSource = [null, .. Enumerable.Range(0, Size - 1).Select(_ => (LocationIdentityDTO?)this.DataHelper.SaveLocation())]; + this.locationSource = [null, .. Enumerable.Range(0, Size - 1).Select(_ => (LocationIdentityDTO?)this.DataManager.SaveLocation())]; - this.employeeSource = [null, this.DataHelper.SaveEmployee()]; + this.employeeSource = [null, this.DataManager.SaveEmployee()]; - this.AuthManager.For(PrincipalName).CreatePrincipal(); + await this.AuthManager.For(PrincipalName).CreatePrincipalAsync(ct); - this.GeneratePermission(); + await this.GeneratePermissionAsync(ct); } [Fact] @@ -66,7 +67,7 @@ public async Task LoadGenerateAuthPerformanceObjects_CountEquals() Assert.Equal(findCount, authPerfCount); } - private void GeneratePermission() + private async ValueTask GeneratePermissionAsync(CancellationToken ct) { var request = from fbu in this.fbuSource @@ -78,7 +79,7 @@ from employee in this.employeeSource select new SampleSystemTestPermission(SampleSystemSecurityRole.TestPerformance, fbu, mbu, location, employee).ToManagedPermission(); - this.AuthManager.For(PrincipalName).SetRole(request.ToArray()); + await this.AuthManager.For(PrincipalName).SetRoleAsync([.. request], ct); } private async Task GenerateAuthPerformanceObject() => @@ -92,7 +93,7 @@ await this.RootServiceProvider.GetRequiredService().Evaluat var empRep = sp.GetRequiredService>().Create(); var testObjRep = sp.GetRequiredService>().Create(); - int count = 0; + var count = 0; foreach (var fbu in this.fbuSource.Take(Size - 3)) { foreach (var mbu in this.mbuSource.Take(Size - 3)) diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AuthPerformanceTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AuthPerformanceTests.cs index d53fabba1..0b26fd8b7 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AuthPerformanceTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/AuthPerformanceTests.cs @@ -4,15 +4,16 @@ using SampleSystem.Domain; using SampleSystem.Domain.TestDeserializedAuth; -using SampleSystem.IntegrationTests.__Support.TestData; using SampleSystem.Security; using SampleSystem.WebApiCore.Controllers.Main; using Anch.SecuritySystem; +using SampleSystem.IntegrationTests._Environment.TestData; + namespace SampleSystem.IntegrationTests; -public class AuthPerformanceTests : TestBase +public class AuthPerformanceTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private const string TestUser = "TestUser"; @@ -20,15 +21,15 @@ public class AuthPerformanceTests : TestBase private const int SplitBy = 25; - public AuthPerformanceTests() + protected override async ValueTask InitializeAsync(CancellationToken ct) { - var genLoc = Enumerable.Range(0, Limit).ToList(i => this.DataHelper.SaveLocation()); + var genLoc = Enumerable.Range(0, Limit).ToList(i => this.DataManager.SaveLocation()); - var genEmployee = Enumerable.Range(0, Limit).ToList(i => this.DataHelper.SaveEmployee()); + var genEmployee = Enumerable.Range(0, Limit).ToList(i => this.DataManager.SaveEmployee()); - var genBu = Enumerable.Range(0, Limit).ToList(i => this.DataHelper.SaveBusinessUnit()); + var genBu = Enumerable.Range(0, Limit).ToList(i => this.DataManager.SaveBusinessUnit()); - var genMbu = Enumerable.Range(0, Limit).ToList(i => this.DataHelper.SaveManagementUnit()); + var genMbu = Enumerable.Range(0, Limit).ToList(i => this.DataManager.SaveManagementUnit()); var genObjects = this.EvaluateWrite(ctx => { diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/BUProjectionTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/BUProjectionTests.cs index d415e550d..7f3b9940c 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/BUProjectionTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/BUProjectionTests.cs @@ -3,41 +3,41 @@ using SampleSystem.Domain.BU; using SampleSystem.Domain.Inline; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.WebApiCore.Controllers.MainQuery; namespace SampleSystem.IntegrationTests; -public class BUProjectionTests : TestBase +public class BUProjectionTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private const string TestEmployee0Login = "Test Employee 0"; private const string TestEmployee1Login = "Test Employee 1"; private const string TestEmployee2Login = "Test Employee 2"; - public BUProjectionTests() + protected override async ValueTask InitializeAsync(CancellationToken ct) { - var buTypeId = this.DataHelper.SaveBusinessUnitType(DefaultConstants.BUSINESS_UNIT_TYPE_COMPANY_ID); + var buTypeId = this.DataManager.SaveBusinessUnitType(DefaultConstants.BUSINESS_UNIT_TYPE_COMPANY_ID); - var luxoftBuId = this.DataHelper.SaveBusinessUnit( + var luxoftBuId = this.DataManager.SaveBusinessUnit( id: DefaultConstants.BUSINESS_UNIT_PARENT_COMPANY_ID, name: DefaultConstants.BUSINESS_UNIT_PARENT_COMPANY_NAME, type: buTypeId); - var costBuId = this.DataHelper.SaveBusinessUnit( + var costBuId = this.DataManager.SaveBusinessUnit( id: DefaultConstants.BUSINESS_UNIT_PARENT_CC_ID, name: DefaultConstants.BUSINESS_UNIT_PARENT_CC_NAME, type: buTypeId, parent: luxoftBuId); - var profitBuId = this.DataHelper.SaveBusinessUnit( + var profitBuId = this.DataManager.SaveBusinessUnit( id: DefaultConstants.BUSINESS_UNIT_PARENT_PC_ID, name: DefaultConstants.BUSINESS_UNIT_PARENT_PC_NAME, type: buTypeId, parent: luxoftBuId); - var empId1 = this.DataHelper.SaveEmployee(login: TestEmployee0Login, coreBusinessUnit: costBuId, nameEng: new Fio { FirstName = "AA" }); - var empId2 = this.DataHelper.SaveEmployee(login: TestEmployee1Login, coreBusinessUnit: costBuId, nameEng: new Fio { FirstName = "BB" }); - var empId3 = this.DataHelper.SaveEmployee(login: TestEmployee2Login, coreBusinessUnit: profitBuId, nameEng: new Fio { FirstName = "CC" }); + var empId1 = this.DataManager.SaveEmployee(login: TestEmployee0Login, coreBusinessUnit: costBuId, nameEng: new Fio { FirstName = "AA" }); + var empId2 = this.DataManager.SaveEmployee(login: TestEmployee1Login, coreBusinessUnit: costBuId, nameEng: new Fio { FirstName = "BB" }); + var empId3 = this.DataManager.SaveEmployee(login: TestEmployee2Login, coreBusinessUnit: profitBuId, nameEng: new Fio { FirstName = "CC" }); this.Evaluate( DBSessionMode.Write, diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/BusinessUnitTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/BusinessUnitTests.cs index 7632102aa..d6fb07a6f 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/BusinessUnitTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/BusinessUnitTests.cs @@ -1,16 +1,17 @@ using Framework.Application; using Framework.AutomationCore.RootServiceProviderContainer; -using Framework.AutomationCore.Utils; using Framework.BLL.Domain.Persistent; using Framework.Core; using Framework.Database; using Anch.SecuritySystem; +using Framework.AutomationCore.Utils; + using SampleSystem.Domain.BU; using SampleSystem.Domain.Enums; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.Security; using SampleSystem.WebApiCore.Controllers.MainQuery; @@ -18,7 +19,7 @@ namespace SampleSystem.IntegrationTests; -public class BusinessUnitTests : TestBase +public class BusinessUnitTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private const string EmployeeName = "TestSecondaryAccessEmployee"; @@ -26,31 +27,32 @@ public class BusinessUnitTests : TestBase private const int ExistedBusinessUnitsInDatabase = 3; - public BusinessUnitTests() + protected override async ValueTask InitializeAsync(CancellationToken ct) { - var buTypeId = this.DataHelper.SaveBusinessUnitType(DefaultConstants.BUSINESS_UNIT_TYPE_COMPANY_ID); + var buTypeId = this.DataManager.SaveBusinessUnitType(DefaultConstants.BUSINESS_UNIT_TYPE_COMPANY_ID); - var luxoftBuId = this.DataHelper.SaveBusinessUnit( + var luxoftBuId = this.DataManager.SaveBusinessUnit( id: DefaultConstants.BUSINESS_UNIT_PARENT_COMPANY_ID, name: DefaultConstants.BUSINESS_UNIT_PARENT_COMPANY_NAME, type: buTypeId); - this.DataHelper.SaveBusinessUnit( + this.DataManager.SaveBusinessUnit( id: DefaultConstants.BUSINESS_UNIT_PARENT_CC_ID, name: DefaultConstants.BUSINESS_UNIT_PARENT_CC_NAME, type: buTypeId, parent: luxoftBuId); - this.DataHelper.SaveBusinessUnit( + this.DataManager.SaveBusinessUnit( id: DefaultConstants.BUSINESS_UNIT_PARENT_PC_ID, name: DefaultConstants.BUSINESS_UNIT_PARENT_PC_NAME, type: buTypeId, parent: luxoftBuId); - this.AuthManager.For(EmployeeName).SetRole( + await this.AuthManager.For(EmployeeName).SetRoleAsync( new SampleSystemTestPermission( SampleSystemSecurityRole.TestRole3, - new BusinessUnitIdentityDTO(DefaultConstants.BUSINESS_UNIT_PARENT_PC_ID))); + new BusinessUnitIdentityDTO(DefaultConstants.BUSINESS_UNIT_PARENT_PC_ID)), + ct); } [Fact] @@ -60,13 +62,13 @@ public void CheckBusinessUnitSecondaryAccess_HasAccess() var businessUnitQueryController = this.GetControllerEvaluator(EmployeeName); // Act - var businessUnitTree = businessUnitQueryController.Evaluate( - c => c.GetTestBusinessUnitTreeByOperation( - new GetTestBusinessUnitTreeByOperationAutoRequest - { - OdataQueryString = string.Empty, - SecurityRule = new DomainSecurityRule.ClientSecurityRule(SampleSystemSecurityOperation.EmployeeEdit.Name) - })); + var businessUnitTree = businessUnitQueryController.Evaluate(c => c.GetTestBusinessUnitTreeByOperation( + new GetTestBusinessUnitTreeByOperationAutoRequest + { + OdataQueryString = string.Empty, + SecurityRule = new DomainSecurityRule.ClientSecurityRule( + SampleSystemSecurityOperation.EmployeeEdit.Name) + })); // Assert Assert.Equal(2, businessUnitTree.TotalCount); @@ -83,13 +85,13 @@ public void GetTreeWithFilter() var businessUnitQueryController = this.GetControllerEvaluator(EmployeeName); // Act - var businessUnitTree = businessUnitQueryController.Evaluate( - c => c.GetTestBusinessUnitTreeByOperation( - new GetTestBusinessUnitTreeByOperationAutoRequest - { - OdataQueryString = "$filter=Name eq 'test'", - SecurityRule = new DomainSecurityRule.ClientSecurityRule(SampleSystemSecurityOperation.EmployeeEdit.Name) - })); + var businessUnitTree = businessUnitQueryController.Evaluate(c => c.GetTestBusinessUnitTreeByOperation( + new GetTestBusinessUnitTreeByOperationAutoRequest + { + OdataQueryString = "$filter=Name eq 'test'", + SecurityRule = new DomainSecurityRule.ClientSecurityRule( + SampleSystemSecurityOperation.EmployeeEdit.Name) + })); // Assert Assert.Equal(0, businessUnitTree.TotalCount); @@ -112,8 +114,8 @@ public void GetFullBusinessUnitsTreeTwoTestInOne() public void LoadTreeWithMiddlePermission_RootParentLoadedWithViewMode() { // Arrange - var parentBu = this.DataHelper.SaveBusinessUnit(parentIsNeeded: false); - var childBu = this.DataHelper.SaveBusinessUnit(parent: parentBu); + var parentBu = this.DataManager.SaveBusinessUnit(parentIsNeeded: false); + var childBu = this.DataManager.SaveBusinessUnit(parent: parentBu); this.ClearIntegrationEvents(); @@ -160,34 +162,33 @@ private void TestGetFullBusinessUnitsTree() private void CreateBigBuTree() { - var buAccountId = this.DataHelper.SaveBusinessUnitType(DefaultConstants.BUSINESS_UNIT_TYPE_ACCOUNT_ID); + var buAccountId = this.DataManager.SaveBusinessUnitType(DefaultConstants.BUSINESS_UNIT_TYPE_ACCOUNT_ID); + + this.DataManager + .EvaluateWrite(context => + { + var period = new Period( + this.FinancialYearService.GetCurrentFinancialYear().StartDate + .AddYears(-1)); + var accountType = context.Logics.BusinessUnitType.GetById(buAccountId.Id); - this.DataHelper - .EvaluateWrite( - context => + for (var i = 0; i < ParentsCount; i++) { - var period = new Period( - this.FinancialYearService.GetCurrentFinancialYear().StartDate - .AddYears(-1)); - var accountType = context.Logics.BusinessUnitType.GetById(buAccountId.Id); - - for (var i = 0; i < ParentsCount; i++) - { - var accountBu = - new BusinessUnit - { - Id = Guid.NewGuid(), - Active = true, - Name = TextRandomizer.UniqueString("Account"), - IsPool = true, - BusinessUnitStatus = BusinessUnitStatus.Current, - IsProduction = true, - BusinessUnitType = accountType, - Period = period - }; - - context.Logics.Default.Create().Insert(accountBu, accountBu.Id); - } - }); + var accountBu = + new BusinessUnit + { + Id = Guid.NewGuid(), + Active = true, + Name = TextRandomizer.UniqueString("Account"), + IsPool = true, + BusinessUnitStatus = BusinessUnitStatus.Current, + IsProduction = true, + BusinessUnitType = accountType, + Period = period + }; + + context.Logics.Default.Create().Insert(accountBu, accountBu.Id); + } + }); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/CurrentUserManyRelativePathTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/CurrentUserManyRelativePathTests.cs index fa7081af3..1b473cccc 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/CurrentUserManyRelativePathTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/CurrentUserManyRelativePathTests.cs @@ -5,23 +5,21 @@ using Anch.SecuritySystem; using SampleSystem.Domain; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class CurrentUserManyRelativePathTests : TestBase +public class CurrentUserManyRelativePathTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private Guid[] testEmployeeIdents; private Guid testObj; - public CurrentUserManyRelativePathTests() + protected override async ValueTask InitializeAsync(CancellationToken ct) { this.testEmployeeIdents = - Enumerable.Range(0, 3).Select( - _ => { return this.DataHelper.SaveEmployee().Id; }) - .ToArray(); + Enumerable.Range(0, 3).Select(_ => this.DataManager.SaveEmployee().Id).ToArray(); this.testObj = this.EvaluateWrite( ctx => @@ -32,7 +30,7 @@ public CurrentUserManyRelativePathTests() foreach (var testEmployeeIdent in this.testEmployeeIdents) { - var testEmployee = ctx.Logics.Employee.GetById(testEmployeeIdent, true); + var testEmployee = ctx.Logics.Employee.GetById(testEmployeeIdent, true)!; new TestRelativeEmployeeChildObject(parentObj) { Employee = testEmployee }; } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/CurrentUserSingleRelativePathTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/CurrentUserSingleRelativePathTests.cs index 518d53e6b..b3f0d833f 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/CurrentUserSingleRelativePathTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/CurrentUserSingleRelativePathTests.cs @@ -9,15 +9,15 @@ using SampleSystem.Domain; using SampleSystem.Domain.Employee; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class CurrentUserSingleRelativePathTests : TestBase +public class CurrentUserSingleRelativePathTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private Guid[] testObjectIdents; - public CurrentUserSingleRelativePathTests() => + protected override async ValueTask InitializeAsync(CancellationToken ct) => this.testObjectIdents = this.Evaluate( DBSessionMode.Write, ctx => diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/CurrentUserSourceTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/CurrentUserSourceTests.cs index 0f320c495..5ddd711ac 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/CurrentUserSourceTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/CurrentUserSourceTests.cs @@ -5,18 +5,18 @@ using Anch.SecuritySystem.UserSource; using SampleSystem.Domain.Employee; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class CurrentUserSourceTests : TestBase +public class CurrentUserSourceTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void TryGetCurrentUserWithEmployee_CurrentUserResolved() { // Arrange var randomName = TextRandomizer.RandomString(10); - var employeeId = this.DataHelper.SaveEmployee(login: randomName).Id; + var employeeId = this.DataManager.SaveEmployee(login: randomName).Id; // Act var result = this.Evaluate( @@ -40,16 +40,14 @@ public void TryGetCurrentUserWithoutEmployee_ExceptionRaised() var randomName = TextRandomizer.RandomString(10); // Act - var action = () => - { + var ex = Record.Exception(() => this.Evaluate( DBSessionMode.Read, randomName, - ctx => ctx.CurrentEmployeeSource.CurrentUser.Id); - }; + ctx => ctx.CurrentEmployeeSource.CurrentUser.Id)); // Assert - var exception = Assert.Throws(action); - Assert.Equal($"{nameof(Employee)} \"{randomName}\" not found", exception.Message); + var userSourceException = Assert.IsType(ex); + Assert.Equal($"{nameof(Employee)} \"{randomName}\" not found", userSourceException.Message); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/ChangeIndexesStrategyTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/ChangeIndexesStrategyTests.cs index 5f0726e92..83fbd33bf 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/ChangeIndexesStrategyTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/ChangeIndexesStrategyTests.cs @@ -1,15 +1,16 @@ -using Framework.Database.NHibernate.DBGenerator; +using Framework.AutomationCore.RootServiceProviderContainer; +using Framework.Database.NHibernate.DBGenerator; using Microsoft.SqlServer.Management.Smo; using SampleSystem.DbGenerate.NHibernate; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using Index = Microsoft.SqlServer.Management.Smo.Index; namespace SampleSystem.IntegrationTests.DBGeneration; -public class ChangeIndexesStrategyTests : TestBase +public class ChangeIndexesStrategyTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void GenerateLocal_ColumnHasIndexWithIncludedColumns_PreventsDefaultIndexFromGeneration() @@ -18,7 +19,7 @@ public void GenerateLocal_ColumnHasIndexWithIncludedColumns_PreventsDefaultIndex var generator = new DbGeneratorTest(); var tableName = "Employee"; - var table = this.DataHelper.GetTable(this.DatabaseContext.Main.DatabaseName, tableName); + var table = this.DataManager.GetTable(this.DatabaseContext.Main.DatabaseName, tableName); var baseIndexName = "IX_Employee_coreBusinessUnitId"; var newIndexName = "IX_Employee_coreBusinessUnitId_inc"; @@ -46,10 +47,10 @@ public void GenerateLocal_ColumnHasIndexWithIncludedColumns_PreventsDefaultIndex this.DatabaseContext.Main.Password), skipFrameworkDatabases: true); - var changedTable = this.DataHelper.GetTable(this.DatabaseContext.Main.DatabaseName, tableName); + var changedTable = this.DataManager.GetTable(this.DatabaseContext.Main.DatabaseName, tableName); // Assert - var indexes = changedTable.Indexes.Cast().ToList(); + var indexes = changedTable.Indexes.ToList(); Assert.Contains(indexes, x => x.Name == newIndexName); Assert.DoesNotContain(indexes, x => x.Name == baseIndexName); } @@ -61,7 +62,7 @@ public void GenerateLocal_IgnoredIndex_NotCreated() var generator = new DbGeneratorTest(); var tableName = "Employee"; - var table = this.DataHelper.GetTable(this.DatabaseContext.Main.DatabaseName, tableName); + var table = this.DataManager.GetTable(this.DatabaseContext.Main.DatabaseName, tableName); var ignoredIndexName = "IX_Employee_hRDepartmentId"; @@ -77,10 +78,10 @@ public void GenerateLocal_IgnoredIndex_NotCreated() this.DatabaseContext.Main.Password), ignoredIndexes: [ignoredIndexName], skipFrameworkDatabases: true); - var changedTable = this.DataHelper.GetTable(this.DatabaseContext.Main.DatabaseName, tableName); + var changedTable = this.DataManager.GetTable(this.DatabaseContext.Main.DatabaseName, tableName); // Assert - Assert.DoesNotContain(changedTable.Indexes.Cast(), x => x.Name == ignoredIndexName); + Assert.DoesNotContain(changedTable.Indexes, x => x.Name == ignoredIndexName); } [Fact] @@ -98,9 +99,9 @@ public void GenerateLocal_UniqueFieldForFK_NoDuplicates() this.DatabaseContext.Main.Password), skipFrameworkDatabases: true); - var changedTable = this.DataHelper.GetTable(this.DatabaseContext.Main.DatabaseName, "Employee"); + var changedTable = this.DataManager.GetTable(this.DatabaseContext.Main.DatabaseName, "Employee"); // Assert - Assert.DoesNotContain(changedTable.Indexes.Cast(), x => x.Name == "IX_ChildEntity_parentId"); + Assert.DoesNotContain(changedTable.Indexes, x => x.Name == "IX_ChildEntity_parentId"); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/GenerateDBTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/GenerateDBTests.cs index 3f872461f..3dd2cccc9 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/GenerateDBTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/GenerateDBTests.cs @@ -1,27 +1,24 @@ -using Framework.Database.NHibernate.DBGenerator; +using Anch.Testing.Xunit; -using SampleSystem.DbGenerate.NHibernate; -using SampleSystem.IntegrationTests.__Support.TestData; +using Microsoft.Extensions.DependencyInjection; + +using SampleSystem.IntegrationTests._Environment; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests.DBGeneration; -public class GenerateDBTests : TestBase +public class GenerateDBTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { - [Fact] - public void GenerateDB_SecondTime_ShouldNotFail() + [AnchFact] + public async Task GenerateDB_SecondTime_ShouldNotFail(CancellationToken ct) { // Arrange - var generator = new DbGeneratorTest(); + var initializer = rootServiceProvider.GetRequiredService(); // Act - var action = new Action(() => generator.GenerateAllDB( - this.DatabaseContext.Main.DataSource, - this.DatabaseContext.Main.DatabaseName, - credential: DbUserCredential.Create( - this.DatabaseContext.Main.UserId, - this.DatabaseContext.Main.Password))); + var ex = await Record.ExceptionAsync(() => initializer.Initialize(ct)); // Assert - Assert.Null(Record.Exception(action)); + Assert.Null(ex); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/SchemeUpdateTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/SchemeUpdateTests.cs index 89b0dc47c..0f737b93e 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/SchemeUpdateTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/SchemeUpdateTests.cs @@ -1,21 +1,21 @@ -using SampleSystem.DbGenerate.NHibernate; -using SampleSystem.IntegrationTests.__Support.TestData; +using Framework.AutomationCore.RootServiceProviderContainer; + +using SampleSystem.DbGenerate.NHibernate; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests.DBGeneration; -public class SchemeUpdateTests : TestBase +public class SchemeUpdateTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void SchemeUpdate_ExistsDatabase_ShouldNotFail() { // Arrange - var generator = new UseSchemeUpdateTest(); // Act - var action = new Action(() => UseSchemeUpdateTest.UseSchemeUpdate(this.DatabaseContext.Main.ConnectionString)); + var ex = Record.Exception(() => UseSchemeUpdateTest.UseSchemeUpdate(this.DatabaseContext.Main.ConnectionString)); // Assert - var ex = Record.Exception(action); Assert.Null(ex); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/UniqueGroupDatabaseScriptGeneratorTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/UniqueGroupDatabaseScriptGeneratorTests.cs index 04cf66d8c..cac84ee6e 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/UniqueGroupDatabaseScriptGeneratorTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DBGeneration/UniqueGroupDatabaseScriptGeneratorTests.cs @@ -1,15 +1,16 @@ -using Framework.Database.NHibernate.DBGenerator; +using Framework.AutomationCore.RootServiceProviderContainer; +using Framework.Database.NHibernate.DBGenerator; using Microsoft.SqlServer.Management.Smo; using SampleSystem.DbGenerate.NHibernate; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using Index = Microsoft.SqlServer.Management.Smo.Index; namespace SampleSystem.IntegrationTests.DBGeneration; -public class UniqueGroupDatabaseScriptGeneratorTests : TestBase +public class UniqueGroupDatabaseScriptGeneratorTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void GenerateLocal_UniqueIndexExistsWithLessColumns_RecreatesColumns() @@ -19,7 +20,7 @@ public void GenerateLocal_UniqueIndexExistsWithLessColumns_RecreatesColumns() var tableName = "RoleRoleDegreeLink"; - var table = this.DataHelper.GetTable(this.DatabaseContext.Main.DatabaseName, tableName); + var table = this.DataManager.GetTable(this.DatabaseContext.Main.DatabaseName, tableName); var indexName = "unilink_RoleRoleDegreeLink"; @@ -41,14 +42,14 @@ public void GenerateLocal_UniqueIndexExistsWithLessColumns_RecreatesColumns() this.DatabaseContext.Main.Password), skipFrameworkDatabases: true); - var changedTable = this.DataHelper.GetTable(this.DatabaseContext.Main.DatabaseName, tableName); + var changedTable = this.DataManager.GetTable(this.DatabaseContext.Main.DatabaseName, tableName); // changedTable.Indexes.Refresh(); - var indexes = changedTable.Indexes.Cast().ToList(); + var indexes = changedTable.Indexes.ToList(); // Assert Assert.Contains(indexes, x => x.Name == indexName); - var indexedColumns = indexes.First(x => x.Name == indexName).IndexedColumns.Cast().ToList(); + var indexedColumns = indexes.First(x => x.Name == indexName).IndexedColumns.ToList(); Assert.Equal(2, indexedColumns.Count); Assert.Contains(indexedColumns, x => x.Name == "roleDegreeId"); Assert.Contains(indexedColumns, x => x.Name == "roleId"); diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DefaultFieldsTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DefaultFieldsTests.cs index a9aa91eb9..56bd5aeb8 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DefaultFieldsTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DefaultFieldsTests.cs @@ -14,8 +14,8 @@ public void GetDefaultValueFromAttr_CompareWithDTO_DefaultValuesEquals() // Act // Assert - Assert.NotEqual(default(int), dto.IntVal); - Assert.NotEqual(default(string), dto.StrVal); + Assert.NotEqual(0, dto.IntVal); + Assert.NotEqual(null, dto.StrVal); Assert.NotEqual(default(DayOfWeek), dto.EnumVal); Assert.Equal(TestDefaultFieldsMappingObj.IntDefaultVal, dto.IntVal); diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DependencySecurityTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DependencySecurityTests.cs index dd44e6fed..7d7989062 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DependencySecurityTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/DependencySecurityTests.cs @@ -2,13 +2,13 @@ using SampleSystem.Domain.TestDependency; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.Security; using SampleSystem.WebApiCore.Controllers.Main; namespace SampleSystem.IntegrationTests; -public class DependencySecurityTests : TestBase +public class DependencySecurityTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private const string TestEmployeeLogin = "DS SecurityTester"; @@ -30,15 +30,15 @@ public class DependencySecurityTests : TestBase private BusinessUnitIdentityDTO bu2Ident; - public DependencySecurityTests() + protected override async ValueTask InitializeAsync(CancellationToken ct) { - this.bu1Ident = this.DataHelper.SaveBusinessUnit(); + this.bu1Ident = this.DataManager.SaveBusinessUnit(); - this.bu2Ident = this.DataHelper.SaveBusinessUnit(); + this.bu2Ident = this.DataManager.SaveBusinessUnit(); - this.DataHelper.SaveEmployee(login: TestEmployeeLogin); + this.DataManager.SaveEmployee(login: TestEmployeeLogin); - this.AuthManager.For(TestEmployeeLogin).SetRole(new SampleSystemTestPermission(SampleSystemSecurityRole.SeManager, this.bu2Ident)); + await this.AuthManager.For(TestEmployeeLogin).SetRoleAsync(new SampleSystemTestPermission(SampleSystemSecurityRole.SeManager, this.bu2Ident), ct); this.EvaluateWrite( context => diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EmployeeProjectionTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EmployeeProjectionTests.cs index 6a6fbea61..f71a84587 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EmployeeProjectionTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EmployeeProjectionTests.cs @@ -3,59 +3,60 @@ using Framework.Core; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.Security; using SampleSystem.WebApiCore.Controllers.MainQuery; namespace SampleSystem.IntegrationTests; -public class EmployeeProjectionTests : TestBase +public class EmployeeProjectionTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private const string ProjectionPrincipalName = "Projection Tester"; private const string TestEmployee1Login = "Test Employee 1"; private const string TestEmployee2Login = "Test Employee 2"; private const string TestEmployee3Login = "Test Employee 3"; - public EmployeeProjectionTests() + protected override async ValueTask InitializeAsync(CancellationToken ct) { - var buTypeId = this.DataHelper.SaveBusinessUnitType(DefaultConstants.BUSINESS_UNIT_TYPE_COMPANY_ID); + var buTypeId = this.DataManager.SaveBusinessUnitType(DefaultConstants.BUSINESS_UNIT_TYPE_COMPANY_ID); - var luxoftBuId = this.DataHelper.SaveBusinessUnit( + var luxoftBuId = this.DataManager.SaveBusinessUnit( id: DefaultConstants.BUSINESS_UNIT_PARENT_COMPANY_ID, name: DefaultConstants.BUSINESS_UNIT_PARENT_COMPANY_NAME, type: buTypeId); - var costBuId = this.DataHelper.SaveBusinessUnit( + var costBuId = this.DataManager.SaveBusinessUnit( id: DefaultConstants.BUSINESS_UNIT_PARENT_CC_ID, name: DefaultConstants.BUSINESS_UNIT_PARENT_CC_NAME, type: buTypeId, parent: luxoftBuId); - var profitBuId = this.DataHelper.SaveBusinessUnit( + var profitBuId = this.DataManager.SaveBusinessUnit( id: DefaultConstants.BUSINESS_UNIT_PARENT_PC_ID, name: DefaultConstants.BUSINESS_UNIT_PARENT_PC_NAME, type: buTypeId, parent: luxoftBuId); - this.DataHelper.SaveEmployee(login: ProjectionPrincipalName, coreBusinessUnit: costBuId); - this.DataHelper.SaveEmployee(login: TestEmployee1Login, coreBusinessUnit: costBuId); - this.DataHelper.SaveEmployee(login: TestEmployee2Login, coreBusinessUnit: profitBuId); - this.DataHelper.SaveEmployee(login: TestEmployee3Login, coreBusinessUnit: costBuId); + this.DataManager.SaveEmployee(login: ProjectionPrincipalName, coreBusinessUnit: costBuId); + this.DataManager.SaveEmployee(login: TestEmployee1Login, coreBusinessUnit: costBuId); + this.DataManager.SaveEmployee(login: TestEmployee2Login, coreBusinessUnit: profitBuId); + this.DataManager.SaveEmployee(login: TestEmployee3Login, coreBusinessUnit: costBuId); - this.AuthManager.For(ProjectionPrincipalName).SetRole( + await this.AuthManager.For(ProjectionPrincipalName).SetRoleAsync( new SampleSystemTestPermission( SampleSystemSecurityRole.SeManager, - new BusinessUnitIdentityDTO(DefaultConstants.BUSINESS_UNIT_PARENT_PC_ID))); + new BusinessUnitIdentityDTO(DefaultConstants.BUSINESS_UNIT_PARENT_PC_ID)), + ct); - this.AuthManager.For(TestEmployee1Login).SetRole(SampleSystemSecurityRole.TestRole1); - this.AuthManager.For(TestEmployee3Login).SetRole(SampleSystemSecurityRole.TestRole2); + await this.AuthManager.For(TestEmployee1Login).SetRoleAsync(SampleSystemSecurityRole.TestRole1, ct); + await this.AuthManager.For(TestEmployee3Login).SetRoleAsync(SampleSystemSecurityRole.TestRole2, ct); } [Fact] public void EmployeeProjectionTest() { // Arrange - var identity = this.DataHelper.SaveEmployee(Guid.NewGuid()); + var identity = this.DataManager.SaveEmployee(Guid.NewGuid()); var controller = this.GetControllerEvaluator(); // Act @@ -121,7 +122,7 @@ public void EmployeeProjectionSortingTest() foreach (var login in logins) { - this.DataHelper.SaveEmployee(login: login); + this.DataManager.SaveEmployee(login: login); } var expected = logins.Reverse().ToArray(Maybe.Return); diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EmployeeTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EmployeeTests.cs index 1a2b30708..fdc9dcc24 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EmployeeTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EmployeeTests.cs @@ -11,17 +11,19 @@ using Anch.SecuritySystem; +using Framework.AutomationCore.RootServiceProviderContainer; + using Microsoft.Extensions.DependencyInjection; using NHibernate.Impl; using SampleSystem.Domain.Employee; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class EmployeeTests : TestBase +public class EmployeeTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void GetEmployeeFromDB_FilterByAge_ReturnNotNulRecords() @@ -32,7 +34,7 @@ public void GetEmployeeFromDB_FilterByAge_ReturnNotNulRecords() */ // Arrange - this.DataHelper.SaveEmployee(Guid.NewGuid(), age: 10); + this.DataManager.SaveEmployee(Guid.NewGuid(), age: 10); CoreDatabaseUtil.ExecuteSql( this.DatabaseContext.Main.ConnectionString, "INSERT INTO [app].[Employee] ([id], age) VALUES (NewId(), null)"); @@ -52,7 +54,7 @@ public void AddNewEmployee_CheckEmployeeSaved() { // Arrange var employeeController = this.MainWebApi.Employee; - var employeeIdentity = this.DataHelper.SaveEmployee(Guid.NewGuid()); + var employeeIdentity = this.DataManager.SaveEmployee(Guid.NewGuid()); // Act var employees = employeeController.Evaluate(c => c.GetSimpleEmployees()); @@ -70,7 +72,7 @@ public void GetEmployeeByOData_ContainsForNumberProperty_OnlyRequestedDataInTheR foreach (var pin in new[] { 123, 456 }) { - var employeeIdentity = this.DataHelper.SaveEmployee(Guid.NewGuid()); + var employeeIdentity = this.DataManager.SaveEmployee(Guid.NewGuid()); var employee = employeeController.Evaluate(c => c.GetSimpleEmployee(employeeIdentity)); employee.Pin = pin; employeeController.Evaluate(c => c.SaveEmployee(employee.ToStrict())); @@ -105,7 +107,7 @@ public void GetEmployeeByOData_TakeTestWithoutSorting_OnlyRequestedDataInTheResu foreach (var item in idToPinMap) { - var employeeIdentity = this.DataHelper.SaveEmployee(item.Key); + var employeeIdentity = this.DataManager.SaveEmployee(item.Key); var employee = employeeController.Evaluate(c => c.GetSimpleEmployee(employeeIdentity)); employee.Pin = item.Value; employeeController.Evaluate(c => c.SaveEmployee(employee.ToStrict())); @@ -146,7 +148,7 @@ public void GetEmployeeByOData_TakeAndSkipTestWithoutSorting_OnlyRequestedDataIn foreach (var item in idToPinMap) { - var employeeIdentity = this.DataHelper.SaveEmployee(item.Key); + var employeeIdentity = this.DataManager.SaveEmployee(item.Key); var employee = employeeController.Evaluate(c => c.GetSimpleEmployee(employeeIdentity)); employee.Pin = item.Value; employeeController.Evaluate(c => c.SaveEmployee(employee.ToStrict())); @@ -177,7 +179,7 @@ public void GetEmployeeByOData_TakeAndSkipTestWithSorting_OnlyRequestedDataInThe foreach (var pin in new[] { 123, 456 }) { - var employeeIdentity = this.DataHelper.SaveEmployee(Guid.NewGuid()); + var employeeIdentity = this.DataManager.SaveEmployee(Guid.NewGuid()); var employee = employeeController.Evaluate(c => c.GetSimpleEmployee(employeeIdentity)); employee.Pin = pin; employeeController.Evaluate(c => c.SaveEmployee(employee.ToStrict())); @@ -197,7 +199,7 @@ public void GetEmployeeByOData_TakeAndSkipTestWithSorting_OnlyRequestedDataInThe public void ForceDomainTypeEvent_ForceEmployeeSaveEvent_ContainsEventEmployee() { // Arrange - var employeeIdentity = this.DataHelper.SaveEmployee(Guid.NewGuid()); + var employeeIdentity = this.DataManager.SaveEmployee(Guid.NewGuid()); var configFacade = this.GetConfigurationControllerEvaluator(); @@ -226,7 +228,7 @@ public void ChangeEmployee_ProcessModifications_ContainsNotification() // Arrange var employeeController = this.MainWebApi.Employee; - var employeeIdentity = this.DataHelper.SaveEmployee(Guid.NewGuid()); + var employeeIdentity = this.DataManager.SaveEmployee(Guid.NewGuid()); var employeeVersion = employeeController.Evaluate(c => c.GetSimpleEmployee(employeeIdentity)).Version; this.ClearNotifications(); @@ -262,7 +264,7 @@ public void ChangeEmployee_ProcessModifications_ChangedUnprocessedCount() { // Arrange var employeeController = this.MainWebApi.Employee; - var employeeIdentity = this.DataHelper.SaveEmployee(Guid.NewGuid()); + var employeeIdentity = this.DataManager.SaveEmployee(Guid.NewGuid()); var employeeVersion = employeeController.Evaluate(c => c.GetSimpleEmployee(employeeIdentity)).Version; this.ClearNotifications(); @@ -296,7 +298,7 @@ public void ChangeEmployee_ContainsAribaEvent() { // Arrange var employeeController = this.MainWebApi.Employee; - var employeeIdentity = this.DataHelper.SaveEmployee(Guid.NewGuid()); + var employeeIdentity = this.DataManager.SaveEmployee(Guid.NewGuid()); var employeeVersion = employeeController.Evaluate(c => c.GetSimpleEmployee(employeeIdentity)).Version; this.ClearIntegrationEvents(); @@ -327,15 +329,16 @@ public void ChangeEmployeeWithoutVersionInfo_RaisedStateException() { // Arrange var employeeController = this.MainWebApi.Employee; - var employeeIdentity = this.DataHelper.SaveEmployee(Guid.NewGuid()); + var employeeIdentity = this.DataManager.SaveEmployee(Guid.NewGuid()); // Act - var call = new Action( + var ex = Record.Exception( () => employeeController.Evaluate( c => c.UpdateEmployee(new EmployeeUpdateDTO { Id = employeeIdentity.Id, Interphone = Maybe.Return("1234") }))); // Assert - Assert.Equal($"Object '{nameof(Employee)}' was updated or deleted by another transaction", Assert.Throws(call).Message); + var staleDomainObjectStateException = Assert.IsType(ex); + Assert.Equal($"Object '{nameof(Employee)}' was updated or deleted by another transaction", staleDomainObjectStateException.Message); } [Fact] diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EnversBug1676.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EnversBug1676.cs index 31cf90094..bd412362b 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EnversBug1676.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EnversBug1676.cs @@ -1,11 +1,11 @@ using Framework.AutomationCore.RootServiceProviderContainer; using SampleSystem.Domain.EnversBug1676; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class EnversBug1676 : TestBase +public class EnversBug1676(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void OneToOneMapping() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EventDALListenerTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EventDALListenerTests.cs index 6c7772ade..da2b29394 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EventDALListenerTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/EventDALListenerTests.cs @@ -2,11 +2,11 @@ using Framework.Database; using SampleSystem.EventMetadata; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class EventDALListenerTests : TestBase +public class EventDALListenerTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public async Task Employee_SendCustomEventOperation_ExceptionNotThrow() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ExpandPathTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ExpandPathTests.cs index be131d718..158436543 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ExpandPathTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ExpandPathTests.cs @@ -1,12 +1,13 @@ using Framework.Application; +using Framework.AutomationCore.RootServiceProviderContainer; using Framework.Core; using Framework.Database; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class ExpandPathTests : TestBase +public class ExpandPathTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void LiftToNullableContainsExt_ShouldNotThrowException() @@ -16,11 +17,13 @@ public void LiftToNullableContainsExt_ShouldNotThrowException() // Act var action = new Action(() => - { - var res = this.Evaluate(DBSessionMode.Read, context => context.Logics.Employee.GetListBy(employee => employee.CoreBusinessUnit.Period.ContainsExt(period.EndDate ?? period.StartDate))); + { + var res = this.Evaluate( + DBSessionMode.Read, + context => context.Logics.Employee.GetListBy(employee => employee.CoreBusinessUnit.Period.ContainsExt(period.EndDate ?? period.StartDate))); - return; - }); + return; + }); // Assert action(); @@ -33,11 +36,11 @@ public void LiftToNullableBinaryExpression_ShouldNotThrowException() // Act var action = new Action(() => - { - var res = this.Evaluate(DBSessionMode.Read, context => context.Logics.Employee.GetListBy(employee => employee.LocationCode == null)); + { + var res = this.Evaluate(DBSessionMode.Read, context => context.Logics.Employee.GetListBy(employee => employee.LocationCode == null)); - return; - }); + return; + }); // Assert action(); @@ -50,15 +53,15 @@ public void LiftToNullablePeriodIntersect_ShouldNotThrowException() // Act var action = new Action(() => - { - var res = this.Evaluate( - DBSessionMode.Read, - context => context.Logics.Employee.GetListBy( - employee => employee.CoreBusinessUnitPeriod.IsIntersected( - this.TimeProvider.GetCurrentMonth()))); + { + var currentMonth = this.TimeProvider.GetCurrentMonth(); - return; - }); + var res = this.Evaluate( + DBSessionMode.Read, + context => context.Logics.Employee.GetListBy(employee => employee.CoreBusinessUnitPeriod.IsIntersected(currentMonth))); + + return; + }); // Assert action(); @@ -72,11 +75,15 @@ public void LiftToNullablePeriodContains_ShouldNotThrowException() // Act var action = new Action(() => - { - var res = this.Evaluate(DBSessionMode.Read, context => context.Logics.Employee.GetListBy(employee => employee.CoreBusinessUnitPeriod.Contains(this.TimeProvider.GetToday()))); + { + var today = this.TimeProvider.GetToday(); + + var res = this.Evaluate( + DBSessionMode.Read, + context => context.Logics.Employee.GetListBy(employee => employee.CoreBusinessUnitPeriod.Contains(today))); - return; - }); + return; + }); // Assert action(); diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ExtraQueryableSecurityPathTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ExtraQueryableSecurityPathTests.cs index 567b01175..6cef89e13 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ExtraQueryableSecurityPathTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ExtraQueryableSecurityPathTests.cs @@ -11,12 +11,12 @@ using SampleSystem.BLL; using SampleSystem.Domain.Employee; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.Security; namespace SampleSystem.IntegrationTests; -public class ExtraQueryableSecurityPathTests : TestBase +public class ExtraQueryableSecurityPathTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private EmployeeIdentityDTO TestEmployee; @@ -34,48 +34,50 @@ public class ExtraQueryableSecurityPathTests : TestBase private LocationIdentityDTO loc2Ident; - public ExtraQueryableSecurityPathTests() + protected override async ValueTask InitializeAsync(CancellationToken ct) { - this.bu1Ident = this.DataHelper.SaveBusinessUnit(); + this.bu1Ident = this.DataManager.SaveBusinessUnit(); - this.bu2Ident = this.DataHelper.SaveBusinessUnit(); + this.bu2Ident = this.DataManager.SaveBusinessUnit(); - this.loc1Ident = this.DataHelper.SaveLocation(name: "Loc 1 (ExtraQueryableSecurityPathTests)"); + this.loc1Ident = this.DataManager.SaveLocation(name: "Loc 1 (ExtraQueryableSecurityPathTests)"); - this.loc2Ident = this.DataHelper.SaveLocation(name: "Loc 2 (ExtraQueryableSecurityPathTests)"); + this.loc2Ident = this.DataManager.SaveLocation(name: "Loc 2 (ExtraQueryableSecurityPathTests)"); - this.TestEmployee = this.DataHelper.SaveEmployee(login: "EQSP SecurityTester"); + this.TestEmployee = this.DataManager.SaveEmployee(login: "EQSP SecurityTester"); - this.AuthManager.For(this.TestEmployee.Id).SetRole( - new SampleSystemTestPermission(SampleSystemSecurityRole.SeManager, this.bu2Ident, null, this.loc1Ident), - new SampleSystemTestPermission(SampleSystemSecurityRole.SeManager, this.bu2Ident, null, this.loc2Ident)); + await this.AuthManager.For(this.TestEmployee.Id).SetRoleAsync( + [ + new SampleSystemTestPermission(SampleSystemSecurityRole.SeManager, this.bu2Ident, null, this.loc1Ident), + new SampleSystemTestPermission(SampleSystemSecurityRole.SeManager, this.bu2Ident, null, this.loc2Ident) + ], + ct); - this.TestEmp1 = this.DataHelper.SaveEmployee(coreBusinessUnit: this.bu1Ident, location: this.loc1Ident); + this.TestEmp1 = this.DataManager.SaveEmployee(coreBusinessUnit: this.bu1Ident, location: this.loc1Ident); - this.TestEmp2 = this.DataHelper.SaveEmployee(coreBusinessUnit: this.bu2Ident, location: this.loc1Ident); + this.TestEmp2 = this.DataManager.SaveEmployee(coreBusinessUnit: this.bu2Ident, location: this.loc1Ident); - this.TestEmp3 = this.DataHelper.SaveEmployee(coreBusinessUnit: this.bu2Ident, location: this.loc2Ident); + this.TestEmp3 = this.DataManager.SaveEmployee(coreBusinessUnit: this.bu2Ident, location: this.loc2Ident); } [Fact] public void TestExtraQueryableSecurityPath_LoadedWithExtraQueryableFilter() { // Arrange - var createProviderFunc = FuncHelper.Create( - (ISampleSystemBLLContext context) => - { - var extraQueryableSecurity = context.Logics.Location.GetUnsecureQueryable(); - - var extraSecurityPath = SecurityPath.Create(e => e.CoreBusinessUnit, true) - .And(e => e.Location, true) - .And( - e => extraQueryableSecurity.Where( - l => l == e.Location && e.Location.Id == this.loc1Ident.Id), true); - - return context.ServiceProvider.GetRequiredService>().Create( - SampleSystemSecurityOperation.EmployeeView, - extraSecurityPath); - }); + var createProviderFunc = FuncHelper.Create((ISampleSystemBLLContext context) => + { + var extraQueryableSecurity = context.Logics.Location.GetUnsecureQueryable(); + + var extraSecurityPath = SecurityPath.Create(e => e.CoreBusinessUnit, true) + .And(e => e.Location, true) + .And( + e => extraQueryableSecurity.Where(l => l == e.Location && e.Location.Id == this.loc1Ident.Id), + true); + + return context.ServiceProvider.GetRequiredService>().Create( + SampleSystemSecurityOperation.EmployeeView, + extraSecurityPath); + }); // Act var items = this.Evaluate( diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/FixedPropertyValidatorTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/FixedPropertyValidatorTests.cs index a0a36320a..28738a85b 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/FixedPropertyValidatorTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/FixedPropertyValidatorTests.cs @@ -1,11 +1,11 @@ using SampleSystem.Domain; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.WebApiCore.Controllers.Main; namespace SampleSystem.IntegrationTests; -public class FixedPropertyValidatorTests : TestBase +public class FixedPropertyValidatorTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void PrimitiveImmutablePropertyChanged_RaisedValidationError() @@ -16,17 +16,18 @@ public void PrimitiveImmutablePropertyChanged_RaisedValidationError() new TestImmutableObjStrictDTO { TestImmutablePrimitiveProperty = "AAA" })); // Act - Action changePropertyAction = () => - { - var dto = testImmutableObjController.Evaluate(c => c.GetRichTestImmutableObj(identity)); - dto.TestImmutablePrimitiveProperty = "BBB"; - testImmutableObjController.Evaluate(c => c.SaveTestImmutableObj(dto.ToStrict())); - }; + var ex = Record.Exception(() => + { + var dto = testImmutableObjController.Evaluate(c => c.GetRichTestImmutableObj(identity)); + dto.TestImmutablePrimitiveProperty = "BBB"; + testImmutableObjController.Evaluate(c => c.SaveTestImmutableObj(dto.ToStrict())); + }); // Assert + var validationException = Assert.IsType(ex); Assert.Equal( $"{nameof(TestImmutableObj.TestImmutablePrimitiveProperty)} field in {nameof(TestImmutableObj)} can't be changed", - Assert.Throws(changePropertyAction).Message); + validationException.Message); } [Fact] @@ -38,17 +39,18 @@ public void ReferenceImmutablePropertyChanged_RaisedValidationError() var identity = testImmutableObjController.Evaluate(c => c.SaveTestImmutableObj(new TestImmutableObjStrictDTO { })); // Act - Action changePropertyAction = () => - { - var dto = testImmutableObjController.Evaluate(c => c.GetRichTestImmutableObj(identity)); - dto.TestImmutableRefProperty = this.DataHelper.GetCurrentEmployee(); - testImmutableObjController.Evaluate(c => c.SaveTestImmutableObj(dto.ToStrict())); - }; + var ex = Record.Exception(() => + { + var dto = testImmutableObjController.Evaluate(c => c.GetRichTestImmutableObj(identity)); + dto.TestImmutableRefProperty = this.DataManager.GetCurrentEmployee(); + testImmutableObjController.Evaluate(c => c.SaveTestImmutableObj(dto.ToStrict())); + }); // Assert - Assert.Equal( + var validationException = Assert.IsType(ex); + Assert.Equal( $"{nameof(TestImmutableObj.TestImmutableRefProperty)} field in {nameof(TestImmutableObj)} can't be changed", - Assert.Throws(changePropertyAction).Message); + validationException.Message); } [Fact] @@ -73,12 +75,13 @@ public void ImmutablePropertyChangedByIntegration_RaisedValidationError() var identity = integrationTestImmutableObjController.Evaluate(c => c.SaveTestImmutableObj(new TestImmutableObjIntegrationRichDTO { TestImmutablePrimitiveProperty = "AAA", Id = Guid.NewGuid() })); // Act - Action changePropertyAction = () => integrationTestImmutableObjController.Evaluate(c => c.SaveTestImmutableObj(new TestImmutableObjIntegrationRichDTO { TestImmutablePrimitiveProperty = "BBB", Id = identity.Id })); + var ex = Record.Exception(() => integrationTestImmutableObjController.Evaluate(c => c.SaveTestImmutableObj(new TestImmutableObjIntegrationRichDTO { TestImmutablePrimitiveProperty = "BBB", Id = identity.Id }))); // Assert + var validationException = Assert.IsType(ex); Assert.Equal( $"{nameof(TestImmutableObj.TestImmutablePrimitiveProperty)} field in {nameof(TestImmutableObj)} can't be changed", - Assert.Throws(changePropertyAction).Message); + validationException.Message); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/GetNotificationPrincipalsByHierarchicalContextTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/GetNotificationPrincipalsByHierarchicalContextTests.cs index 05e7d1082..fab46f119 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/GetNotificationPrincipalsByHierarchicalContextTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/GetNotificationPrincipalsByHierarchicalContextTests.cs @@ -7,15 +7,16 @@ using SampleSystem.Domain.Employee; using SampleSystem.Domain.MU; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; using SampleSystem.Security; using Anch.SecuritySystem.Notification; using Anch.SecuritySystem.Notification.Domain; +using SampleSystem.IntegrationTests._Environment.TestData; + namespace SampleSystem.IntegrationTests; -public class GetNotificationPrincipalsByHierarchicalContextTests : TestBase +public class GetNotificationPrincipalsByHierarchicalContextTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private BusinessUnitIdentityDTO rootBusinessUnit; @@ -43,21 +44,21 @@ public class GetNotificationPrincipalsByHierarchicalContextTests : TestBase private string searchNotificationEmployeeLogin2 = nameof(searchNotificationEmployeeLogin2); - public GetNotificationPrincipalsByHierarchicalContextTests() + protected override async ValueTask InitializeAsync(CancellationToken ct) { - this.rootBusinessUnit = this.DataHelper.SaveBusinessUnit(id: DefaultConstants.BUSINESS_UNIT_PARENT_CC_ID); - this.child_1_0_BusinessUnit = this.DataHelper.SaveBusinessUnit(parent: this.rootBusinessUnit); - this.child_1_1_BusinessUnit = this.DataHelper.SaveBusinessUnit(parent: this.child_1_0_BusinessUnit); - this.child_2_0_BusinessUnit = this.DataHelper.SaveBusinessUnit(parent: this.rootBusinessUnit); - this.child_2_1_BusinessUnit = this.DataHelper.SaveBusinessUnit(parent: this.child_2_0_BusinessUnit); - - this.rootManagementUnit = this.DataHelper.SaveManagementUnit(id: DefaultConstants.MANAGEMENT_UNIT_PARENT_COMPANY_ID); - this.child_1_0_ManagementUnit = this.DataHelper.SaveManagementUnit(parent: this.rootManagementUnit); - this.child_1_1_ManagementUnit = this.DataHelper.SaveManagementUnit(parent: this.child_1_0_ManagementUnit); - this.child_2_0_ManagementUnit = this.DataHelper.SaveManagementUnit(parent: this.rootManagementUnit); - this.child_2_1_ManagementUnit = this.DataHelper.SaveManagementUnit(parent: this.child_2_0_ManagementUnit); - - this.rootEmployee = this.DataHelper.SaveEmployee(); + this.rootBusinessUnit = this.DataManager.SaveBusinessUnit(id: DefaultConstants.BUSINESS_UNIT_PARENT_CC_ID); + this.child_1_0_BusinessUnit = this.DataManager.SaveBusinessUnit(parent: this.rootBusinessUnit); + this.child_1_1_BusinessUnit = this.DataManager.SaveBusinessUnit(parent: this.child_1_0_BusinessUnit); + this.child_2_0_BusinessUnit = this.DataManager.SaveBusinessUnit(parent: this.rootBusinessUnit); + this.child_2_1_BusinessUnit = this.DataManager.SaveBusinessUnit(parent: this.child_2_0_BusinessUnit); + + this.rootManagementUnit = this.DataManager.SaveManagementUnit(id: DefaultConstants.MANAGEMENT_UNIT_PARENT_COMPANY_ID); + this.child_1_0_ManagementUnit = this.DataManager.SaveManagementUnit(parent: this.rootManagementUnit); + this.child_1_1_ManagementUnit = this.DataManager.SaveManagementUnit(parent: this.child_1_0_ManagementUnit); + this.child_2_0_ManagementUnit = this.DataManager.SaveManagementUnit(parent: this.rootManagementUnit); + this.child_2_1_ManagementUnit = this.DataManager.SaveManagementUnit(parent: this.child_2_0_ManagementUnit); + + this.rootEmployee = this.DataManager.SaveEmployee(); } [Fact] diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ImpersonateTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ImpersonateTests.cs index 496522ea6..941ddc255 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ImpersonateTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ImpersonateTests.cs @@ -1,9 +1,9 @@ -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.WebApiCore.Controllers.Main; namespace SampleSystem.IntegrationTests; -public class ImpersonateTests : TestBase +public class ImpersonateTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public async Task SaveDataWithImpersonate_ImpersonateWork() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/InformationTest.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/InformationTest.cs index 37030a962..bbde0a266 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/InformationTest.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/InformationTest.cs @@ -3,11 +3,11 @@ using SampleSystem.Domain.Employee; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class InformationTest : TestBase +public class InformationTest(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void CreateAndRemoveInformation_ContainsIntegrationEvents() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/IntegrationVersionTest.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/IntegrationVersionTest.cs index b725bc52d..f7dcf9483 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/IntegrationVersionTest.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/IntegrationVersionTest.cs @@ -4,12 +4,12 @@ using SampleSystem.Domain.IntegrationVersions; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.WebApiCore.Controllers.Integration; namespace SampleSystem.IntegrationTests; -public class IntegrationVersionTest : TestBase +public class IntegrationVersionTest(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void SaveWithMoreVersion_IgnoreLessPolicy_ValueSaved() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/JobTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/JobTests.cs index 69c90b5d0..5a70802ec 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/JobTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/JobTests.cs @@ -3,12 +3,12 @@ using Framework.Database; using SampleSystem.Domain; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.ServiceEnvironment.Jobs; namespace SampleSystem.IntegrationTests; -public class JobTests : TestBase +public class JobTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public async Task InvokeJobs_JobObjectsCreated() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/JsonConverterTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/JsonConverterTests.cs index fdb2a6232..112054c04 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/JsonConverterTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/JsonConverterTests.cs @@ -1,13 +1,14 @@ using System.Text.Json; +using Framework.AutomationCore.RootServiceProviderContainer; using Framework.Core; using Framework.Infrastructure.JsonConverter; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class JsonConverterTests : TestBase +public class JsonConverterTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void DateTimeConverted_ResultCorrected() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/LegalEntityProjectionTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/LegalEntityProjectionTests.cs index 5733c4ac1..50e0542ea 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/LegalEntityProjectionTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/LegalEntityProjectionTests.cs @@ -6,11 +6,11 @@ using SampleSystem.Domain.Directories; using SampleSystem.Domain.Projections; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class LegalEntityProjectionTests : TestBase +public class LegalEntityProjectionTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void LegalEntityProjectionNestedMappingTest() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ManagmentUnitFluentMappingTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ManagmentUnitFluentMappingTests.cs index 30a6b962c..6b27c0a05 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ManagmentUnitFluentMappingTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ManagmentUnitFluentMappingTests.cs @@ -3,17 +3,17 @@ using Framework.Database; using SampleSystem.Domain.NhFluentMapping; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class ManagmentUnitFluentMappingTests : TestBase +public class ManagmentUnitFluentMappingTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void CheckBusinessUnitSecondaryAccess_HasAccess() { // Arrange - var employeeId = this.DataHelper.SaveEmployee(); + var employeeId = this.DataManager.SaveEmployee(); this.Evaluate( DBSessionMode.Write, diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ManualAndLegacyProjectionSecurityTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ManualAndLegacyProjectionSecurityTests.cs index efde84212..27803d50c 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ManualAndLegacyProjectionSecurityTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ManualAndLegacyProjectionSecurityTests.cs @@ -1,13 +1,13 @@ using SampleSystem.Domain.Projections; using SampleSystem.Generated.DTO; using SampleSystem.Domain.ManualProjections; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.Security; using SampleSystem.WebApiCore.Controllers.MainQuery; namespace SampleSystem.IntegrationTests; -public class ManualAndLegacyProjectionSecurityTests : TestBase +public class ManualAndLegacyProjectionSecurityTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private const string TestEmployeeLogin = "MALProjection SecurityTester"; @@ -20,19 +20,19 @@ public class ManualAndLegacyProjectionSecurityTests : TestBase private BusinessUnitIdentityDTO bu2Ident; - public ManualAndLegacyProjectionSecurityTests() + protected override async ValueTask InitializeAsync(CancellationToken ct) { - this.bu1Ident = this.DataHelper.SaveBusinessUnit(); + this.bu1Ident = this.DataManager.SaveBusinessUnit(); - this.bu2Ident = this.DataHelper.SaveBusinessUnit(); + this.bu2Ident = this.DataManager.SaveBusinessUnit(); - this.DataHelper.SaveEmployee(login: TestEmployeeLogin); + this.DataManager.SaveEmployee(login: TestEmployeeLogin); - this.AuthManager.For(TestEmployeeLogin).SetRole(new SampleSystemTestPermission(SampleSystemSecurityRole.SeManager, this.bu2Ident)); + await this.AuthManager.For(TestEmployeeLogin).SetRoleAsync(new SampleSystemTestPermission(SampleSystemSecurityRole.SeManager, this.bu2Ident), ct); - this.TestEmp1 = this.DataHelper.SaveEmployee(coreBusinessUnit: this.bu1Ident); + this.TestEmp1 = this.DataManager.SaveEmployee(coreBusinessUnit: this.bu1Ident); - this.TestEmp2 = this.DataHelper.SaveEmployee(coreBusinessUnit: this.bu2Ident); + this.TestEmp2 = this.DataManager.SaveEmployee(coreBusinessUnit: this.bu2Ident); } [Fact] diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NH/FullTextSearchTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NH/FullTextSearchTests.cs index 9de1bf9b2..1beb4b9bf 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NH/FullTextSearchTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NH/FullTextSearchTests.cs @@ -1,10 +1,10 @@ using Framework.AutomationCore.RootServiceProviderContainer; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests.NH; -public class FullTextSearchTests : TestBase +public class FullTextSearchTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { /// /// Тест предназначен для проверки работоспособности диалекта NHibernate, diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NHibFetchTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NHibFetchTests.cs index 3897a20ca..b36fa4edd 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NHibFetchTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NHibFetchTests.cs @@ -3,11 +3,11 @@ using Anch.GenericQueryable; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class NHibFetchTests : TestBase +public class NHibFetchTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void TestPropCollection_TestPassed() => diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NhibArrayContainsTest.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NhibArrayContainsTest.cs index 39eeddeae..073684484 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NhibArrayContainsTest.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NhibArrayContainsTest.cs @@ -8,18 +8,18 @@ using SampleSystem.Domain.BU; using SampleSystem.Domain.Enums; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class NhibArrayContainsTest : TestBase +public class NhibArrayContainsTest(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void LinqContainsOverArray_TranslatedAndExecutedCorrectly() { // Arrange var name = TextRandomizer.UniqueString("BusinessUnit"); - var bu = this.DataHelper.SaveBusinessUnit(name: name); + var bu = this.DataManager.SaveBusinessUnit(name: name); var arr1 = new[] { bu.Id }; var arr2 = new[] { BusinessUnitStatus.Current }; diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NhibDateTimeTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NhibDateTimeTests.cs index e5aab0b26..4afeedf10 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NhibDateTimeTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NhibDateTimeTests.cs @@ -1,19 +1,13 @@ using Framework.AutomationCore.RootServiceProviderContainer; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.WebApiCore.Controllers.Main; namespace SampleSystem.IntegrationTests; -public class NhibDateTimeTests : TestBase +public class NhibDateTimeTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { - private DateTime prevDateTime; - - public NhibDateTimeTests() => this.prevDateTime = this.TimeProvider.GetLocalNow().DateTime; - - protected override void BeforeCleanup() => this.SetCurrentDateTime(this.prevDateTime); - [Fact] public void CreateObject_CreatedDateOverride() { diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NotificationCountryTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NotificationCountryTests.cs index d33bf5abe..17c03c7d3 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NotificationCountryTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/NotificationCountryTests.cs @@ -4,11 +4,11 @@ using SampleSystem.Domain.Directories; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class NotificationCountryTests : TestBase +public class NotificationCountryTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void CreateAndUpdateCountry_SingleModificationExists() @@ -129,9 +129,10 @@ public void EmulateFailureCountryModification_RaisedException() var configController = this.GetConfigurationControllerEvaluator(DefaultConstants.NOTIFICATION_ADMIN); // Act - var call = new Action(() => configController.Evaluate(c => c.ProcessModifications(1000))); + var ex = Record.Exception(() => configController.Evaluate(c => c.ProcessModifications(1000))); // Assert - Assert.Equal("Both arguments (previous and current) can't be null", Assert.Throws(call).Message); + var argumentException = Assert.IsType(ex); + Assert.Equal("Both arguments (previous and current) can't be null", argumentException.Message); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/OneToOneTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/OneToOneTests.cs index 6ff21b7e8..079b4bef8 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/OneToOneTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/OneToOneTests.cs @@ -2,12 +2,12 @@ using Framework.Database; using SampleSystem.Domain.Employee; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.WebApiCore.Controllers.MainQuery; namespace SampleSystem.IntegrationTests; -public class OneToOneTests : TestBase +public class OneToOneTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void GetRequestProjection_ContainsOneToOneDetail_Initialized() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/PerfomanceTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/PerfomanceTests.cs index 9712ec4c6..ca13c8bc5 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/PerfomanceTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/PerfomanceTests.cs @@ -6,11 +6,11 @@ using Framework.Database; using SampleSystem.Domain.Employee; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class PerfomanceTests : TestBase +public class PerfomanceTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void GetEmployee_ToManyFilterParameters_CheckTimeTest() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/PrincipalTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/PrincipalTests.cs index 7f0cb5133..4ff731284 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/PrincipalTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/PrincipalTests.cs @@ -3,14 +3,14 @@ using Framework.Authorization.Generated.DTO; using Framework.Core; -using SampleSystem.IntegrationTests.__Support.TestData; - using Anch.SecuritySystem; + +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.WebApiCore.Controllers.Main; namespace SampleSystem.IntegrationTests; -public class PrincipalTests : TestBase +public class PrincipalTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void CreatePrincipal_SaveEventExist() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/PrincipalWithInitTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/PrincipalWithInitTests.cs index d000eecd8..e4c6c29c1 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/PrincipalWithInitTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/PrincipalWithInitTests.cs @@ -5,47 +5,51 @@ using Framework.Database; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; using SampleSystem.Security; using Anch.SecuritySystem; using Anch.SecuritySystem.Validation; +using Framework.AutomationCore.RootServiceProviderContainer; + +using SampleSystem.IntegrationTests._Environment.TestData; + namespace SampleSystem.IntegrationTests; -public class PrincipalWithInitTests : TestBase +public class PrincipalWithInitTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private const string TestPrincipalName = "Duplicate Permission Tester"; private Period testPeriod; - public PrincipalWithInitTests() + protected override async ValueTask InitializeAsync(CancellationToken ct) { this.testPeriod = this.TimeProvider.GetCurrentMonth(); - var buTypeId = this.DataHelper.SaveBusinessUnitType(DefaultConstants.BUSINESS_UNIT_TYPE_COMPANY_ID); + var buTypeId = this.DataManager.SaveBusinessUnitType(DefaultConstants.BUSINESS_UNIT_TYPE_COMPANY_ID); - var luxoftBuId = this.DataHelper.SaveBusinessUnit( + var luxoftBuId = this.DataManager.SaveBusinessUnit( id: DefaultConstants.BUSINESS_UNIT_PARENT_COMPANY_ID, name: DefaultConstants.BUSINESS_UNIT_PARENT_COMPANY_NAME, type: buTypeId); - var costBuId = this.DataHelper.SaveBusinessUnit( + var costBuId = this.DataManager.SaveBusinessUnit( id: DefaultConstants.BUSINESS_UNIT_PARENT_CC_ID, name: DefaultConstants.BUSINESS_UNIT_PARENT_CC_NAME, type: buTypeId, parent: luxoftBuId); - var profitBuId = this.DataHelper.SaveBusinessUnit( + var profitBuId = this.DataManager.SaveBusinessUnit( id: DefaultConstants.BUSINESS_UNIT_PARENT_PC_ID, name: DefaultConstants.BUSINESS_UNIT_PARENT_PC_NAME, type: buTypeId, parent: luxoftBuId); - this.AuthManager.For(TestPrincipalName).SetRole( + await this.AuthManager.For(TestPrincipalName).SetRoleAsync( new SampleSystemTestPermission( SampleSystemSecurityRole.TestPerformance, - new BusinessUnitIdentityDTO(DefaultConstants.BUSINESS_UNIT_PARENT_PC_ID)) { Period = new PermissionPeriod(this.testPeriod.StartDate, this.testPeriod.EndDate) }); + new BusinessUnitIdentityDTO(DefaultConstants.BUSINESS_UNIT_PARENT_PC_ID)) { Period = new PermissionPeriod(this.testPeriod.StartDate, this.testPeriod.EndDate) }, + ct); } [Fact] @@ -98,6 +102,8 @@ public void CreateDuplicatePermission_ValidationError() }; // Assert - Assert.Contains(expectedErrorMessage, Assert.Throws(call).Message); + var ex = Record.Exception(() => call()); + var validationException = Assert.IsType(ex); + Assert.Contains(expectedErrorMessage, validationException.Message); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/RepositoryControllerTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/RepositoryControllerTests.cs index eb9296df1..5421184d2 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/RepositoryControllerTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/RepositoryControllerTests.cs @@ -1,9 +1,9 @@ -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.WebApiCore.Controllers.Main; namespace SampleSystem.IntegrationTests; -public class RepositoryControllerTests : TestBase +public class RepositoryControllerTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public async Task TestLoadFromRepository_CurrentEmployeeLoaded() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/RepositoryWithoutSecurityTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/RepositoryWithoutSecurityTests.cs index 8802889e2..f0591366d 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/RepositoryWithoutSecurityTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/RepositoryWithoutSecurityTests.cs @@ -1,9 +1,9 @@ -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.WebApiCore.Controllers.Main; namespace SampleSystem.IntegrationTests; -public class RepositoryWithoutSecurityTests : TestBase +public class RepositoryWithoutSecurityTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public async Task GetDataFromUnsecurityRepository_DataLoaded() @@ -27,9 +27,9 @@ public async Task GetDataFromUnsecurityRepository_TryLoadWithSecurity_DataLoadFa var controllerEvaluator = this.GetControllerEvaluator(); // Act - Func saveAction = () => controllerEvaluator.EvaluateAsync(c => c.TestFaultSave(default)); + var ex = await Record.ExceptionAsync(() => controllerEvaluator.EvaluateAsync(c => c.TestFaultSave(default))); // Assert - await Assert.ThrowsAsync(saveAction); + Assert.IsType(ex); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/RestrictionRoleTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/RestrictionRoleTests.cs index b45791906..07aa875e6 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/RestrictionRoleTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/RestrictionRoleTests.cs @@ -6,15 +6,16 @@ using SampleSystem.Domain.Directories; using SampleSystem.Domain.Employee; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; using SampleSystem.Security; using SampleSystem.WebApiCore.Controllers.Main; using Anch.SecuritySystem; using Anch.SecuritySystem.Validation; +using SampleSystem.IntegrationTests._Environment.TestData; + namespace SampleSystem.IntegrationTests; -public class RestrictionRoleTests : TestBase +public class RestrictionRoleTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void GetRestrictionObjectsWithRestrictionRole_RestrictionApplied() @@ -63,7 +64,7 @@ public void TryCreateEmptyPermission_PermissionCreated() public void TryCreatePermissionWithCorrectSecurityContext_PermissionCreated() { // Arrange - var businessUnit = this.DataHelper.SaveBusinessUnit(); + var businessUnit = this.DataManager.SaveBusinessUnit(); // Act var action = () => @@ -80,17 +81,18 @@ public void TryCreatePermissionWithCorrectSecurityContext_PermissionCreated() public void TryCreatePermissionWithInvalidSecurityContext_ExceptionRaised() { // Arrange - var location = this.DataHelper.SaveLocation(); + var location = this.DataManager.SaveLocation(); // Act - var action = () => - this.AuthManager.For().SetRole( - new SampleSystemTestPermission( - SampleSystemSecurityRole.RestrictionRole, - location: location)); + var ex = Record.Exception(() => + this.AuthManager.For().SetRole( + new SampleSystemTestPermission( + SampleSystemSecurityRole.RestrictionRole, + location: location))); // Assert - Assert.Contains($"Invalid SecurityContextType: {nameof(Location)}", Assert.Throws(action).Message); + var validationException = Assert.IsType(ex); + Assert.Contains($"Invalid SecurityContextType: {nameof(Location)}", validationException.Message); } [Fact] @@ -165,15 +167,16 @@ public void GetRestrictionObjectsWithConditionRule_RestrictionApplied() public void TryCreatePermissionWithoutRequiredSecurityContext_ExceptionRaised() { // Arrange - var location = this.DataHelper.SaveLocation(); + var location = this.DataManager.SaveLocation(); // Act - var action = () => this.AuthManager.For().SetRole( - new SampleSystemTestPermission(SampleSystemSecurityRole.RequiredRestrictionRole, location: location)); + var ex = Record.Exception(() => this.AuthManager.For().SetRole( + new SampleSystemTestPermission(SampleSystemSecurityRole.RequiredRestrictionRole, location: location))); // Assert + var validationException = Assert.IsType(ex); Assert.Contains( $"{nameof(Framework.Authorization.Domain.Permission)} must contain the required contexts: {nameof(BusinessUnit)}", - Assert.Throws(action).Message); + validationException.Message); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SampleSystem.IntegrationTests.NHibernate.csproj b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SampleSystem.IntegrationTests.NHibernate.csproj index c313772ec..d39c757c8 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SampleSystem.IntegrationTests.NHibernate.csproj +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SampleSystem.IntegrationTests.NHibernate.csproj @@ -6,10 +6,11 @@ + - + all runtime; build; native; contentfiles; analyzers; buildtransitive @@ -17,19 +18,19 @@ - + PreserveNewest - + - + PreserveNewest diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SecurityContextRestrictionFilterTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SecurityContextRestrictionFilterTests.cs index 32b52e9a8..eff658d11 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SecurityContextRestrictionFilterTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SecurityContextRestrictionFilterTests.cs @@ -3,15 +3,16 @@ using SampleSystem.Domain.BU; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; using SampleSystem.Security; using Anch.SecuritySystem; using Anch.SecuritySystem.Validation; +using SampleSystem.IntegrationTests._Environment.TestData; + namespace SampleSystem.IntegrationTests; -public class SecurityContextRestrictionFilterTests : TestBase +public class SecurityContextRestrictionFilterTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private static readonly SecurityRole DefaultSecurityRole = SampleSystemSecurityRole.DefaultRole; @@ -26,13 +27,13 @@ public class SecurityContextRestrictionFilterTests : TestBase private BusinessUnitIdentityDTO buWithAllowedFilter; - public SecurityContextRestrictionFilterTests() + protected override async ValueTask InitializeAsync(CancellationToken ct) { - this.employee = this.DataHelper.SaveEmployee(login: this.employeeLogin); + this.employee = this.DataManager.SaveEmployee(login: this.employeeLogin); - this.defaultBu = this.DataHelper.SaveBusinessUnit(); + this.defaultBu = this.DataManager.SaveBusinessUnit(); - this.buWithAllowedFilter = this.DataHelper.SaveBusinessUnit(allowedForFilterRole: true); + this.buWithAllowedFilter = this.DataManager.SaveBusinessUnit(allowedForFilterRole: true); } [Fact] @@ -41,14 +42,15 @@ public void CreatePermissionWithRestrictionFilter_ApplyInvalidBusinessUnit_Excep // Arrange // Act - var action = () => this.AuthManager.For(this.employee.Id).SetRole( - new SampleSystemTestPermission(SampleSystemSecurityRole.WithRestrictionFilterRole) - { - BusinessUnit = this.defaultBu - }); + var ex = Record.Exception(() => this.AuthManager.For(this.employee.Id).SetRole( + new SampleSystemTestPermission(SampleSystemSecurityRole.WithRestrictionFilterRole) + { + BusinessUnit = this.defaultBu + })); // Assert - Assert.Contains($"SecurityContext: '{this.defaultBu.Id}' denied by filter", Assert.Throws(action).Message); + var validationException = Assert.IsType(ex); + Assert.Contains($"SecurityContext: '{this.defaultBu.Id}' denied by filter", validationException.Message); } [Fact] diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SecurityPathTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SecurityPathTests.cs index 0b0082bba..89e570512 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SecurityPathTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SecurityPathTests.cs @@ -7,18 +7,18 @@ using SampleSystem.Domain.Employee; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.Security; namespace SampleSystem.IntegrationTests; -public class SecurityPathTests : TestBase +public class SecurityPathTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void SecurityPathWithContext_EmployeeWithoutContextRestrictions_EmployeeShouldHaveAccess() { // Arrange - var employeeIdentity = this.DataHelper.SaveEmployee(Guid.NewGuid()); + var employeeIdentity = this.DataManager.SaveEmployee(Guid.NewGuid()); // Act var result = this.Evaluate( diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SecurityRuleTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SecurityRuleTests.cs index c04da0fdc..f62182a17 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SecurityRuleTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SecurityRuleTests.cs @@ -8,13 +8,14 @@ using Microsoft.Extensions.DependencyInjection; using SampleSystem.Domain.Employee; -using SampleSystem.IntegrationTests.__Support.TestData; using Anch.SecuritySystem.AccessDenied; +using SampleSystem.IntegrationTests._Environment.TestData; + namespace SampleSystem.IntegrationTests; -public class SecurityRuleTests : TestBase +public class SecurityRuleTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public async Task ApplyExceptRule_CurrentUserExcepted() @@ -22,9 +23,9 @@ public async Task ApplyExceptRule_CurrentUserExcepted() // Arrange var testSecurityRule = SecurityRole.Administrator.Except(DomainSecurityRule.CurrentUser); - var testOtherEmployeeId = this.DataHelper.SaveEmployee().Id; + var testOtherEmployeeId = this.DataManager.SaveEmployee().Id; - var currentEmployeeId = this.DataHelper.GetCurrentEmployee().Id; + var currentEmployeeId = this.DataManager.GetCurrentEmployee().Id; var testObjectIdents = await this.EvaluateAsync( DBSessionMode.Write, @@ -63,16 +64,17 @@ public void ApplyOverrideFaultMessageRule_FaultMessageChanged() var testSecurityRule = DomainSecurityRule.AccessDenied.WithOverrideAccessDeniedMessage(faultMessage); // Act - var action = () => this.Evaluate( - DBSessionMode.Read, - ctx => - { - var bll = ctx.Logics.EmployeeFactory.Create(testSecurityRule); + var ex = Record.Exception(() => this.Evaluate( + DBSessionMode.Read, + ctx => + { + var bll = ctx.Logics.EmployeeFactory.Create(testSecurityRule); - bll.CheckAccess(ctx.CurrentEmployeeSource.CurrentUser); - }); + bll.CheckAccess(ctx.CurrentEmployeeSource.CurrentUser); + })); // Assert - Assert.Equal(faultMessage, Assert.Throws(action).Message); + var accessDeniedException = Assert.IsType(ex); + Assert.Equal(faultMessage, accessDeniedException.Message); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SequenceBllTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SequenceBllTests.cs index 033f42ae2..c3b6f92ea 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SequenceBllTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SequenceBllTests.cs @@ -2,11 +2,11 @@ using Framework.Configuration.BLL; using Framework.Database; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class SequenceBllTests : TestBase +public class SequenceBllTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void GetNextNumber_TwoCallsInParallelTransactions_ShouldGiveDifferentNumbers() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SqlParserTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SqlParserTests.cs index abf9d326e..53c224889 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SqlParserTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SqlParserTests.cs @@ -4,12 +4,12 @@ using SampleSystem.Domain; using SampleSystem.Domain.Employee; using SampleSystem.Domain.HRDepartment; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.WebApiCore.Controllers.Main; namespace SampleSystem.IntegrationTests; -public class SqlParserTests : TestBase +public class SqlParserTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void SaveNullIntoNotNullProperty_RequiredConstraintDALException() @@ -18,10 +18,11 @@ public void SaveNullIntoNotNullProperty_RequiredConstraintDALException() var testObject = new SqlParserTestObj(); // Act - Action action = () => this.EvaluateWrite(context => { context.Logics.SqlParserTestObj.Save(testObject); }); + var ex = Record.Exception(() => this.EvaluateWrite(context => { context.Logics.SqlParserTestObj.Save(testObject); })); // Assert - Assert.Contains("The field \'notNullColumn\' of type SqlParserTestObj must be initialized", Assert.Throws(action).Message); + var requiredConstraintException = Assert.IsType(ex); + Assert.Contains("The field \'notNullColumn\' of type SqlParserTestObj must be initialized", requiredConstraintException.Message); } [Fact] @@ -32,15 +33,16 @@ public void SaveNotUniqueProperty_UniqueViolationConstraintDALException() var testObject2 = new SqlParserTestObj { UniqueColumn = "1", NotNullColumn = "2" }; // Act - Action action = () => this.EvaluateWrite( - context => - { - context.Logics.SqlParserTestObj.Save(testObject1); - context.Logics.SqlParserTestObj.Save(testObject2); - }); + var ex = Record.Exception(() => this.EvaluateWrite( + context => + { + context.Logics.SqlParserTestObj.Save(testObject1); + context.Logics.SqlParserTestObj.Save(testObject2); + })); // Assert - Assert.Contains("SqlParserTestObj with same:\'UniqueColumn\' already exists", Assert.Throws(action).Message); + var uniqueViolationException = Assert.IsType(ex); + Assert.Contains("SqlParserTestObj with same:\'UniqueColumn\' already exists", uniqueViolationException.Message); } [Fact] @@ -58,14 +60,15 @@ public void RemoveLinkedObject_RemoveLinkedObjectsDALException() }); // Act - Action action = () => this.EvaluateWrite( - context => - { - context.Logics.SqlParserTestObj.Remove(testObject); - }); + var ex = Record.Exception(() => this.EvaluateWrite( + context => + { + context.Logics.SqlParserTestObj.Remove(testObject); + })); // Assert - Assert.Contains($"{nameof(SqlParserTestObj)} cannot be removed because it is used in {nameof(SqlParserTestObjContainer)}", Assert.Throws(action).Message); + var removeLinkedObjectsException = Assert.IsType(ex); + Assert.Contains($"{nameof(SqlParserTestObj)} cannot be removed because it is used in {nameof(SqlParserTestObjContainer)}", removeLinkedObjectsException.Message); } [Fact] @@ -75,29 +78,30 @@ public void RemoveHRDepartment_HasEmployeeWithHRDepartment_CorrectExceptionMessa var employeeController = this.MainWebApi.Employee; var hRDepartmentController = this.GetControllerEvaluator(); - var buTypeId = this.DataHelper.SaveBusinessUnitType(DefaultConstants.BUSINESS_UNIT_TYPE_COMPANY_ID); + var buTypeId = this.DataManager.SaveBusinessUnitType(DefaultConstants.BUSINESS_UNIT_TYPE_COMPANY_ID); - var luxoftBuId = this.DataHelper.SaveBusinessUnit( + var luxoftBuId = this.DataManager.SaveBusinessUnit( id: DefaultConstants.BUSINESS_UNIT_PARENT_COMPANY_ID, name: DefaultConstants.BUSINESS_UNIT_PARENT_COMPANY_NAME, type: buTypeId); - var costBuId = this.DataHelper.SaveBusinessUnit( + var costBuId = this.DataManager.SaveBusinessUnit( id: DefaultConstants.BUSINESS_UNIT_PARENT_CC_ID, name: DefaultConstants.BUSINESS_UNIT_PARENT_CC_NAME, type: buTypeId, parent: luxoftBuId); - var location = this.DataHelper.SaveLocation(name: "testLocation"); + var location = this.DataManager.SaveLocation(name: "testLocation"); - var employeeIdentity = this.DataHelper.SaveEmployee(login: "value", coreBusinessUnit: costBuId, location: location); + var employeeIdentity = this.DataManager.SaveEmployee(login: "value", coreBusinessUnit: costBuId, location: location); var fullEmployee = employeeController.Evaluate(c => c.GetFullEmployee(employeeIdentity)); // Act - Action action = () => hRDepartmentController.Evaluate(c => c.RemoveHRDepartment(fullEmployee.HRDepartment.Identity)); + var ex = Record.Exception(() => hRDepartmentController.Evaluate(c => c.RemoveHRDepartment(fullEmployee.HRDepartment.Identity))); // Assert - Assert.Equal($"{nameof(HRDepartment)} cannot be removed because it is used in {nameof(Employee)}", Assert.Throws(action).Message); + var removeLinkedObjectsException = Assert.IsType(ex); + Assert.Equal($"{nameof(HRDepartment)} cannot be removed because it is used in {nameof(Employee)}", removeLinkedObjectsException.Message); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SubscriptionCustomNotPersistentModelTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SubscriptionCustomNotPersistentModelTests.cs index f248f9958..440efa0dc 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SubscriptionCustomNotPersistentModelTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/SubscriptionCustomNotPersistentModelTests.cs @@ -2,12 +2,12 @@ using Framework.Database; using SampleSystem.Domain.Directories; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.Subscriptions.Metadata.DomainChangedByRecipients.NotPersistentCustomModel; namespace SampleSystem.IntegrationTests; -public class SubscriptionCustomNotPersistentModelTests : TestBase +public class SubscriptionCustomNotPersistentModelTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void CustomNotPersistentNotificationModel_Always_ShouldNotThrowException() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/Subscriptions_Metadata/MetadataSubscriptionSystemServiceTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/Subscriptions_Metadata/MetadataSubscriptionSystemServiceTests.cs index 0f906955d..2b04f6dca 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/Subscriptions_Metadata/MetadataSubscriptionSystemServiceTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/Subscriptions_Metadata/MetadataSubscriptionSystemServiceTests.cs @@ -5,13 +5,13 @@ using SampleSystem.Domain.Employee; using SampleSystem.Domain.Models.Custom; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests.Subscriptions_Metadata; -public sealed class MetadataSubscriptionSystemServiceTests : TestBase +public sealed class MetadataSubscriptionSystemServiceTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { - public MetadataSubscriptionSystemServiceTests() => this.GetNotifications().Clear(); + protected override async ValueTask InitializeAsync(CancellationToken ct) => this.GetNotifications().Clear(); [Fact] public void SubscriptionFromMetadataShouldBeSent() @@ -20,7 +20,7 @@ public void SubscriptionFromMetadataShouldBeSent() var employee = this.CreateEmployee(); // Act - var results = this.DataHelper.ProcessSubscription(employee, employee); + var results = this.DataManager.ProcessSubscription(employee, employee); var errors = results.GetErrors().ToList(); var expectedNotifications = this.GetNotifications() @@ -36,11 +36,11 @@ public void SubscriptionFromMetadataShouldBeSent() public void RazorTemplateImpl_SubscriptionFromMetadataShouldBeSent() { // Arrange - var employee = this.DataHelper.SaveEmployee("Chuck Norris"); + var employee = this.DataManager.SaveEmployee("Chuck Norris"); var message = @"String.Concat it is good choice for Chuck Norris."; // Act - var results = this.DataHelper.ProcessSubscription(employee, employee); + var results = this.DataManager.ProcessSubscription(employee, employee); var errors = results.GetErrors().ToList(); var expectedNotifications = this.GetNotifications() @@ -64,7 +64,7 @@ public void LocalRazorTemplate_SubscriptionFromMetadataShouldBeSent() var message = $"

Hi there!!!

{Environment.NewLine}My test employee Name: John Doe {Environment.NewLine}Date: 21 Oct 2015"; // Act - var results = this.DataHelper.ProcessSubscription(employee, employee); + var results = this.DataManager.ProcessSubscription(employee, employee); var errors = results.GetErrors().ToList(); var expectedNotifications = this.GetNotifications() @@ -88,7 +88,7 @@ public void AttachTest() var content = Encoding.UTF8.GetBytes("Hello world!"); // Act - this.DataHelper.ProcessSubscription(employee, employee); + this.DataManager.ProcessSubscription(employee, employee); var expectedNotifications = this.GetNotifications() .Where(n => n.From == "Attachment@luxoft.com"); @@ -112,7 +112,7 @@ public void AttachTemplateEvaluatorTest() var content = "Hello world! John Doe "; // Act - this.DataHelper.ProcessSubscription(employee, employee); + this.DataManager.ProcessSubscription(employee, employee); var expectedNotifications = this.GetNotifications().Where(n => n.From == "AttachmentTemplateEvaluator@luxoft.com"); @@ -135,7 +135,7 @@ public void AttachInlinedTest() var messageTemplate = @" John Doe
"; // Act - this.DataHelper.ProcessSubscription(employee, employee); + this.DataManager.ProcessSubscription(employee, employee); var expectedNotifications = this.GetNotifications() .Where(n => n.From == "InlineAttach@luxoft.com"); @@ -153,7 +153,7 @@ public void DateModelCreateSubscriptionTest() // Arrange // Act - this.DataHelper.ProcessSubscription(null, new DateModel { Year = 2019 }); + this.DataManager.ProcessSubscription(null, new DateModel { Year = 2019 }); var expectedNotifications = this.GetNotifications() .Where(n => n.From == "DateModelCreateSampleSystem@luxoft.com"); @@ -164,7 +164,7 @@ public void DateModelCreateSubscriptionTest() private Employee CreateEmployee() { - var employee = this.DataHelper.SaveEmployee("John Doe"); + var employee = this.DataManager.SaveEmployee("John Doe"); return employee; } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/TransactionFlushBeforeCommit.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/TransactionFlushBeforeCommit.cs index 52d2c36d5..40fe6c6ac 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/TransactionFlushBeforeCommit.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/TransactionFlushBeforeCommit.cs @@ -3,11 +3,11 @@ using SampleSystem.Domain.Employee; using SampleSystem.Domain.ForUpdate; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class TransactionFlushBeforeCommit : TestBase +public class TransactionFlushBeforeCommit(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void ShouldNotConsiderChangesWhileTransactionIsNotCommited() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/UniqueGroupTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/UniqueGroupTests.cs index 3264c809c..d02da67b1 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/UniqueGroupTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/UniqueGroupTests.cs @@ -1,24 +1,25 @@ using Framework.Database.DALExceptions; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests; -public class UniqueGroupTests : TestBase +public class UniqueGroupTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void UniqueGroup_NonUniqueEntityCreated_ErrorUsesCustomName() { // Arrange - var role = this.DataHelper.SaveEmployeeRole(); - var roleDegree = this.DataHelper.SaveEmployeeRoleDegree(); + var role = this.DataManager.SaveEmployeeRole(); + var roleDegree = this.DataManager.SaveEmployeeRoleDegree(); - this.DataHelper.SaveRoleRoleDegreeLink(role, roleDegree); + this.DataManager.SaveRoleRoleDegreeLink(role, roleDegree); // Act - var action = new Action(() => this.DataHelper.SaveRoleRoleDegreeLink(role, roleDegree)); + var ex = Record.Exception(() => this.DataManager.SaveRoleRoleDegreeLink(role, roleDegree)); // Assert - Assert.Equal("Role-Seniority link with same:'Role,Seniority' already exists", Assert.Throws(action).Message); + var uniqueViolationException = Assert.IsType(ex); + Assert.Equal("Role-Seniority link with same:'Role,Seniority' already exists", uniqueViolationException.Message); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/UpdateTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/UpdateTests.cs index d9bb6341a..718d96859 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/UpdateTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/UpdateTests.cs @@ -4,12 +4,12 @@ using Framework.Core; using SampleSystem.Generated.DTO; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.WebApiCore.Controllers.Main; namespace SampleSystem.IntegrationTests; -public class UpdateTests : TestBase +public class UpdateTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void ExampleContainer_UpdatePropertyChanged1() diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ValidationTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ValidationTests.cs index 4b898f5cf..496f3a8ab 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ValidationTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/ValidationTests.cs @@ -1,22 +1,22 @@ -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using ValidationException = Framework.Validation.ValidationException; namespace SampleSystem.IntegrationTests; -public class ValidationTests : TestBase +public class ValidationTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void ValidateByDB_ValidationException() { // Arrange - this.DataHelper.SaveEmployee("John Doe", "JD"); + this.DataManager.SaveEmployee("John Doe", "JD"); // Act - Action call = () => this.DataHelper.SaveEmployee("John Doe", "JD"); + var ex = Record.Exception(() => this.DataManager.SaveEmployee("John Doe", "JD")); // Assert - Assert.Throws(call); + Assert.IsType(ex); } [Fact] @@ -25,10 +25,11 @@ public void ValidateByClassAttribute_ValidationException() // Arrange // Act - Action call = () => this.DataHelper.SaveEmployee(pin: 1234); + var ex = Record.Exception(() => this.DataManager.SaveEmployee(pin: 1234)); // Assert - Assert.Equal("Employee Pin could not be set as '1234'", Assert.Throws(call).Message); + var validationException = Assert.IsType(ex); + Assert.Equal("Employee Pin could not be set as '1234'", validationException.Message); } [Fact] @@ -36,13 +37,14 @@ public void ValidateByConcreteValidator_ValidationException() { // Arrange var externalId = new Random().Next(); - this.DataHelper.SaveEmployee(externalId: externalId); + this.DataManager.SaveEmployee(externalId: externalId); // Act - Action call = () => this.DataHelper.SaveEmployee(externalId: externalId); + var ex = Record.Exception(() => this.DataManager.SaveEmployee(externalId: externalId)); // Assert - Assert.Equal($"Employee with ExternalId '{externalId}' already exists.", Assert.Throws(call).Message); + var validationException = Assert.IsType(ex); + Assert.Equal($"Employee with ExternalId '{externalId}' already exists.", validationException.Message); } [Fact] @@ -50,13 +52,14 @@ public void ValidateByGlobalValidator_ValidationException() { // Arrange var pin = new Random().Next(); - this.DataHelper.SaveEmployee(pin: pin); + this.DataManager.SaveEmployee(pin: pin); // Act - Action call = () => this.DataHelper.SaveEmployee(pin: pin); + var ex = Record.Exception(() => this.DataManager.SaveEmployee(pin: pin)); // Assert - Assert.Equal($"Employee with Pin '{pin}' already exists.", Assert.Throws(call).Message); + var validationException = Assert.IsType(ex); + Assert.Equal($"Employee with Pin '{pin}' already exists.", validationException.Message); } [Fact] @@ -67,7 +70,7 @@ public void Validate_HasInvalidVirtualProperty_ShouldNotThrow() var invalidDate = DateTime.MinValue; // Act - Action call = () => this.DataHelper.SaveEmployee(externalId: externalId, nonValidateVirtualProp: invalidDate); + Action call = () => this.DataManager.SaveEmployee(externalId: externalId, nonValidateVirtualProp: invalidDate); // Assert call(); @@ -81,9 +84,10 @@ public void Validate_HasInvalidVirtualPropertyMarkedWithAttribute_ShouldThrow() var invalidDate = DateTime.MinValue; // Act - Action call = () => this.DataHelper.SaveEmployee(externalId: externalId, validateVirtualProp: invalidDate); + var ex = Record.Exception(() => this.DataManager.SaveEmployee(externalId: externalId, validateVirtualProp: invalidDate)); // Assert - Assert.Equal("Employee has ValidateVirtualProp value was too overflow for a DateTime", Assert.Throws(call).Message); + var validationException = Assert.IsType(ex); + Assert.Equal("Employee has ValidateVirtualProp value was too overflow for a DateTime", validationException.Message); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/VirtualPermissionTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/VirtualPermissionTests.cs index 2cc236498..da5d2ec91 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/VirtualPermissionTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/VirtualPermissionTests.cs @@ -3,24 +3,24 @@ using SampleSystem.Domain.BU; using SampleSystem.Domain.Enums; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; using SampleSystem.Security; namespace SampleSystem.IntegrationTests; -public class VirtualPermissionTests : TestBase +public class VirtualPermissionTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private (string UserLogin, Guid BuId, Guid EmployeeId)[] Datas; - public VirtualPermissionTests() => + protected override async ValueTask InitializeAsync(CancellationToken ct) => this.Datas = new[] { "testEmployeeLogin", "otherTestEmployeeLogin" } .Select( userLogin => { - var buId = this.DataHelper.SaveBusinessUnit().Id; + var buId = this.DataManager.SaveBusinessUnit().Id; - var employeeId = this.DataHelper.SaveEmployee(login: userLogin).Id; + var employeeId = this.DataManager.SaveEmployee(login: userLogin).Id; this.Evaluate( DBSessionMode.Write, diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/WebApi/EmployeeTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/WebApi/EmployeeTests.cs index a8a036393..e270ed240 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/WebApi/EmployeeTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/WebApi/EmployeeTests.cs @@ -1,14 +1,14 @@ -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; namespace SampleSystem.IntegrationTests.WebApi; -public class WebApiTests : TestBase +public class WebApiTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { [Fact] public void WebApi_CallMethod() { // Arrange - var employeeIdentity = this.DataHelper.SaveEmployee(Guid.NewGuid()); + var employeeIdentity = this.DataManager.SaveEmployee(Guid.NewGuid()); var employeeController = this.MainWebApi.Employee; diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/WrongSecurityMessageTests.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/WrongSecurityMessageTests.cs index 7866012bc..69f3567e8 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/WrongSecurityMessageTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/WrongSecurityMessageTests.cs @@ -5,20 +5,22 @@ using Anch.SecuritySystem; using SampleSystem.Domain.Employee; -using SampleSystem.IntegrationTests.__Support.TestData; using SampleSystem.Security; using Anch.SecuritySystem.AccessDenied; +using SampleSystem.IntegrationTests._Environment.TestData; + namespace SampleSystem.IntegrationTests; -public class WrongSecurityMessageTests : TestBase +public class WrongSecurityMessageTests(IServiceProvider rootServiceProvider) : TestBase(rootServiceProvider) { private static readonly string TestPrincipalName = TextRandomizer.RandomString(10); private static readonly Guid TestPrincipalId = Guid.NewGuid(); - public WrongSecurityMessageTests() => this.DataHelper.SaveEmployee(login: TestPrincipalName, id: TestPrincipalId); + protected override async ValueTask InitializeAsync(CancellationToken ct) => + this.DataManager.SaveEmployee(login: TestPrincipalName, id: TestPrincipalId); [Fact] public void UseWrongSecurityMode_ErrorMessageCorrected() => this.UseSecurityRule_WithoutSecurity_ErrorMessageCorrected(SecurityRule.Edit); @@ -34,14 +36,15 @@ private void UseSecurityRule_WithoutSecurity_ErrorMessageCorrected(SecurityRule //Arrange // Act - var action = () => this.Evaluate( - DBSessionMode.Read, - TestPrincipalName, - ctx => ctx.Logics.EmployeeFactory.Create(securityRule).CheckAccess(ctx.CurrentEmployeeSource.CurrentUser)); + var ex = Record.Exception(() => this.Evaluate( + DBSessionMode.Read, + TestPrincipalName, + ctx => ctx.Logics.EmployeeFactory.Create(securityRule).CheckAccess(ctx.CurrentEmployeeSource.CurrentUser))); // Assert + var accessDeniedException = Assert.IsType(ex); Assert.Equal( $"You have no permissions to access object with type = '{nameof(Employee)}' (id = '{TestPrincipalId}', securityRule = '{securityRule}')", - Assert.Throws(action).Message); + accessDeniedException.Message); } } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/EmptySchemaInitializer.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/EmptySchemaInitializer.cs new file mode 100644 index 000000000..4f89bf51b --- /dev/null +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/EmptySchemaInitializer.cs @@ -0,0 +1,22 @@ +using Anch.Core; + +using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; +using Framework.Database.NHibernate.DBGenerator; + +using SampleSystem.DbGenerate.NHibernate; + +namespace SampleSystem.IntegrationTests._Environment; + +public class EmptySchemaInitializer(IDatabaseContext databaseContext) : IInitializer +{ + public async Task Initialize(CancellationToken cancellationToken) + { + var generator = new DbGeneratorTest(); + + // Act + generator.GenerateAllDB( + databaseContext.Main.DataSource, + databaseContext.Main.DatabaseName, + credential: DbUserCredential.Create(databaseContext.Main.UserId, databaseContext.Main.Password)); + } +} diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/FluentMigration/InitNumberInDomainObjectEventMigration.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/FluentMigration/InitNumberInDomainObjectEventMigration.cs similarity index 88% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/FluentMigration/InitNumberInDomainObjectEventMigration.cs rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/FluentMigration/InitNumberInDomainObjectEventMigration.cs index b8f724e7f..edb9c6a0a 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/FluentMigration/InitNumberInDomainObjectEventMigration.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/FluentMigration/InitNumberInDomainObjectEventMigration.cs @@ -3,7 +3,7 @@ using Framework.Configuration.Domain; -namespace SampleSystem.IntegrationTests.__Support.FluentMigration; +namespace SampleSystem.IntegrationTests._Environment.FluentMigration; [Migration(2022_11_18_16_09_00)] public class InitNumberInDomainObjectEventMigration : Migration diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/NHibTestEnvironment.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/NHibTestEnvironment.cs new file mode 100644 index 000000000..4848e9a02 --- /dev/null +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/NHibTestEnvironment.cs @@ -0,0 +1,57 @@ +using Anch.Testing.Database.DependencyInjection; +using Anch.Testing.Xunit; + +using Bss.Platform.Events.Abstractions; + +using Framework.Application.Jobs; +using Framework.AutomationCore; +using Framework.AutomationCore.ServiceEnvironment; + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting.Internal; + +using SampleSystem.IntegrationTests._Environment; +using SampleSystem.IntegrationTests._Environment.TestData; +using SampleSystem.IntegrationTests._Environment.TestData.Helpers; +using SampleSystem.IntegrationTests._Environment.Utils; +using SampleSystem.ServiceEnvironment; +using SampleSystem.ServiceEnvironment.DependencyInjection; +using SampleSystem.ServiceEnvironment.Jobs; +using SampleSystem.WebApiCore.Controllers.Main; + +[assembly: AnchTestFramework] + +namespace SampleSystem.IntegrationTests._Environment; + +public class NHibTestEnvironment : BssTestEnvironment +{ + private const string SettingsFileName = "testAppSettings.json"; + protected override IConfiguration Configuration { get; } = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(SettingsFileName, false, true) + .AddJsonFile($"{Environment.MachineName}.{SettingsFileName}", true) + .AddEnvironmentVariables(nameof(SampleSystem)).Build(); + protected override void InitInitializers(IDatabaseTestingSetup setup) => + + setup.SetEmptySchemaInitializer() + .SetTestDataInitializer(); + + + protected override void InitServices(IServiceCollection services) => + + services.AddGeneralDependencyInjection(this.Configuration, new HostingEnvironment(), s => s.AddExtensions(new SampleSystemNHibernateExtension())) + + .AddSingleton() + + .AddIntegrationTests() + + .AddScoped() + + .AddSingleton(new JobImpersonateData("sampleSystemTestJob")) + .AddJobs([typeof(SampleJob).Assembly]) + + .AddTestControllers([typeof(EmployeeController).Assembly]) + + .AddSingleton(); +} diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Scripts/CheckConstraint.sql b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Scripts/CheckConstraint.sql similarity index 100% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Scripts/CheckConstraint.sql rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Scripts/CheckConstraint.sql diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Scripts/Configuration/Configuration.sql b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Scripts/Configuration/Configuration.sql similarity index 100% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Scripts/Configuration/Configuration.sql rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Scripts/Configuration/Configuration.sql diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Scripts/NoCheckConstraint.sql b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Scripts/NoCheckConstraint.sql similarity index 100% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Scripts/NoCheckConstraint.sql rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Scripts/NoCheckConstraint.sql diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Scripts/SampleSystem/Create AncestorChildView.sql b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Scripts/SampleSystem/Create AncestorChildView.sql similarity index 100% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Scripts/SampleSystem/Create AncestorChildView.sql rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Scripts/SampleSystem/Create AncestorChildView.sql diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Scripts/SampleSystem/Sample.sql b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Scripts/SampleSystem/Sample.sql similarity index 100% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Scripts/SampleSystem/Sample.sql rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Scripts/SampleSystem/Sample.sql diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/DefaultConstants.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/DefaultConstants.cs similarity index 98% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/DefaultConstants.cs rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/DefaultConstants.cs index c2f6f5daf..3fb360309 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/DefaultConstants.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/DefaultConstants.cs @@ -1,4 +1,4 @@ -namespace SampleSystem.IntegrationTests.__Support.TestData; +namespace SampleSystem.IntegrationTests._Environment.TestData; public static class DefaultConstants { diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/Helpers/DataHelper.Employee.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/Helpers/DataManager.Employee.cs similarity index 98% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/Helpers/DataHelper.Employee.cs rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/Helpers/DataManager.Employee.cs index ee2ba26ae..c61fe32d0 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/Helpers/DataHelper.Employee.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/Helpers/DataManager.Employee.cs @@ -1,19 +1,18 @@ -using Framework.AutomationCore.RootServiceProviderContainer; +using Anch.SecuritySystem.UserSource; + +using Framework.AutomationCore.RootServiceProviderContainer; using Framework.AutomationCore.Utils; using Framework.Core; - using Microsoft.Extensions.DependencyInjection; using SampleSystem.Domain.Employee; using SampleSystem.Domain.Inline; using SampleSystem.Generated.DTO; -using Anch.SecuritySystem.UserSource; - -namespace SampleSystem.IntegrationTests.__Support.TestData.Helpers; +namespace SampleSystem.IntegrationTests._Environment.TestData.Helpers; -public partial class DataHelper +public partial class DataManager { public EmployeeIdentityDTO SaveEmployee( Guid? id = null, diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/Helpers/DataManager.Init.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/Helpers/DataManager.Init.cs new file mode 100644 index 000000000..81bb4f95b --- /dev/null +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/Helpers/DataManager.Init.cs @@ -0,0 +1,16 @@ +using Framework.AutomationCore.RootServiceProviderContainer; + +using SampleSystem.BLL; + +namespace SampleSystem.IntegrationTests._Environment.TestData.Helpers; + +public partial class DataManager(IServiceProvider rootServiceProvider) : IRootServiceProviderContainer +{ + private Guid GetGuid(Guid? id) + { + id = id ?? Guid.NewGuid(); + return (Guid)id; + } + + public IServiceProvider RootServiceProvider { get; } = rootServiceProvider; +} diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/Helpers/DataHelper.Smo.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/Helpers/DataManager.Smo.cs similarity index 70% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/Helpers/DataHelper.Smo.cs rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/Helpers/DataManager.Smo.cs index 4d4ca2656..28369987b 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/Helpers/DataHelper.Smo.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/Helpers/DataManager.Smo.cs @@ -1,8 +1,10 @@ -using Microsoft.SqlServer.Management.Smo; +using Framework.AutomationCore.RootServiceProviderContainer; -namespace SampleSystem.IntegrationTests.__Support.TestData.Helpers; +using Microsoft.SqlServer.Management.Smo; -public partial class DataHelper +namespace SampleSystem.IntegrationTests._Environment.TestData.Helpers; + +public partial class DataManager { public Table GetTable(string databaseName, string tableName, string schema = "app") { diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/Helpers/DataHelper.Subscriptions.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/Helpers/DataManager.Subscriptions.cs similarity index 85% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/Helpers/DataHelper.Subscriptions.cs rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/Helpers/DataManager.Subscriptions.cs index b12ac7be5..0c5457944 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/Helpers/DataHelper.Subscriptions.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/Helpers/DataManager.Subscriptions.cs @@ -5,9 +5,9 @@ using Microsoft.Extensions.DependencyInjection; -namespace SampleSystem.IntegrationTests.__Support.TestData.Helpers; +namespace SampleSystem.IntegrationTests._Environment.TestData.Helpers; -public partial class DataHelper +public partial class DataManager { public List> ProcessSubscription(T? prev, T? next) diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/Helpers/DataHelper.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/Helpers/DataManager.cs similarity index 98% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/Helpers/DataHelper.cs rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/Helpers/DataManager.cs index 90e68fe01..944fdea1e 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/Helpers/DataHelper.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/Helpers/DataManager.cs @@ -14,9 +14,9 @@ using SampleSystem.Generated.DTO; using SampleSystem.WebApiCore.Controllers.Main; -namespace SampleSystem.IntegrationTests.__Support.TestData.Helpers; +namespace SampleSystem.IntegrationTests._Environment.TestData.Helpers; -public partial class DataHelper +public partial class DataManager { public CountryIdentityDTO SaveCountry( Guid? id = null, @@ -433,9 +433,9 @@ public CompanyLegalEntityIdentityDTO SaveCompanyLegalEntity( if (legal == null) { - CompanyLegalEntity parentDomainObject = (parent == null) - ? null - : context.Logics.CompanyLegalEntity.GetById(parent.Value.Id); + var parentDomainObject = (parent == null) + ? null + : context.Logics.CompanyLegalEntity.GetById(parent.Value.Id); legal = new CompanyLegalEntity { diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/SampleSystemTestPermission.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/SampleSystemTestPermission.cs similarity index 97% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/SampleSystemTestPermission.cs rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/SampleSystemTestPermission.cs index dadb604ce..6a5750ccb 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/SampleSystemTestPermission.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/SampleSystemTestPermission.cs @@ -1,4 +1,6 @@ using Anch.Core; +using Anch.SecuritySystem; +using Anch.SecuritySystem.Testing; using SampleSystem.Domain.BU; using SampleSystem.Domain.Directories; @@ -6,10 +8,7 @@ using SampleSystem.Domain.MU; using SampleSystem.Generated.DTO; -using Anch.SecuritySystem; -using Anch.SecuritySystem.Testing; - -namespace SampleSystem.IntegrationTests.__Support.TestData; +namespace SampleSystem.IntegrationTests._Environment.TestData; public class SampleSystemTestPermission : TestPermission { diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/TestBase.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/TestBase.cs new file mode 100644 index 000000000..69ac10474 --- /dev/null +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/TestBase.cs @@ -0,0 +1,36 @@ +using Anch.SecuritySystem.Testing; + +using Framework.AutomationCore; +using Framework.AutomationCore.ServiceEnvironment; + +using Microsoft.Extensions.DependencyInjection; + +using SampleSystem.BLL; +using SampleSystem.IntegrationTests._Environment.TestData.Helpers; +using SampleSystem.IntegrationTests._Environment.WebApi; +using SampleSystem.WebApiCore.Controllers.Main; + +namespace SampleSystem.IntegrationTests._Environment.TestData; + +public class TestBase(IServiceProvider rootServiceProvider) : IntegrationTestBase(rootServiceProvider), IAsyncLifetime +{ + public MainWebApi MainWebApi => new(this.RootServiceProvider); + + public MainAuditWebApi MainAuditWebApi => new(this.RootServiceProvider); + + protected DataManager DataManager => this.RootServiceProvider.GetRequiredService(); + + protected RootAuthManager AuthManager => this.RootServiceProvider.GetRequiredService(); + + protected ControllerEvaluator GetAuthControllerEvaluator(string? principalName = null) => + this.GetControllerEvaluator(principalName); + + protected ControllerEvaluator GetConfigurationControllerEvaluator(string? principalName = null) => + this.GetControllerEvaluator(principalName); + + protected virtual ValueTask InitializeAsync(CancellationToken ct) => ValueTask.CompletedTask; + + ValueTask IAsyncLifetime.InitializeAsync() => this.InitializeAsync(TestContext.Current.CancellationToken); + + ValueTask IAsyncDisposable.DisposeAsync() => ValueTask.CompletedTask; +} diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/TestDataInitializer.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/TestDataInitializer.cs similarity index 82% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/TestDataInitializer.cs rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/TestDataInitializer.cs index 6c95e61b5..7ac03bd9f 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/TestDataInitializer.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/TestData/TestDataInitializer.cs @@ -1,30 +1,31 @@ -using Framework.AutomationCore.Settings; +using Anch.Core; +using Anch.SecuritySystem; +using Anch.SecuritySystem.Services; +using Anch.SecuritySystem.Testing; + +using Framework.AutomationCore.Settings; using Microsoft.Extensions.Options; using SampleSystem.Domain.Enums; using SampleSystem.Domain.Inline; -using SampleSystem.IntegrationTests.__Support.TestData.Helpers; +using SampleSystem.IntegrationTests._Environment.TestData.Helpers; using SampleSystem.ServiceEnvironment; -using Anch.SecuritySystem; -using Anch.SecuritySystem.Services; -using Anch.SecuritySystem.Testing; - -namespace SampleSystem.IntegrationTests.__Support.TestData; +namespace SampleSystem.IntegrationTests._Environment.TestData; public class TestDataInitializer( SampleSystemInitializer mainInitializer, RootAuthManager authManager, - DataHelper dataHelper, + DataManager dataManager, IOptions settings, - IRootImpersonateService rootImpersonateService) + IRootImpersonateService rootImpersonateService) : IInitializer { - public async Task InitializeAsync(CancellationToken cancellationToken) => + public async Task Initialize(CancellationToken cancellationToken) => await rootImpersonateService - .WithImpersonateAsync(nameof(TestDataInitializer), async () => await this.InitializeAsyncInternal(cancellationToken)); + .WithImpersonateAsync(nameof(TestDataInitializer), async () => await this.InitializeInternal(cancellationToken)); - public async Task InitializeAsyncInternal(CancellationToken cancellationToken) + public async Task InitializeInternal(CancellationToken cancellationToken) { await mainInitializer.InitializeAsync(cancellationToken); @@ -36,7 +37,7 @@ public async Task InitializeAsyncInternal(CancellationToken cancellationToken) var integrationTestUserName = settings.Value.IntegrationTestUserName; - dataHelper.SaveEmployee( + dataManager.SaveEmployee( id: DefaultConstants.EMPLOYEE_MY_ID, nameEng: new Fio { FirstName = DefaultConstants.EMPLOYEE_MY_NAME, LastName = DefaultConstants.EMPLOYEE_MY_NAME }, login: integrationTestUserName); @@ -45,7 +46,7 @@ public async Task InitializeAsyncInternal(CancellationToken cancellationToken) foreach (var localAdmin in settings.Value.LocalAdmins) { - dataHelper.SaveEmployee(login: localAdmin); + dataManager.SaveEmployee(login: localAdmin); await authManager.For(localAdmin).SetRoleAsync(SecurityRole.Administrator, cancellationToken); } @@ -53,16 +54,16 @@ public async Task InitializeAsyncInternal(CancellationToken cancellationToken) private void FillMainData() { - dataHelper.SaveCountry( + dataManager.SaveCountry( id: DefaultConstants.COUNTRY_RUSSIA_ID, name: DefaultConstants.COUNTRY_RUSSIA_NAME, nativeName: DefaultConstants.COUNTRY_RUSSIA_NATIVE_NAME, code: DefaultConstants.COUNTRY_RUSSIA_CODE, culture: "ru-RU"); - dataHelper.SaveLocation(id: DefaultConstants.LOCATION_PARENT_ID, name: DefaultConstants.LOCATION_PARENT_NAME); + dataManager.SaveLocation(id: DefaultConstants.LOCATION_PARENT_ID, name: DefaultConstants.LOCATION_PARENT_NAME); - var company = dataHelper.SaveBusinessUnitType( + var company = dataManager.SaveBusinessUnitType( DefaultConstants.BUSINESS_UNIT_TYPE_COMPANY_ID, DefaultConstants.BUSINESS_UNIT_TYPE_COMPANY_NAME, isAdministrative: false, @@ -70,7 +71,7 @@ private void FillMainData() canBeLinkedToDepartment: false, canBeResourcePool: false, needVertical: false); - var lob = dataHelper.SaveBusinessUnitType( + var lob = dataManager.SaveBusinessUnitType( DefaultConstants.BUSINESS_UNIT_TYPE_LOB_ID, DefaultConstants.BUSINESS_UNIT_TYPE_LOB_NAME, projectStartAllowed: true, @@ -78,7 +79,7 @@ private void FillMainData() canBeResourcePool: true, needVertical: false); - var businessSegment = dataHelper.SaveBusinessUnitType( + var businessSegment = dataManager.SaveBusinessUnitType( DefaultConstants.BUSINESS_UNIT_TYPE_BUSINESS_SEGMENT_ID, DefaultConstants.BUSINESS_UNIT_TYPE_BUSINESS_SEGMENT_NAME, possibleStartDate: PossibleStartDate.FinYearStart, @@ -94,7 +95,7 @@ private void FillMainData() canBeNewBusiness: false, possibleParents: [company]); - var account = dataHelper.SaveBusinessUnitType( + var account = dataManager.SaveBusinessUnitType( DefaultConstants.BUSINESS_UNIT_TYPE_ACCOUNT_ID, DefaultConstants.BUSINESS_UNIT_TYPE_ACCOUNT_NAME, possibleStartDate: PossibleStartDate.AnyDay, @@ -116,21 +117,21 @@ private void FillMainData() possibleParents: [businessSegment, lob, company], transferTo: [businessSegment, lob, company]); - dataHelper.SaveBusinessUnitType( + dataManager.SaveBusinessUnitType( DefaultConstants.BUSINESS_UNIT_TYPE_ADMIN_COMMERCIAL_ID, DefaultConstants.BUSINESS_UNIT_TYPE_ADMIN_COMMERCIAL_NAME, projectStartAllowed: true, canBeLinkedToDepartment: true, canBeResourcePool: true, needVertical: false); - dataHelper.SaveBusinessUnitType( + dataManager.SaveBusinessUnitType( DefaultConstants.BUSINESS_UNIT_TYPE_ADMIN_SERVICES_ID, DefaultConstants.BUSINESS_UNIT_TYPE_ADMIN_SERVICES_NAME, projectStartAllowed: true, canBeLinkedToDepartment: true, canBeResourcePool: true, needVertical: false); - dataHelper.SaveBusinessUnitType( + dataManager.SaveBusinessUnitType( DefaultConstants.BUSINESS_UNIT_TYPE_DIVISION_ID, DefaultConstants.BUSINESS_UNIT_TYPE_DIVISION_NAME, projectStartAllowed: true, @@ -139,7 +140,7 @@ private void FillMainData() needVertical: false, possibleParents: [company, account]); - dataHelper.SaveBusinessUnitType( + dataManager.SaveBusinessUnitType( DefaultConstants.BUSINESS_UNIT_TYPE_NEW_BUSINESS_ID, DefaultConstants.BUSINESS_UNIT_TYPE_NEW_BUSINESS_NAME, projectStartAllowed: true, @@ -148,21 +149,21 @@ private void FillMainData() needVertical: true, possibleParents: [company, account, businessSegment]); - dataHelper.SaveBusinessUnitType( + dataManager.SaveBusinessUnitType( DefaultConstants.BUSINESS_UNIT_TYPE_SERVICE_ID, DefaultConstants.BUSINESS_UNIT_TYPE_SERVICE_NAME, projectStartAllowed: true, canBeLinkedToDepartment: true, canBeResourcePool: true, needVertical: false); - dataHelper.SaveBusinessUnitType( + dataManager.SaveBusinessUnitType( DefaultConstants.BUSINESS_UNIT_TYPE_SE_ADMINISTRATIVE_ID, DefaultConstants.BUSINESS_UNIT_TYPE_SE_ADMINISTRATIVE_NAME, projectStartAllowed: true, canBeLinkedToDepartment: true, canBeResourcePool: true, needVertical: false); - var seDivision = dataHelper.SaveBusinessUnitType( + var seDivision = dataManager.SaveBusinessUnitType( DefaultConstants.BUSINESS_UNIT_TYPE_SE_DIVISION_ID, DefaultConstants.BUSINESS_UNIT_TYPE_SE_DIVISION_NAME, possibleStartDate: PossibleStartDate.AnyDay, @@ -178,14 +179,14 @@ private void FillMainData() canBeNewBusiness: false, possibleParents: [account], transferTo: [account]); - dataHelper.SaveBusinessUnitType( + dataManager.SaveBusinessUnitType( DefaultConstants.BUSINESS_UNIT_TYPE_SE_SUB_DIVISION_ID, DefaultConstants.BUSINESS_UNIT_TYPE_SE_SE_SUB_DIVISION_NAME, projectStartAllowed: true, canBeLinkedToDepartment: true, canBeResourcePool: true, needVertical: false); - dataHelper.SaveBusinessUnitType( + dataManager.SaveBusinessUnitType( DefaultConstants.BUSINESS_UNIT_TYPE_PRACTICE_ID, DefaultConstants.BUSINESS_UNIT_TYPE_PRACTICE_NAME, projectStartAllowed: true, @@ -193,7 +194,7 @@ private void FillMainData() canBeResourcePool: true, needVertical: false); - dataHelper.SaveBusinessUnitType( + dataManager.SaveBusinessUnitType( DefaultConstants.BUSINESS_UNIT_TYPE_PROGRAM_ID, DefaultConstants.BUSINESS_UNIT_TYPE_PROGRAM_NAME, currentTypeInPossibleParents: true, @@ -217,29 +218,29 @@ private void FillMainData() ], transferTo: [account, seDivision]); - dataHelper.SaveEmployeePosition( + dataManager.SaveEmployeePosition( DefaultConstants.EMPLOYEE_POSITION_TESTER_ID, DefaultConstants.EMPLOYEE_POSITION_TESTER_NAME); - dataHelper.SaveEmployeeRegistrationType( + dataManager.SaveEmployeeRegistrationType( DefaultConstants.EMPLOYEE_REGISTRATION_TYPE_STAFF_ID, DefaultConstants.EMPLOYEE_REGISTRATION_TYPE_STAFF_NAME); - dataHelper.SaveEmployeeRole( + dataManager.SaveEmployeeRole( DefaultConstants.EMPLOYEE_ROLE_TESTER_ID, DefaultConstants.EMPLOYEE_ROLE_TESTER_NAME); - dataHelper.SaveEmployeeRoleDegree( + dataManager.SaveEmployeeRoleDegree( DefaultConstants.EMPLOYEE_ROLE_DEGREE_REGULAR_ID, DefaultConstants.EMPLOYEE_ROLE_DEGREE_REGULAR_NAME); - dataHelper.SaveCompanyLegalEntity( + dataManager.SaveCompanyLegalEntity( DefaultConstants.COMPANY_LEGAL_ENTITY_ID, DefaultConstants.COMPANY_LEGAL_ENTITY_NAME); - dataHelper.SaveEmployee(DefaultConstants.HRDepartment_DEFAULT_HEAD_EMPLOYEE_ID, login: "Default_HRDepartment_HEAD", isObjectRequired: false); + dataManager.SaveEmployee(DefaultConstants.HRDepartment_DEFAULT_HEAD_EMPLOYEE_ID, login: "Default_HRDepartment_HEAD", isObjectRequired: false); - dataHelper.SaveHRDepartment( + dataManager.SaveHRDepartment( DefaultConstants.HRDEPARTMENT_PARENT_ID, DefaultConstants.HRDEPARTMENT_PARENT_NAME); } diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Utils/SampleSystemTestDatabaseGenerator.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Utils/SampleSystemTestDatabaseGenerator.cs new file mode 100644 index 000000000..2b4477c5e --- /dev/null +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Utils/SampleSystemTestDatabaseGenerator.cs @@ -0,0 +1,52 @@ +//using Framework.AutomationCore.Settings; +//using Framework.AutomationCore.Utils.DatabaseUtils; +//using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; +//using Framework.Database.NHibernate.DBGenerator; + +//using Microsoft.Extensions.Options; + +//using SampleSystem.DbGenerate.NHibernate; +//using SampleSystem.IntegrationTests.__Support.FluentMigration; +//using SampleSystem.IntegrationTests.__Support.TestData; + +//namespace SampleSystem.IntegrationTests.__Support.Utils; + +//public class SampleSystemTestDatabaseGenerator( +// IDatabaseContext databaseContext, +// IOptions settings, +// TestDataInitializer testDataInitializer) +// : TestDatabaseGenerator(databaseContext, settings) +//{ +// public override IEnumerable TestServers => new List { "." }; + +// public async override Task GenerateDatabasesAsync() => +// new DbGeneratorTest().GenerateAllDB( +// this.DatabaseContext.Main.DataSource, +// mainDatabaseName: this.DatabaseContext.Main.DatabaseName, +// credential: DbUserCredential.Create( +// this.DatabaseContext.Main.UserId, +// this.DatabaseContext.Main.Password)); + +// public override async Task CheckTestDatabaseAsync() +// { +// if (this.DatabaseContext.Server.TableRowCount(this.DatabaseContext.Main.DatabaseName, "Location") > 100) +// { +// throw new Exception( +// "Location row count more than 100. Please ensure that you run tests in Test Environment. If you want to run tests in the environment, please delete all Location rows (Location table) manually and rerun tests."); +// } +// } + +// public override async Task GenerateTestDataAsync() => await testDataInitializer.InitializeAsync(CancellationToken.None); + +// public override void ExecuteInsertsForDatabases() +// { +// base.ExecuteInsertsForDatabases(); + +// CoreDatabaseUtil.ExecuteSqlFromFolder(this.DatabaseContext.Main.ConnectionString, @"__Support/Scripts/Authorization", this.DatabaseContext.Main.DatabaseName); +// CoreDatabaseUtil.ExecuteSqlFromFolder(this.DatabaseContext.Main.ConnectionString,@"__Support/Scripts/Configuration", this.DatabaseContext.Main.DatabaseName); + +// CoreDatabaseUtil.ExecuteSqlFromFolder(this.DatabaseContext.Main.ConnectionString,@"__Support/Scripts/SampleSystem", this.DatabaseContext.Main.DatabaseName); + +// new BssFluentMigrator(this.DatabaseContext.Main.ConnectionString, typeof(InitNumberInDomainObjectEventMigration).Assembly).Migrate(); +// } +//} diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Utils/TestIntegrationEventPublisher.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Utils/TestIntegrationEventPublisher.cs similarity index 79% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Utils/TestIntegrationEventPublisher.cs rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Utils/TestIntegrationEventPublisher.cs index 45fe0ec04..d3ac44659 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Utils/TestIntegrationEventPublisher.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/Utils/TestIntegrationEventPublisher.cs @@ -1,6 +1,6 @@ using Bss.Platform.Events.Abstractions; -namespace SampleSystem.IntegrationTests.__Support.Utils; +namespace SampleSystem.IntegrationTests._Environment.Utils; public class TestIntegrationEventPublisher : IIntegrationEventPublisher { diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/WebApi/IntegrationWebApi.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/WebApi/IntegrationWebApi.cs similarity index 67% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/WebApi/IntegrationWebApi.cs rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/WebApi/IntegrationWebApi.cs index fe3f904d4..6f1cf7549 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/WebApi/IntegrationWebApi.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/WebApi/IntegrationWebApi.cs @@ -1,8 +1,8 @@ using Framework.AutomationCore.WebApi; -using SampleSystem.IntegrationTests.__Support.TestData; +using SampleSystem.IntegrationTests._Environment.TestData; -namespace SampleSystem.IntegrationTests.__Support.WebApi; +namespace SampleSystem.IntegrationTests._Environment.WebApi; public class IntegrationWebApi(IServiceProvider serviceProvider) : IntegrationWebApiBase(serviceProvider) { diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/WebApi/MainAuditWebApi.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/WebApi/MainAuditWebApi.cs similarity index 88% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/WebApi/MainAuditWebApi.cs rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/WebApi/MainAuditWebApi.cs index 5f9e01d28..55b8b021c 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/WebApi/MainAuditWebApi.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/WebApi/MainAuditWebApi.cs @@ -3,7 +3,7 @@ using SampleSystem.WebApiCore.Controllers.Audit; -namespace SampleSystem.IntegrationTests.__Support.WebApi; +namespace SampleSystem.IntegrationTests._Environment.WebApi; public class MainAuditWebApi(IServiceProvider serviceProvider) : WebApiBase(serviceProvider) { diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/WebApi/MainWebApi.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/WebApi/MainWebApi.cs similarity index 90% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/WebApi/MainWebApi.cs rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/WebApi/MainWebApi.cs index c7f1fbf62..eca7e4f39 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/WebApi/MainWebApi.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/_Environment/WebApi/MainWebApi.cs @@ -3,7 +3,7 @@ using SampleSystem.WebApiCore.Controllers.Main; -namespace SampleSystem.IntegrationTests.__Support.WebApi; +namespace SampleSystem.IntegrationTests._Environment.WebApi; public class MainWebApi(IServiceProvider serviceProvider) : WebApiBase(serviceProvider) { diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/InitializeAndCleanup.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/InitializeAndCleanup.cs deleted file mode 100644 index 0a4496d89..000000000 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/InitializeAndCleanup.cs +++ /dev/null @@ -1,55 +0,0 @@ -using Bss.Platform.Events.Abstractions; - -using Framework.Application.Jobs; -using Framework.AutomationCore.Environment; -using Framework.AutomationCore.ServiceEnvironment; - -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting.Internal; - -using SampleSystem.IntegrationTests.__Support.TestData; -using SampleSystem.IntegrationTests.__Support.TestData.Helpers; -using SampleSystem.IntegrationTests.__Support.Utils; -using SampleSystem.ServiceEnvironment; -using SampleSystem.ServiceEnvironment.DependencyInjection; -using SampleSystem.ServiceEnvironment.Jobs; -using SampleSystem.WebApiCore.Controllers.Main; - -namespace SampleSystem.IntegrationTests.__Support; - -public class AssemblyFixture : IAsyncLifetime -{ - public static readonly TestEnvironment TestEnvironment = new TestEnvironmentBuilder() - .WithDefaultConfiguration($"{nameof(SampleSystem)}_") - .WithDatabaseGenerator() - .WithServiceProviderBuildFunc(GetServices) - .Build(); - - private static IServiceCollection GetServices(IConfiguration configuration, IServiceCollection services) => - services - .AddGeneralDependencyInjection(configuration, new HostingEnvironment(), s => s.AddExtensions(new SampleSystemNHibernateExtension())) - - .AddSingleton() - - .AddIntegrationTests() - - .AddScoped() - - .AddSingleton(new JobImpersonateData("sampleSystemTestJob")) - .AddJobs([typeof(SampleJob).Assembly]) - - .AddTestControllers([typeof(EmployeeController).Assembly]) - - .AddSingleton() - - .AddSingleton(); - - public Task InitializeAsync() => TestEnvironment.AssemblyInitializeAndCleanup.EnvironmentInitializeAsync(); - - public async Task DisposeAsync() - { - await TestEnvironment.AssemblyInitializeAndCleanup.EnvironmentCleanupAsync(); - GC.SuppressFinalize(this); - } -} diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestCollection.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestCollection.cs deleted file mode 100644 index 496c777db..000000000 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestCollection.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace SampleSystem.IntegrationTests.__Support; - -[CollectionDefinition("Test Collection")] -public class TestCollection : ICollectionFixture -{ -} diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/Helpers/DataHelper.Init.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/Helpers/DataHelper.Init.cs deleted file mode 100644 index 49351d4d6..000000000 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/Helpers/DataHelper.Init.cs +++ /dev/null @@ -1,14 +0,0 @@ -using Framework.AutomationCore.RootServiceProviderContainer; - -using SampleSystem.BLL; - -namespace SampleSystem.IntegrationTests.__Support.TestData.Helpers; - -public partial class DataHelper(IServiceProvider rootServiceProvider) : RootServiceProviderContainer(rootServiceProvider) -{ - private Guid GetGuid(Guid? id) - { - id = id ?? Guid.NewGuid(); - return (Guid)id; - } -} diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/TestBase.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/TestBase.cs deleted file mode 100644 index f5bca4e6e..000000000 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/TestData/TestBase.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Framework.AutomationCore; -using Framework.AutomationCore.ServiceEnvironment; - -using Microsoft.Extensions.DependencyInjection; - -using SampleSystem.BLL; -using SampleSystem.IntegrationTests.__Support.TestData.Helpers; -using SampleSystem.IntegrationTests.__Support.WebApi; -using SampleSystem.WebApiCore.Controllers.Main; - -using Anch.SecuritySystem.Testing; - -namespace SampleSystem.IntegrationTests.__Support.TestData; - -[Collection("Test Collection")] -public class TestBase : IntegrationTestBase, IDisposable -{ - protected TestBase() : base(AssemblyFixture.TestEnvironment.ServiceProviderPool) => base.Initialize(); - - public MainWebApi MainWebApi => new(this.RootServiceProvider); - - public MainAuditWebApi MainAuditWebApi => new(this.RootServiceProvider); - - protected DataHelper DataHelper => this.RootServiceProvider.GetRequiredService(); - - protected RootAuthManager AuthManager => this.RootServiceProvider.GetRequiredService(); - - public void Dispose() - { - this.BeforeCleanup(); - base.Cleanup(); - } - - protected virtual void BeforeCleanup() - { - } - - protected ControllerEvaluator GetAuthControllerEvaluator(string? principalName = null) => this.GetControllerEvaluator(principalName); - - protected ControllerEvaluator GetConfigurationControllerEvaluator(string? principalName = null) => this.GetControllerEvaluator(principalName); -} diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Utils/SampleSystemTestDatabaseGenerator.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Utils/SampleSystemTestDatabaseGenerator.cs deleted file mode 100644 index 55b2b6174..000000000 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/__Support/Utils/SampleSystemTestDatabaseGenerator.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Framework.AutomationCore.Settings; -using Framework.AutomationCore.Utils.DatabaseUtils; -using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; -using Framework.Database.NHibernate.DBGenerator; - -using Microsoft.Extensions.Options; - -using SampleSystem.DbGenerate.NHibernate; -using SampleSystem.IntegrationTests.__Support.FluentMigration; -using SampleSystem.IntegrationTests.__Support.TestData; - -namespace SampleSystem.IntegrationTests.__Support.Utils; - -public class SampleSystemTestDatabaseGenerator( - IDatabaseContext databaseContext, - IOptions settings, - TestDataInitializer testDataInitializer) - : TestDatabaseGenerator(databaseContext, settings) -{ - public override IEnumerable TestServers => new List { "." }; - - public async override Task GenerateDatabasesAsync() => - new DbGeneratorTest().GenerateAllDB( - this.DatabaseContext.Main.DataSource, - mainDatabaseName: this.DatabaseContext.Main.DatabaseName, - credential: DbUserCredential.Create( - this.DatabaseContext.Main.UserId, - this.DatabaseContext.Main.Password)); - - public override async Task CheckTestDatabaseAsync() - { - if (this.DatabaseContext.Server.TableRowCount(this.DatabaseContext.Main.DatabaseName, "Location") > 100) - { - throw new Exception( - "Location row count more than 100. Please ensure that you run tests in Test Environment. If you want to run tests in the environment, please delete all Location rows (Location table) manually and rerun tests."); - } - } - - public override async Task GenerateTestDataAsync() => await testDataInitializer.InitializeAsync(default); - - public override void ExecuteInsertsForDatabases() - { - base.ExecuteInsertsForDatabases(); - - CoreDatabaseUtil.ExecuteSqlFromFolder(this.DatabaseContext.Main.ConnectionString, @"__Support/Scripts/Authorization", this.DatabaseContext.Main.DatabaseName); - CoreDatabaseUtil.ExecuteSqlFromFolder(this.DatabaseContext.Main.ConnectionString,@"__Support/Scripts/Configuration", this.DatabaseContext.Main.DatabaseName); - - CoreDatabaseUtil.ExecuteSqlFromFolder(this.DatabaseContext.Main.ConnectionString,@"__Support/Scripts/SampleSystem", this.DatabaseContext.Main.DatabaseName); - - new BssFluentMigrator(this.DatabaseContext.Main.ConnectionString, typeof(InitNumberInDomainObjectEventMigration).Assembly).Migrate(); - } -} diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/appsettings.json b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/testAppSettings.json similarity index 100% rename from src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/appsettings.json rename to src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.NHibernate/testAppSettings.json diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/SampleSystem.IntegrationTests.Xunit.NHibernate.csproj b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/SampleSystem.IntegrationTests.Xunit.NHibernate.csproj deleted file mode 100644 index 8d147849e..000000000 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/SampleSystem.IntegrationTests.Xunit.NHibernate.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - false - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - Always - - - - - - - - diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/ServiceProviderMemberDataTest.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/ServiceProviderMemberDataTest.cs deleted file mode 100644 index a43f69fe7..000000000 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/ServiceProviderMemberDataTest.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Bss.Testing.Xunit.Sdk; - -using Anch.SecuritySystem; - -using Microsoft.Extensions.DependencyInjection; - -using SampleSystem.IntegrationTests.Xunit.NHibernate.__Support; - -namespace SampleSystem.IntegrationTests.Xunit.NHibernate; - -public class ServiceProviderMemberDataTest(IServiceProvider serviceProvider) : TestBase(serviceProvider) -{ - [BssTheory] - [ServiceProviderMemberData(nameof(GetMemberData))] - public void GetDataFromServiceProvider(FullSecurityRole role) => Assert.NotNull(role.Name); - - protected IEnumerable GetMemberData() => - this.ServiceProvider.GetRequiredService().SecurityRoles.Select(x => new [] { x }); -} diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/__Support/Database/DatabaseGenerator.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/__Support/Database/DatabaseGenerator.cs deleted file mode 100644 index f3403e2c6..000000000 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/__Support/Database/DatabaseGenerator.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Framework.AutomationCore.Settings; -using Framework.AutomationCore.Utils.DatabaseUtils; -using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; -using Framework.Database.NHibernate.DBGenerator; - -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Options; - -using SampleSystem.DbGenerate.NHibernate; -using SampleSystem.IntegrationTests.__Support.FluentMigration; -using SampleSystem.IntegrationTests.Xunit.NHibernate.__Support.TestData; - -namespace SampleSystem.IntegrationTests.Xunit.NHibernate.__Support.Database; - -public class DatabaseGenerator( - IDatabaseContext databaseContext, - IOptions settings, - IConfiguration configuration) - : TestDatabaseGenerator(databaseContext, settings) -{ - public override IEnumerable TestServers => new List { "." }; - - public override async Task GenerateDatabasesAsync() => - new DbGeneratorTest().GenerateAllDB( - this.DatabaseContext.Main.DataSource, - mainDatabaseName: this.DatabaseContext.Main.DatabaseName, - credential: DbUserCredential.Create( - this.DatabaseContext.Main.UserId, - this.DatabaseContext.Main.Password)); - - public override async Task CheckTestDatabaseAsync() - { - if (this.DatabaseContext.Server.TableRowCount(this.DatabaseContext.Main.DatabaseName, "Location") > 100) - { - throw new Exception( - "Location row count more than 100. Please ensure that you run tests in Test Environment. If you want to run tests in the environment, please delete all Location rows (Location table) manually and rerun tests."); - } - } - - public override async Task GenerateTestDataAsync() => await new TestDataInitializer(configuration, this.DatabaseContext) - .InitializeAsync(CancellationToken.None); - public override void ExecuteInsertsForDatabases() - { - base.ExecuteInsertsForDatabases(); - - CoreDatabaseUtil.ExecuteSqlFromFolder(this.DatabaseContext.Main.ConnectionString, @"__Support/Scripts/Authorization", this.DatabaseContext.Main.DatabaseName); - CoreDatabaseUtil.ExecuteSqlFromFolder(this.DatabaseContext.Main.ConnectionString,@"__Support/Scripts/Configuration", this.DatabaseContext.Main.DatabaseName); - CoreDatabaseUtil.ExecuteSqlFromFolder(this.DatabaseContext.Main.ConnectionString,@"__Support/Scripts/SampleSystem", this.DatabaseContext.Main.DatabaseName); - - new BssFluentMigrator(this.DatabaseContext.Main.ConnectionString, typeof(InitNumberInDomainObjectEventMigration).Assembly).Migrate(); - } -} diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/__Support/EnvironmentInitializer.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/__Support/EnvironmentInitializer.cs deleted file mode 100644 index f854a8bf5..000000000 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/__Support/EnvironmentInitializer.cs +++ /dev/null @@ -1,53 +0,0 @@ -using Bss.Platform.Events.Abstractions; -using Bss.Testing.Xunit.Interfaces; - -using Anch.DependencyInjection; - -using Framework.AutomationCore.ServiceEnvironment; -using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; -using Framework.AutomationCore.Xunit; -using Framework.AutomationCore.Xunit.ServiceEnvironment; - -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting.Internal; - -using SampleSystem.IntegrationTests.__Support.TestData.Helpers; -using SampleSystem.IntegrationTests.__Support.Utils; -using SampleSystem.IntegrationTests.Xunit.NHibernate.__Support.Database; -using SampleSystem.IntegrationTests.Xunit.NHibernate.__Support.TestData; -using SampleSystem.ServiceEnvironment; -using SampleSystem.ServiceEnvironment.DependencyInjection; -using SampleSystem.WebApiCore.Controllers.Main; - -[assembly: CollectionBehavior(CollectionBehavior.CollectionPerClass)] -[assembly: TestFramework("Bss.Testing.Xunit.TestFramework", "Bss.Testing.Xunit")] - -namespace SampleSystem.IntegrationTests.Xunit.NHibernate.__Support; - -public class EnvironmentInitializer : AutomationCoreFrameworkInitializer -{ - public override IServiceCollection ConfigureFramework(IServiceCollection services) => - services - .AddSingleton() - .AddSingleton() - .AddSingleton( - new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile("appsettings.json", false) - .AddEnvironmentVariables($"{nameof(SampleSystem)}_") - .Build()); - - public override IServiceProvider ConfigureTestEnvironment(IServiceCollection services, IConfiguration configuration) => - services - .AddGeneralDependencyInjection(configuration, new HostingEnvironment(), s => s.AddExtensions(new SampleSystemNHibernateExtension())) - .AddSingleton() - .AddScoped() - .AddTestControllers([typeof(EmployeeController).Assembly]) - .AddSingleton() - .AddSingleton() - .AddXunitIntegrationTests() - .AddValidator() - .Validate() - .BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true, ValidateScopes = true }); -} diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/__Support/TestBase.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/__Support/TestBase.cs deleted file mode 100644 index 1a10249b8..000000000 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/__Support/TestBase.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace SampleSystem.IntegrationTests.Xunit.NHibernate.__Support; - -public class TestBase(IServiceProvider serviceProvider) -{ - protected IServiceProvider ServiceProvider { get; } = serviceProvider; -} diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/__Support/TestData/TestDataInitializer.cs b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/__Support/TestData/TestDataInitializer.cs deleted file mode 100644 index aa41a2276..000000000 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/__Support/TestData/TestDataInitializer.cs +++ /dev/null @@ -1,264 +0,0 @@ -using Framework.AutomationCore.Extensions; -using Framework.AutomationCore.Settings; -using Framework.AutomationCore.Utils.DatabaseUtils.Interfaces; - -using Anch.SecuritySystem; -using Anch.SecuritySystem.Services; -using Anch.SecuritySystem.Testing; - -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Options; - -using SampleSystem.Domain.Enums; -using SampleSystem.Domain.Inline; -using SampleSystem.IntegrationTests.__Support.TestData; -using SampleSystem.IntegrationTests.__Support.TestData.Helpers; -using SampleSystem.ServiceEnvironment; - -namespace SampleSystem.IntegrationTests.Xunit.NHibernate.__Support.TestData; - -public class TestDataInitializer -{ - private readonly IServiceProvider serviceProvider; - - private readonly DataHelper dataHelper; - - public TestDataInitializer( - IConfiguration configuration, - IDatabaseContext databaseContext) - { - var generatorConfig = configuration.BuildFromRootWithConnectionStrings(databaseContext); - - this.serviceProvider = new EnvironmentInitializer() - .ConfigureTestEnvironment( - new ServiceCollection() - .AddSingleton(databaseContext) - .AddSingleton(generatorConfig), - generatorConfig); - - this.dataHelper = this.serviceProvider.GetRequiredService(); - } - - public async Task InitializeAsync(CancellationToken cancellationToken) => - await this.serviceProvider - .GetRequiredService() - .WithImpersonateAsync( - nameof(TestDataInitializer), - async () => await this.InitializeAsyncInternal(cancellationToken)); - - public async Task InitializeAsyncInternal(CancellationToken cancellationToken) - { - await this.serviceProvider.GetRequiredService().InitializeAsync(cancellationToken); - var authManager = this.serviceProvider.GetRequiredService(); - - await authManager.For(nameof(TestDataInitializer)).SetAdminRoleAsync(cancellationToken); - await authManager.For(DefaultConstants.NOTIFICATION_ADMIN).SetRoleAsync(SecurityRole.SystemIntegration, cancellationToken); - await authManager.For(DefaultConstants.INTEGRATION_BUS).SetRoleAsync(SecurityRole.SystemIntegration, cancellationToken); - - this.FillMainData(); - - var integrationTestUserName = this.serviceProvider.GetRequiredService>() - .Value.IntegrationTestUserName; - - this.dataHelper.SaveEmployee( - id: DefaultConstants.EMPLOYEE_MY_ID, - nameEng: new Fio { FirstName = DefaultConstants.EMPLOYEE_MY_NAME, LastName = DefaultConstants.EMPLOYEE_MY_NAME }, - login: integrationTestUserName); - - await authManager.For(integrationTestUserName).SetAdminRoleAsync(cancellationToken); - } - - private void FillMainData() - { - this.dataHelper.SaveCountry( - id: DefaultConstants.COUNTRY_RUSSIA_ID, - name: DefaultConstants.COUNTRY_RUSSIA_NAME, - nativeName: DefaultConstants.COUNTRY_RUSSIA_NATIVE_NAME, - code: DefaultConstants.COUNTRY_RUSSIA_CODE, - culture: "ru-RU"); - - this.dataHelper.SaveLocation(id: DefaultConstants.LOCATION_PARENT_ID, name: DefaultConstants.LOCATION_PARENT_NAME); - - var company = this.dataHelper.SaveBusinessUnitType( - DefaultConstants.BUSINESS_UNIT_TYPE_COMPANY_ID, - DefaultConstants.BUSINESS_UNIT_TYPE_COMPANY_NAME, - isAdministrative: false, - projectStartAllowed: false, - canBeLinkedToDepartment: false, - canBeResourcePool: false, - needVertical: false); - var lob = this.dataHelper.SaveBusinessUnitType( - DefaultConstants.BUSINESS_UNIT_TYPE_LOB_ID, - DefaultConstants.BUSINESS_UNIT_TYPE_LOB_NAME, - projectStartAllowed: true, - canBeLinkedToDepartment: true, - canBeResourcePool: true, - needVertical: false); - - var businessSegment = this.dataHelper.SaveBusinessUnitType( - DefaultConstants.BUSINESS_UNIT_TYPE_BUSINESS_SEGMENT_ID, - DefaultConstants.BUSINESS_UNIT_TYPE_BUSINESS_SEGMENT_NAME, - possibleStartDate: PossibleStartDate.FinYearStart, - isAdministrative: false, - canBeResourcePool: true, - projectStartAllowed: true, - billProjectAreNotAllowed: false, - startBOConfirm: true, - possibleTransferDate: PossibleStartDate.FinYearStart, - transferBOConfirm: true, - needVertical: false, - canBeIsCommission: false, - canBeNewBusiness: false, - possibleParents: [company]); - - var account = this.dataHelper.SaveBusinessUnitType( - DefaultConstants.BUSINESS_UNIT_TYPE_ACCOUNT_ID, - DefaultConstants.BUSINESS_UNIT_TYPE_ACCOUNT_NAME, - possibleStartDate: PossibleStartDate.AnyDay, - isAdministrative: false, - canBeResourcePool: true, - projectStartAllowed: true, - billProjectAreNotAllowed: false, - startBOConfirm: true, - possibleTransferDate: PossibleStartDate.AnyDay, - transferBOConfirm: true, - needVertical: true, - canBeIsCommission: false, - canBeNewBusiness: true, - possibleFinancialProjectTypes: - [ - FinancialProjectType.Commercial, FinancialProjectType.Administrative, - FinancialProjectType.Investment, FinancialProjectType.RnD - ], - possibleParents: [businessSegment, lob, company], - transferTo: [businessSegment, lob, company]); - - this.dataHelper.SaveBusinessUnitType( - DefaultConstants.BUSINESS_UNIT_TYPE_ADMIN_COMMERCIAL_ID, - DefaultConstants.BUSINESS_UNIT_TYPE_ADMIN_COMMERCIAL_NAME, - projectStartAllowed: true, - canBeLinkedToDepartment: true, - canBeResourcePool: true, - needVertical: false); - this.dataHelper.SaveBusinessUnitType( - DefaultConstants.BUSINESS_UNIT_TYPE_ADMIN_SERVICES_ID, - DefaultConstants.BUSINESS_UNIT_TYPE_ADMIN_SERVICES_NAME, - projectStartAllowed: true, - canBeLinkedToDepartment: true, - canBeResourcePool: true, - needVertical: false); - this.dataHelper.SaveBusinessUnitType( - DefaultConstants.BUSINESS_UNIT_TYPE_DIVISION_ID, - DefaultConstants.BUSINESS_UNIT_TYPE_DIVISION_NAME, - projectStartAllowed: true, - canBeLinkedToDepartment: true, - canBeResourcePool: true, - needVertical: false, - possibleParents: [company, account]); - - this.dataHelper.SaveBusinessUnitType( - DefaultConstants.BUSINESS_UNIT_TYPE_NEW_BUSINESS_ID, - DefaultConstants.BUSINESS_UNIT_TYPE_NEW_BUSINESS_NAME, - projectStartAllowed: true, - canBeLinkedToDepartment: true, - canBeResourcePool: true, - needVertical: true, - possibleParents: [company, account, businessSegment]); - - this.dataHelper.SaveBusinessUnitType( - DefaultConstants.BUSINESS_UNIT_TYPE_SERVICE_ID, - DefaultConstants.BUSINESS_UNIT_TYPE_SERVICE_NAME, - projectStartAllowed: true, - canBeLinkedToDepartment: true, - canBeResourcePool: true, - needVertical: false); - this.dataHelper.SaveBusinessUnitType( - DefaultConstants.BUSINESS_UNIT_TYPE_SE_ADMINISTRATIVE_ID, - DefaultConstants.BUSINESS_UNIT_TYPE_SE_ADMINISTRATIVE_NAME, - projectStartAllowed: true, - canBeLinkedToDepartment: true, - canBeResourcePool: true, - needVertical: false); - var seDivision = this.dataHelper.SaveBusinessUnitType( - DefaultConstants.BUSINESS_UNIT_TYPE_SE_DIVISION_ID, - DefaultConstants.BUSINESS_UNIT_TYPE_SE_DIVISION_NAME, - possibleStartDate: PossibleStartDate.AnyDay, - isAdministrative: false, - canBeResourcePool: false, - projectStartAllowed: false, - billProjectAreNotAllowed: false, - startBOConfirm: true, - possibleTransferDate: PossibleStartDate.FinYearStart, - transferBOConfirm: true, - needVertical: false, - canBeIsCommission: false, - canBeNewBusiness: false, - possibleParents: [account], - transferTo: [account]); - this.dataHelper.SaveBusinessUnitType( - DefaultConstants.BUSINESS_UNIT_TYPE_SE_SUB_DIVISION_ID, - DefaultConstants.BUSINESS_UNIT_TYPE_SE_SE_SUB_DIVISION_NAME, - projectStartAllowed: true, - canBeLinkedToDepartment: true, - canBeResourcePool: true, - needVertical: false); - this.dataHelper.SaveBusinessUnitType( - DefaultConstants.BUSINESS_UNIT_TYPE_PRACTICE_ID, - DefaultConstants.BUSINESS_UNIT_TYPE_PRACTICE_NAME, - projectStartAllowed: true, - canBeLinkedToDepartment: true, - canBeResourcePool: true, - needVertical: false); - - this.dataHelper.SaveBusinessUnitType( - DefaultConstants.BUSINESS_UNIT_TYPE_PROGRAM_ID, - DefaultConstants.BUSINESS_UNIT_TYPE_PROGRAM_NAME, - currentTypeInPossibleParents: true, - currentTypeInTransferTo: true, - possibleStartDate: PossibleStartDate.AnyDay, - isAdministrative: false, - canBeResourcePool: true, - projectStartAllowed: true, - billProjectAreNotAllowed: false, - startBOConfirm: true, - possibleTransferDate: PossibleStartDate.AnyDay, - transferBOConfirm: true, - needVertical: false, - canBeIsCommission: true, - canBeNewBusiness: false, - possibleParents: [account, seDivision, businessSegment], - possibleFinancialProjectTypes: - [ - FinancialProjectType.Commercial, FinancialProjectType.Administrative, - FinancialProjectType.Investment, FinancialProjectType.RnD - ], - transferTo: [account, seDivision]); - - this.dataHelper.SaveEmployeePosition( - DefaultConstants.EMPLOYEE_POSITION_TESTER_ID, - DefaultConstants.EMPLOYEE_POSITION_TESTER_NAME); - - this.dataHelper.SaveEmployeeRegistrationType( - DefaultConstants.EMPLOYEE_REGISTRATION_TYPE_STAFF_ID, - DefaultConstants.EMPLOYEE_REGISTRATION_TYPE_STAFF_NAME); - - this.dataHelper.SaveEmployeeRole( - DefaultConstants.EMPLOYEE_ROLE_TESTER_ID, - DefaultConstants.EMPLOYEE_ROLE_TESTER_NAME); - - this.dataHelper.SaveEmployeeRoleDegree( - DefaultConstants.EMPLOYEE_ROLE_DEGREE_REGULAR_ID, - DefaultConstants.EMPLOYEE_ROLE_DEGREE_REGULAR_NAME); - - this.dataHelper.SaveCompanyLegalEntity( - DefaultConstants.COMPANY_LEGAL_ENTITY_ID, - DefaultConstants.COMPANY_LEGAL_ENTITY_NAME); - - this.dataHelper.SaveEmployee(DefaultConstants.HRDepartment_DEFAULT_HEAD_EMPLOYEE_ID, login: "Default_HRDepartment_HEAD", isObjectRequired: false); - - this.dataHelper.SaveHRDepartment( - DefaultConstants.HRDEPARTMENT_PARENT_ID, - DefaultConstants.HRDEPARTMENT_PARENT_NAME); - } -} diff --git a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/appsettings.json b/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/appsettings.json deleted file mode 100644 index c401e876f..000000000 --- a/src/_SampleSystem/_Tests/SampleSystem.IntegrationTests.Xunit.NHibernate/appsettings.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "AutomationFrameworkSettings": { - "TestRunServerRootFolder": "/var/opt/mssql/" - }, - - "ConnectionStrings": { - "DefaultConnection": "Data Source=.;Initial Catalog=SampleSystem;User Id=sa;Password=P@ssw0rd;Application Name=SampleSystem;TrustServerCertificate=True", - "WorkflowCoreConnection": "Data Source=.;Initial Catalog=SampleSystem;User Id=sa;Password=P@ssw0rd;Application Name=SampleSystem;TrustServerCertificate=True" - }, - - "Hangfire": { - "ConnectionString": "Server=localhost;Initial Catalog=Jobs;User Id=sa;Password=P@ssw0rd;", - "Jobs": { - "TaskReview": { - "Hour": 1, - "Minutes": 0, - "Period": 1 - } - } - } -} diff --git a/src/_SampleSystem/_Tests/SampleSystem.UnitTests/ExtractConstTests.cs b/src/_SampleSystem/_Tests/SampleSystem.UnitTests/ExtractConstTests.cs index 551b959cd..420f2e9ea 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.UnitTests/ExtractConstTests.cs +++ b/src/_SampleSystem/_Tests/SampleSystem.UnitTests/ExtractConstTests.cs @@ -13,13 +13,13 @@ public class ExtractConstTests public void NullValueChainExpression_GetDeepMemberConstValue_NotThrowException() { // Arrange - Parameters p = null; - Expression> testExpr = obj => p.Period.StartDate > obj.Period.StartDate; + Parameters? p = null; + Expression> testExpr = obj => p!.Period.StartDate > obj.Period.StartDate; - Action action = () => testExpr.UpdateBase(OverrideHashSetVisitor.Value); - - var exception = Record.Exception(action); + // Act + var exception = Record.Exception(() => testExpr.UpdateBase(OverrideHashSetVisitor.Value)); + // Assert Assert.Null(exception); } diff --git a/src/_SampleSystem/_Tests/SampleSystem.UnitTests/SampleSystem.UnitTests.csproj b/src/_SampleSystem/_Tests/SampleSystem.UnitTests/SampleSystem.UnitTests.csproj index 4035aeae1..45caffdf6 100644 --- a/src/_SampleSystem/_Tests/SampleSystem.UnitTests/SampleSystem.UnitTests.csproj +++ b/src/_SampleSystem/_Tests/SampleSystem.UnitTests/SampleSystem.UnitTests.csproj @@ -6,7 +6,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive