diff --git a/src/Lumina.sln b/src/Lumina.sln index 705b4779..9c38d44d 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -1,4 +1,4 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 @@ -210,6 +210,20 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.OpenLibrary" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Domain.SharedKernel", "Lumina.Domain.SharedKernel\Lumina.Domain.SharedKernel.csproj", "{9450EAC6-1F33-4BE1-89E3-0275885FE3EE}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Domain.Fixtures", "..\tests\Common\Lumina.Domain.Fixtures\Lumina.Domain.Fixtures.csproj", "{E6449D94-C33A-41CE-9047-7298CF20C311}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Contracts.Fixtures", "..\tests\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj", "{45774AE5-23DB-424B-8E2A-B355ADEFB777}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Application.Fixtures", "..\tests\Common\Lumina.Application.Fixtures\Lumina.Application.Fixtures.csproj", "{BEF177F3-99E7-4649-86AB-B4235B9A95ED}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Infrastructure.Fixtures", "..\tests\Common\Lumina.Infrastructure.Fixtures\Lumina.Infrastructure.Fixtures.csproj", "{7C2AB7E7-F58B-4F96-BDFB-05E403BD999B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Presentation.Api.Fixtures", "..\tests\Common\Lumina.Presentation.Api.Fixtures\Lumina.Presentation.Api.Fixtures.csproj", "{4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Domain.SharedKernel.Fixtures", "..\tests\Common\Lumina.Domain.SharedKernel.Fixtures\Lumina.Domain.SharedKernel.Fixtures.csproj", "{A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -432,6 +446,78 @@ Global {9450EAC6-1F33-4BE1-89E3-0275885FE3EE}.Release|x64.Build.0 = Release|Any CPU {9450EAC6-1F33-4BE1-89E3-0275885FE3EE}.Release|x86.ActiveCfg = Release|Any CPU {9450EAC6-1F33-4BE1-89E3-0275885FE3EE}.Release|x86.Build.0 = Release|Any CPU + {E6449D94-C33A-41CE-9047-7298CF20C311}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E6449D94-C33A-41CE-9047-7298CF20C311}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E6449D94-C33A-41CE-9047-7298CF20C311}.Debug|x64.ActiveCfg = Debug|Any CPU + {E6449D94-C33A-41CE-9047-7298CF20C311}.Debug|x64.Build.0 = Debug|Any CPU + {E6449D94-C33A-41CE-9047-7298CF20C311}.Debug|x86.ActiveCfg = Debug|Any CPU + {E6449D94-C33A-41CE-9047-7298CF20C311}.Debug|x86.Build.0 = Debug|Any CPU + {E6449D94-C33A-41CE-9047-7298CF20C311}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E6449D94-C33A-41CE-9047-7298CF20C311}.Release|Any CPU.Build.0 = Release|Any CPU + {E6449D94-C33A-41CE-9047-7298CF20C311}.Release|x64.ActiveCfg = Release|Any CPU + {E6449D94-C33A-41CE-9047-7298CF20C311}.Release|x64.Build.0 = Release|Any CPU + {E6449D94-C33A-41CE-9047-7298CF20C311}.Release|x86.ActiveCfg = Release|Any CPU + {E6449D94-C33A-41CE-9047-7298CF20C311}.Release|x86.Build.0 = Release|Any CPU + {45774AE5-23DB-424B-8E2A-B355ADEFB777}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {45774AE5-23DB-424B-8E2A-B355ADEFB777}.Debug|Any CPU.Build.0 = Debug|Any CPU + {45774AE5-23DB-424B-8E2A-B355ADEFB777}.Debug|x64.ActiveCfg = Debug|Any CPU + {45774AE5-23DB-424B-8E2A-B355ADEFB777}.Debug|x64.Build.0 = Debug|Any CPU + {45774AE5-23DB-424B-8E2A-B355ADEFB777}.Debug|x86.ActiveCfg = Debug|Any CPU + {45774AE5-23DB-424B-8E2A-B355ADEFB777}.Debug|x86.Build.0 = Debug|Any CPU + {45774AE5-23DB-424B-8E2A-B355ADEFB777}.Release|Any CPU.ActiveCfg = Release|Any CPU + {45774AE5-23DB-424B-8E2A-B355ADEFB777}.Release|Any CPU.Build.0 = Release|Any CPU + {45774AE5-23DB-424B-8E2A-B355ADEFB777}.Release|x64.ActiveCfg = Release|Any CPU + {45774AE5-23DB-424B-8E2A-B355ADEFB777}.Release|x64.Build.0 = Release|Any CPU + {45774AE5-23DB-424B-8E2A-B355ADEFB777}.Release|x86.ActiveCfg = Release|Any CPU + {45774AE5-23DB-424B-8E2A-B355ADEFB777}.Release|x86.Build.0 = Release|Any CPU + {BEF177F3-99E7-4649-86AB-B4235B9A95ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BEF177F3-99E7-4649-86AB-B4235B9A95ED}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BEF177F3-99E7-4649-86AB-B4235B9A95ED}.Debug|x64.ActiveCfg = Debug|Any CPU + {BEF177F3-99E7-4649-86AB-B4235B9A95ED}.Debug|x64.Build.0 = Debug|Any CPU + {BEF177F3-99E7-4649-86AB-B4235B9A95ED}.Debug|x86.ActiveCfg = Debug|Any CPU + {BEF177F3-99E7-4649-86AB-B4235B9A95ED}.Debug|x86.Build.0 = Debug|Any CPU + {BEF177F3-99E7-4649-86AB-B4235B9A95ED}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BEF177F3-99E7-4649-86AB-B4235B9A95ED}.Release|Any CPU.Build.0 = Release|Any CPU + {BEF177F3-99E7-4649-86AB-B4235B9A95ED}.Release|x64.ActiveCfg = Release|Any CPU + {BEF177F3-99E7-4649-86AB-B4235B9A95ED}.Release|x64.Build.0 = Release|Any CPU + {BEF177F3-99E7-4649-86AB-B4235B9A95ED}.Release|x86.ActiveCfg = Release|Any CPU + {BEF177F3-99E7-4649-86AB-B4235B9A95ED}.Release|x86.Build.0 = Release|Any CPU + {7C2AB7E7-F58B-4F96-BDFB-05E403BD999B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7C2AB7E7-F58B-4F96-BDFB-05E403BD999B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7C2AB7E7-F58B-4F96-BDFB-05E403BD999B}.Debug|x64.ActiveCfg = Debug|Any CPU + {7C2AB7E7-F58B-4F96-BDFB-05E403BD999B}.Debug|x64.Build.0 = Debug|Any CPU + {7C2AB7E7-F58B-4F96-BDFB-05E403BD999B}.Debug|x86.ActiveCfg = Debug|Any CPU + {7C2AB7E7-F58B-4F96-BDFB-05E403BD999B}.Debug|x86.Build.0 = Debug|Any CPU + {7C2AB7E7-F58B-4F96-BDFB-05E403BD999B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7C2AB7E7-F58B-4F96-BDFB-05E403BD999B}.Release|Any CPU.Build.0 = Release|Any CPU + {7C2AB7E7-F58B-4F96-BDFB-05E403BD999B}.Release|x64.ActiveCfg = Release|Any CPU + {7C2AB7E7-F58B-4F96-BDFB-05E403BD999B}.Release|x64.Build.0 = Release|Any CPU + {7C2AB7E7-F58B-4F96-BDFB-05E403BD999B}.Release|x86.ActiveCfg = Release|Any CPU + {7C2AB7E7-F58B-4F96-BDFB-05E403BD999B}.Release|x86.Build.0 = Release|Any CPU + {4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91}.Debug|x64.ActiveCfg = Debug|Any CPU + {4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91}.Debug|x64.Build.0 = Debug|Any CPU + {4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91}.Debug|x86.ActiveCfg = Debug|Any CPU + {4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91}.Debug|x86.Build.0 = Debug|Any CPU + {4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91}.Release|Any CPU.Build.0 = Release|Any CPU + {4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91}.Release|x64.ActiveCfg = Release|Any CPU + {4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91}.Release|x64.Build.0 = Release|Any CPU + {4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91}.Release|x86.ActiveCfg = Release|Any CPU + {4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91}.Release|x86.Build.0 = Release|Any CPU + {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Debug|x64.ActiveCfg = Debug|Any CPU + {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Debug|x64.Build.0 = Debug|Any CPU + {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Debug|x86.ActiveCfg = Debug|Any CPU + {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Debug|x86.Build.0 = Debug|Any CPU + {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Release|Any CPU.Build.0 = Release|Any CPU + {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Release|x64.ActiveCfg = Release|Any CPU + {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Release|x64.Build.0 = Release|Any CPU + {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Release|x86.ActiveCfg = Release|Any CPU + {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -478,6 +564,13 @@ Global {8CF6FEA4-624C-4EC9-93D6-EB7626059D7C} = {3C316ABB-08D5-4450-9A4E-91059DB54254} {EADCD78B-04D5-4FE3-855C-E3015531EC8E} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} {9450EAC6-1F33-4BE1-89E3-0275885FE3EE} = {3C316ABB-08D5-4450-9A4E-91059DB54254} + {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} = {16E590D3-DD9F-4B45-BF19-C6E317A57D11} + {E6449D94-C33A-41CE-9047-7298CF20C311} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {45774AE5-23DB-424B-8E2A-B355ADEFB777} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {BEF177F3-99E7-4649-86AB-B4235B9A95ED} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {7C2AB7E7-F58B-4F96-BDFB-05E403BD999B} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4A55A28E-C657-4A0B-95EA-2931AE66004E} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/Fixtures/PermissionEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/PermissionEntityFixture.cs similarity index 52% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/Fixtures/PermissionEntityFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/PermissionEntityFixture.cs index 6296db65..5bdb4867 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/Fixtures/PermissionEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/PermissionEntityFixture.cs @@ -1,13 +1,14 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; using Bogus; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; /// /// Fixture class for the class. @@ -15,26 +16,17 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; [ExcludeFromCodeCoverage] public class PermissionEntityFixture { - private readonly Fixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public PermissionEntityFixture() - { - _fixture = new Fixture(); - ConfigureCustomTypes(); - } - /// /// Creates a random valid . /// + /// Optional. The permission Id. + /// Optional. The permission name. /// The created . - public PermissionEntity CreatePermissionModel() + public PermissionEntity Create(Guid? id = null, AuthorizationPermission? permissionName = null) { return new Faker() - .RuleFor(x => x.Id, f => f.Random.Guid()) - .RuleFor(x => x.PermissionName, f => f.PickRandom()) + .RuleFor(x => x.Id, f => id ?? f.Random.Guid()) + .RuleFor(x => x.PermissionName, f => permissionName ?? f.PickRandom()) .RuleFor(x => x.RolePermissions, []) .RuleFor(x => x.UserPermissions, []) .RuleFor(x => x.CreatedOnUtc, f => f.Date.Past()) @@ -45,18 +37,12 @@ public class PermissionEntityFixture } /// - /// Configures custom type generation rules for the AutoFixture instance. + /// Creates a list of instances with randomized test data. /// - private void ConfigureCustomTypes() + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) { - _fixture.Register(() => new PermissionEntity - { - Id = _fixture.Create(), - PermissionName = _fixture.Create(), - CreatedOnUtc = _fixture.Create(), - CreatedBy = _fixture.Create(), - UpdatedOnUtc = _fixture.Create(), - UpdatedBy = _fixture.Create() - }); + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/Fixtures/RolePermissionEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RolePermissionEntityFixture.cs similarity index 50% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/Fixtures/RolePermissionEntityFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RolePermissionEntityFixture.cs index d5e53e5b..3270b06f 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/Fixtures/RolePermissionEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RolePermissionEntityFixture.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; using Bogus; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; -using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; /// /// Fixture class for the class. @@ -15,24 +15,13 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; [ExcludeFromCodeCoverage] public class RolePermissionEntityFixture { - private readonly Fixture _fixture; - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public RolePermissionEntityFixture() - { - _fixture = new Fixture(); - _faker = new Faker(); - ConfigureCustomTypes(); - } + private readonly Faker _faker = new(); /// /// Creates a random valid . /// /// The created . - public RolePermissionEntity CreateRolePermissionModel() + public RolePermissionEntity Create() { PermissionEntity permission = new() { @@ -71,41 +60,13 @@ public class RolePermissionEntityFixture } /// - /// Configures custom type generation rules for the AutoFixture instance. + /// Creates a list of instances with randomized test data. /// - private void ConfigureCustomTypes() + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) { - _fixture.Register(() => new PermissionEntity - { - Id = _fixture.Create(), - PermissionName = _fixture.Create(), - CreatedOnUtc = _fixture.Create(), - CreatedBy = _fixture.Create(), - UpdatedOnUtc = _fixture.Create(), - UpdatedBy = _fixture.Create() - }); - - _fixture.Register(() => new RoleEntity - { - Id = _fixture.Create(), - RoleName = _fixture.Create(), - CreatedOnUtc = _fixture.Create(), - CreatedBy = _fixture.Create(), - UpdatedOnUtc = _fixture.Create(), - UpdatedBy = _fixture.Create() - }); - - _fixture.Register(() => new RolePermissionEntity - { - Id = _fixture.Create(), - RoleId = _fixture.Create(), - Role = _fixture.Create(), - PermissionId = _fixture.Create(), - Permission = _fixture.Create(), - CreatedOnUtc = _fixture.Create(), - CreatedBy = _fixture.Create(), - UpdatedOnUtc = _fixture.Create(), - UpdatedBy = _fixture.Create() - }); + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } + } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/Fixtures/GetAuthorizationQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserAuthorizationEntityFixture.cs similarity index 52% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/Fixtures/GetAuthorizationQueryFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserAuthorizationEntityFixture.cs index 1c92da38..4e1bada0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/Fixtures/GetAuthorizationQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserAuthorizationEntityFixture.cs @@ -1,42 +1,27 @@ #region ========================================================================= USING ===================================================================================== -using Bogus; using Lumina.Application.Common.DataAccess.Entities.Authorization; -using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization.Fixtures; +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; /// -/// Fixture class for the class. +/// Fixture class for the class. /// [ExcludeFromCodeCoverage] -public class GetAuthorizationQueryFixture +public class UserAuthorizationEntityFixture { - /// - /// Creates a random valid query to get authorization details. - /// - /// Optional user Id to use. If null, a random GUID will be generated. - /// The created query. - public static GetAuthorizationQuery CreateGetAuthorizationQuery(Guid? userId = null) - { - return new Faker() - .CustomInstantiator(f => new GetAuthorizationQuery( - userId ?? f.Random.Guid() - )) - .Generate(); - } - /// /// Creates a random valid authorization entity. /// - /// Optional user Id to use. If null, a random GUID will be generated. + /// Optional. The user Id to use. If null, a random GUID will be generated. /// Whether the user should have admin role. /// The created entity. - public static UserAuthorizationEntity CreateUserAuthorizationEntity(Guid? userId = null, bool isAdmin = false) + public UserAuthorizationEntity Create(Guid? userId = null, bool isAdmin = false) { string role = isAdmin ? "Admin" : string.Empty; @@ -51,4 +36,15 @@ public class GetAuthorizationQueryFixture } }; } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// Whether the users should have admin role. + /// List of configured instances. + public List CreateMany(int count = 3, bool isAdmin = false) + { + return [.. Enumerable.Range(0, count).Select(_ => Create(isAdmin: isAdmin))]; + } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/Fixtures/UserPermissionEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserPermissionEntityFixture.cs similarity index 50% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/Fixtures/UserPermissionEntityFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserPermissionEntityFixture.cs index a3b49692..f94d9984 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/Fixtures/UserPermissionEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserPermissionEntityFixture.cs @@ -1,13 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; using Bogus; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; /// /// Fixture class for the class. @@ -15,24 +13,13 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; [ExcludeFromCodeCoverage] public class UserPermissionEntityFixture { - private readonly Fixture _fixture; - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public UserPermissionEntityFixture() - { - _fixture = new Fixture(); - _faker = new Faker(); - ConfigureCustomTypes(); - } - /// /// Creates a random valid . /// + /// The user the permission is granted to. + /// The permission granted to the user. /// The created . - public UserPermissionEntity CreateUserPermissionModel(UserEntity user, PermissionEntity permission) + public UserPermissionEntity Create(UserEntity user, PermissionEntity permission) { return new Faker() .CustomInstantiator(f => new UserPermissionEntity @@ -50,22 +37,4 @@ public class UserPermissionEntityFixture .Generate(); } - /// - /// Configures custom type generation rules for the AutoFixture instance. - /// - private void ConfigureCustomTypes() - { - _fixture.Register(() => new UserPermissionEntity - { - Id = _fixture.Create(), - UserId = _fixture.Create(), - User = _fixture.Create(), - PermissionId = _fixture.Create(), - Permission = _fixture.Create(), - CreatedOnUtc = _fixture.Create(), - CreatedBy = _fixture.Create(), - UpdatedOnUtc = _fixture.Create(), - UpdatedBy = _fixture.Create() - }); - } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/Fixtures/UserRoleEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserRoleEntityFixture.cs similarity index 57% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/Fixtures/UserRoleEntityFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserRoleEntityFixture.cs index 1c44f1a6..e7142a7d 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/Fixtures/UserRoleEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserRoleEntityFixture.cs @@ -1,14 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; using Bogus; using Lumina.Application.Common.DataAccess.Entities.Authorization; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; - +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; /// /// Fixture class for the class. @@ -16,22 +14,11 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; [ExcludeFromCodeCoverage] public class UserRoleEntityFixture { - private readonly Fixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public UserRoleEntityFixture() - { - _fixture = new Fixture(); - ConfigureCustomTypes(); - } - /// /// Creates a random valid . /// /// The created . - public UserRoleEntity CreateUserRoleModel() + public UserRoleEntity Create() { return new Faker() .CustomInstantiator(f => new UserRoleEntity @@ -64,28 +51,13 @@ public class UserRoleEntityFixture } /// - /// Configures custom type generation rules for the AutoFixture instance. + /// Creates a list of instances with randomized test data. /// - private void ConfigureCustomTypes() + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) { - _fixture.Register(() => new UserEntity - { - Id = _fixture.Create(), - Username = _fixture.Create(), - Password = _fixture.Create(), - Libraries = [], - UserRole = null, - UserPermissions = [], - CreatedOnUtc = _fixture.Create(), - CreatedBy = _fixture.Create() - }); - - _fixture.Register(() => new RoleEntity - { - Id = _fixture.Create(), - RoleName = _fixture.Create(), - CreatedOnUtc = _fixture.Create(), - CreatedBy = _fixture.Create() - }); + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } + } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs similarity index 82% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookEntityFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs index 58b7161d..3e5f2b6d 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs @@ -1,19 +1,15 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; using Bogus; using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.DataAccess.UnitTests.Common.Setup; +using Lumina.Application.Fixtures.Common.Setup;using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; -using Lumina.Contracts.DTO.Common; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; #endregion -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures; +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; /// /// Fixture class for the class. @@ -21,27 +17,14 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures; [ExcludeFromCodeCoverage] public class BookEntityFixture { - private readonly Fixture _fixture; private readonly Random _random = new(); - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public BookEntityFixture() - { - _fixture = new Fixture(); - _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); - _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); - _faker = new Faker(); - ConfigureCustomTypes(); - } + private readonly Faker _faker = new(); /// /// Creates a random valid . /// /// The created . - public BookEntity CreateBookModel() + public BookEntity Create() { int releaseYear = _random.Next(2000, 2010); int reReleaseYear = _random.Next(2010, 2020); @@ -65,8 +48,8 @@ public class BookEntityFixture .RuleFor(x => x.OriginalLanguageCode, f => f.Random.String2(2)) .RuleFor(x => x.OriginalLanguageName, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(x => x.OriginalLanguageNativeName, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(x => x.Tags, f => new HashSet(CreateTags(f.Random.Number(1, 5)))) - .RuleFor(x => x.Genres, f => new HashSet(CreateGenres(f.Random.Number(1, 5)))) + .RuleFor(x => x.Tags, f => [.. CreateTags(f.Random.Number(1, 5))]) + .RuleFor(x => x.Genres, f => [.. CreateGenres(f.Random.Number(1, 5))]) .RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100))) .RuleFor(x => x.PageCount, _random.Next(100, 300)) .RuleFor(x => x.Format, f => f.PickRandom()) @@ -88,6 +71,16 @@ public class BookEntityFixture .Generate(); } + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + /// /// Creates a list of tag entities with random data. /// @@ -119,9 +112,7 @@ public class BookEntityFixture /// A properly formatted LCCN string. private string CreateLCCN(Faker f) { - string letters = new(Enumerable.Range(0, f.Random.Number(0, 3)) - .Select(_ => f.Random.Char('a', 'z')) - .ToArray()); + string letters = new([.. Enumerable.Range(0, f.Random.Number(0, 3)).Select(_ => f.Random.Char('a', 'z'))]); string digits = f.Random.String2(f.Random.Number(8, 10), "0123456789"); return letters + digits; } @@ -155,7 +146,7 @@ public class BookEntityFixture { int firstDigit = f.Random.Number(1, 9); string remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789"); - char suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' }); + char suffix = f.Random.ArrayElement(['A', 'M', 'W']); return $"OL{firstDigit}{remainingDigits}{suffix}"; } @@ -167,9 +158,7 @@ public class BookEntityFixture private string CreateGoogleBooksId(Faker f) { const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - return new string(Enumerable.Repeat(VALID_CHARS, 12) - .Select(s => s[f.Random.Number(VALID_CHARS.Length - 1)]) - .ToArray()); + return new string([.. Enumerable.Repeat(VALID_CHARS, 12).Select(s => s[f.Random.Number(VALID_CHARS.Length - 1)])]); } /// @@ -180,7 +169,11 @@ public class BookEntityFixture private static List CreateIsbns(int count) { return new Faker() - .CustomInstantiator(f => new IsbnEntity(CreateIsbn(f), f.PickRandom())) + .CustomInstantiator(f => + { + string isbnValue = CreateIsbn(f); + return new IsbnEntity(isbnValue, isbnValue.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10); + }) .Generate(count); } @@ -219,7 +212,7 @@ public class BookEntityFixture } } - // + /// /// Creates a list of book rating entities with random data. /// /// The number of ratings to create. @@ -236,19 +229,4 @@ public class BookEntityFixture .Generate(count); } - /// - /// Configures custom type generation rules for the AutoFixture instance. - /// - private void ConfigureCustomTypes() - { - _fixture.Register(() => new TagEntity(_fixture.Create())); - _fixture.Register(() => new GenreEntity(_fixture.Create())); - _fixture.Register(() => new IsbnEntity(_fixture.Create(), _fixture.Create())); - _fixture.Register(() => new BookRatingEntity( - _fixture.Create(), - _fixture.Create(), - _fixture.Create(), - _fixture.Create() - )); - } } diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingEntityFixture.cs new file mode 100644 index 00000000..e06ad74d --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingEntityFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Fixture class for the . +/// +[ExcludeFromCodeCoverage] +public class BookRatingEntityFixture +{ + private readonly Random _random = new(); + private readonly Faker _faker = new(); + + /// + /// Creates a . + /// + /// Optional. The rating value. + /// Optional. The maximum possible rating value. + /// Optional. The rating source. + /// Optional. The number of votes. + /// Whether the rating properties should be populated. Set to to create an invalid entity. + /// The created book rating entity. + public BookRatingEntity Create( + decimal? value = null, + decimal? maxValue = null, + BookRatingSource? source = null, + int? voteCount = null, + bool includeValues = true) + { + return new BookRatingEntity( + includeValues ? (value ?? _random.Next(1, 5)) : null, + includeValues ? (maxValue ?? 5) : null, + includeValues ? (source ?? _faker.PickRandom()) : null, + includeValues ? (voteCount ?? _random.Next(1, 1000)) : null + ); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/Fixtures/LibraryMetadataProviderConfigurationEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryMetadataProviderConfigurationEntityFixture.cs similarity index 65% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/Fixtures/LibraryMetadataProviderConfigurationEntityFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryMetadataProviderConfigurationEntityFixture.cs index cfb044e0..e43f575f 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/Fixtures/LibraryMetadataProviderConfigurationEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryMetadataProviderConfigurationEntityFixture.cs @@ -2,10 +2,12 @@ using Bogus; using Lumina.Application.Common.DataAccess.Entities.Plugins; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Plugins.Fixtures; +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; /// /// Fixture class for the class. @@ -20,7 +22,7 @@ public class LibraryMetadataProviderConfigurationEntityFixture /// The Id of the plugin providing the metadata. /// The rank of the metadata provider, determining the order in which providers are tried. /// The created . - public LibraryMetadataProviderConfigurationEntity CreateConfiguration(Guid libraryId, Guid pluginId, int rank) + public LibraryMetadataProviderConfigurationEntity Create(Guid libraryId, Guid pluginId, int rank) { return new Faker() .RuleFor(configuration => configuration.Id, faker => faker.Random.Guid()) @@ -34,4 +36,17 @@ public class LibraryMetadataProviderConfigurationEntityFixture .RuleFor(configuration => configuration.UpdatedBy, faker => faker.Random.Guid()) .Generate(); } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// The Id of the media library the configurations belong to. + /// The Id of the plugin providing the metadata. + /// The rank of the metadata providers. + /// List of configured instances. + public List CreateMany(int count, Guid libraryId, Guid pluginId, int rank) + { + return [.. Enumerable.Range(0, count).Select(_ => Create(libraryId, pluginId, rank))]; + } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/Fixtures/PluginEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/PluginEntityFixture.cs similarity index 77% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/Fixtures/PluginEntityFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/PluginEntityFixture.cs index 4c9d5feb..c46f8762 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/Fixtures/PluginEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/PluginEntityFixture.cs @@ -5,10 +5,11 @@ using Lumina.Domain.SharedKernel.Common.Enums.Plugins; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Text.Json; #endregion -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Plugins.Fixtures; +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; /// /// Fixture class for the class. @@ -21,7 +22,7 @@ public class PluginEntityFixture /// /// The Id of the plugin, or to generate a random one. /// The created . - public PluginEntity CreatePluginEntity(Guid? id = null) + public PluginEntity Create(Guid? id = null) { return new Faker() .RuleFor(plugin => plugin.Id, faker => id ?? faker.Random.Guid()) @@ -37,4 +38,14 @@ public class PluginEntityFixture .RuleFor(plugin => plugin.UpdatedBy, faker => faker.Random.Guid()) .Generate(); } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/Fixtures/UserEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserEntityFixture.cs similarity index 62% rename from tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/Fixtures/UserEntityFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserEntityFixture.cs index b7924bc6..99b1b7d9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/Fixtures/UserEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserEntityFixture.cs @@ -9,7 +9,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; /// /// Fixture class for the class. @@ -18,27 +18,16 @@ namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtu public class UserEntityFixture { /// - /// Creates a random valid user entity. + /// Creates a random valid . /// /// Number of libraries to generate. Default is 0. /// The created user entity. - public static UserEntity CreateUserEntity(int libraryCount = 0) + public UserEntity Create(int libraryCount = 0) { Guid userId = Guid.NewGuid(); - List libraries = [.. new Faker() - .CustomInstantiator(f => new LibraryEntity - { - Id = Guid.NewGuid(), - UserId = userId, - Title = f.Commerce.ProductName(), - LibraryType = f.PickRandom(), - ContentLocations = [], - CreatedOnUtc = f.Date.Past(), - CreatedBy = userId, - UpdatedOnUtc = null, - UpdatedBy = null - }) - .Generate(libraryCount)]; + List libraries = libraryCount > 0 + ? CreateLibraries(libraryCount, userId) + : []; return new Faker() .CustomInstantiator(f => new UserEntity @@ -61,14 +50,37 @@ public class UserEntityFixture } /// - /// Creates a list of user entities. + /// Creates a list of instances with randomized test data. /// - /// The number of entities to create. - /// The created list. - public static List CreateMany(int count = 3) + /// Number of instances to create. + /// Number of libraries to generate for each user. + /// List of configured instances. + public List CreateMany(int count = 3, int libraryCount = 0) { - return Enumerable.Range(0, count) - .Select(_ => CreateUserEntity()) - .ToList(); + return [.. Enumerable.Range(0, count).Select(_ => Create(libraryCount))]; + } + + /// + /// Creates a valid collection of user libraries. + /// + /// The number of user libraries to create. + /// The unique identifier of the user for whom to create the libraries. + /// A collection of . + private static List CreateLibraries(int count, Guid userId) + { + return new Faker() + .CustomInstantiator(f => new LibraryEntity + { + Id = Guid.NewGuid(), + UserId = userId, + Title = f.Commerce.ProductName(), + LibraryType = f.PickRandom(), + ContentLocations = [], + CreatedOnUtc = f.Date.Past(), + CreatedBy = userId, + UpdatedOnUtc = null, + UpdatedBy = null + }) + .Generate(count); } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/BogusExtensions.cs b/tests/Common/Lumina.Application.Fixtures/Common/Setup/BogusExtensions.cs similarity index 77% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/BogusExtensions.cs rename to tests/Common/Lumina.Application.Fixtures/Common/Setup/BogusExtensions.cs index 7f969784..2ceb6d84 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/BogusExtensions.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/Setup/BogusExtensions.cs @@ -1,10 +1,10 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Bogus; using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.DataAccess.UnitTests.Common.Setup; +namespace Lumina.Application.Fixtures.Common.Setup; /// /// Contains extension methods for the class. @@ -16,7 +16,7 @@ public static class BogusExtensions /// Adds random data generation support to the class. /// /// The faker instance to extend. - /// A random instance. + /// A random instance. public static DateOnly DateOnly(this Faker faker) { return System.DateOnly.FromDateTime(faker.Date.Past()); @@ -28,11 +28,11 @@ public static class BogusExtensions /// The faker instance to extend. /// The start of the interval. /// The end of the interval. - /// A random instance. + /// A random instance. public static DateOnly DateOnlyBetween(this Faker faker, DateOnly start, DateOnly end) { DateTime startDateTime = start.ToDateTime(TimeOnly.MinValue); DateTime endDateTime = end.ToDateTime(TimeOnly.MinValue); return System.DateOnly.FromDateTime(faker.Date.Between(startDateTime, endDateTime)); } -} \ No newline at end of file +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs b/tests/Common/Lumina.Application.Fixtures/Common/Setup/DateOnlySpecimenBuilder.cs similarity index 95% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs rename to tests/Common/Lumina.Application.Fixtures/Common/Setup/DateOnlySpecimenBuilder.cs index c2383b0c..f6533190 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/Setup/DateOnlySpecimenBuilder.cs @@ -4,7 +4,7 @@ using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.DataAccess.UnitTests.Common.Setup; +namespace Lumina.Application.Fixtures.Common.Setup; /// /// Represents a specimen builder for the type. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs b/tests/Common/Lumina.Application.Fixtures/Common/Setup/NullableDateOnlySpecimenBuilder.cs similarity index 88% rename from tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs rename to tests/Common/Lumina.Application.Fixtures/Common/Setup/NullableDateOnlySpecimenBuilder.cs index 83f3931f..d99648ed 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/Setup/NullableDateOnlySpecimenBuilder.cs @@ -4,10 +4,10 @@ using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Common.Setup; +namespace Lumina.Application.Fixtures.Common.Setup; /// -/// Represents a specimen builder for the type. +/// Represents a specimen builder for the type. /// [ExcludeFromCodeCoverage] public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandFixture.cs new file mode 100644 index 00000000..0823f47f --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.AddRole; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class AddRoleCommandFixture +{ + /// + /// Creates a random valid command to add a role. + /// + /// Optional. The role name. + /// Optional. The permission Ids to assign. + /// The number of permissions to generate when none are provided. + /// The created command to add a role. + public AddRoleCommand Create( + string? roleName = null, + IEnumerable? permissions = null, + int permissionCount = 3) + { + Faker faker = new Faker() + .CustomInstantiator(f => new AddRoleCommand( + default!, + default!)) + .RuleFor(x => x.RoleName, f => roleName ?? f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(x => x.Permissions, f => [.. permissions ?? Enumerable.Range(0, permissionCount).Select(_ => Guid.NewGuid())]); + return faker.Generate(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/Fixtures/DeleteRoleCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandFixture.cs similarity index 54% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/Fixtures/DeleteRoleCommandFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandFixture.cs index 15e52a9f..d1bfc2e2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/Fixtures/DeleteRoleCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandFixture.cs @@ -2,10 +2,12 @@ using Bogus; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.DeleteRole.Fixtures; +namespace Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.DeleteRole; /// /// Fixture class for the class. @@ -16,12 +18,23 @@ public class DeleteRoleCommandFixture /// /// Creates a random valid command to delete a role. /// + /// Optional. The role Id. /// The created command. - public DeleteRoleCommand CreateCommand() + public DeleteRoleCommand Create(Guid? roleId = null) { return new Faker() .CustomInstantiator(f => new DeleteRoleCommand( - Guid.NewGuid())) + roleId ?? Guid.NewGuid())) .Generate(); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandFixture.cs new file mode 100644 index 00000000..361534f9 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.UpdateRole; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateRoleCommandFixture +{ + /// + /// Creates a random valid command to update a role. + /// + /// Optional. The role Id. + /// Optional. The role name. + /// Optional. The permission Ids to assign. + /// The number of permissions to generate when none are provided. + /// The created command to update a role. + public UpdateRoleCommand Create( + Guid? roleId = null, + string? roleName = null, + IEnumerable? permissions = null, + int permissionCount = 3) + { + return new Faker() + .CustomInstantiator(f => new UpdateRoleCommand( + default, + default!, + default!)) + .RuleFor(x => x.RoleId, f => roleId ?? Guid.NewGuid()) + .RuleFor(x => x.RoleName, f => roleName ?? f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(x => x.Permissions, f => [.. permissions ?? Enumerable.Range(0, permissionCount).Select(_ => Guid.NewGuid())]) + .Generate(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/Fixtures/GetRolePermissionsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryFixture.cs similarity index 54% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/Fixtures/GetRolePermissionsQueryFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryFixture.cs index 7a2b0a02..aa85e276 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/Fixtures/GetRolePermissionsQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryFixture.cs @@ -2,10 +2,12 @@ using Bogus; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.GetRolePermissions.Fixtures; +namespace Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; /// /// Fixture class for the class. @@ -16,12 +18,23 @@ public class GetRolePermissionsQueryFixture /// /// Creates a random valid query to get role permissions. /// + /// Optional. The role Id. /// The created query. - public GetRolePermissionsQuery CreateQuery() + public GetRolePermissionsQuery Create(Guid? roleId = null) { return new Faker() .CustomInstantiator(f => new GetRolePermissionsQuery( - Guid.NewGuid())) + roleId ?? Guid.NewGuid())) .Generate(); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/Fixtures/GetRolesQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryFixture.cs similarity index 54% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/Fixtures/GetRolesQueryFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryFixture.cs index 381c6378..378feadc 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/Fixtures/GetRolesQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryFixture.cs @@ -1,9 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.GetRoles.Fixtures; +namespace Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Queries.GetRoles; /// /// Fixture class for the class. @@ -15,8 +17,18 @@ public class GetRolesQueryFixture /// Creates a random valid query to get roles. /// /// The created query. - public GetRolesQuery CreateQuery() + public GetRolesQuery Create() { return new GetRolesQuery(); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/Fixtures/GetDirectoriesQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryFixture.cs similarity index 57% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/Fixtures/GetDirectoriesQueryFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryFixture.cs index 30844e65..2c775852 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/Fixtures/GetDirectoriesQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryFixture.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures; +namespace Lumina.Application.Fixtures.Core.FileSystemManagement.Directories.Queries.GetDirectories; /// /// Fixture class for the class. @@ -15,16 +17,27 @@ public class GetDirectoriesQueryFixture /// /// Creates a random valid query to get directories. /// + /// Optional. The file system path. /// Whether to include hidden file system elements or not. /// The created query to get directories. - public static GetDirectoriesQuery CreateGetDirectoriesQuery(bool includeHiddenElements = false) + public GetDirectoriesQuery Create(string? path = null, bool includeHiddenElements = false) { return new Faker() .CustomInstantiator(f => new GetDirectoriesQuery( default!, default )) - .RuleFor(x => x.Path, f => f.System.DirectoryPath()) + .RuleFor(x => x.Path, f => path ?? f.System.DirectoryPath()) .RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryFixture.cs new file mode 100644 index 00000000..ca9fb400 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.FileSystemManagement.Drives.Queries.GetDrives; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDrivesQueryFixture +{ + /// + /// Creates a random valid query to get drives. + /// + /// The created query. + public GetDrivesQuery Create() + { + return new GetDrivesQuery(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryFixture.cs new file mode 100644 index 00000000..637860e2 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetFileSystemQueryFixture +{ + /// + /// Creates a random valid query to get the file system. + /// + /// The created query. + public GetFileSystemQuery Create() + { + return new GetFileSystemQuery(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/Fixtures/GetFilesQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryFixture.cs similarity index 57% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/Fixtures/GetFilesQueryFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryFixture.cs index 9783412f..fc1877af 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/Fixtures/GetFilesQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryFixture.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures; +namespace Lumina.Application.Fixtures.Core.FileSystemManagement.Files.Queries.GetFiles; /// /// Fixture class for the class. @@ -15,16 +17,27 @@ public class GetFilesQueryFixture /// /// Creates a random valid query to get files. /// + /// Optional. The file system path. /// Whether to include hidden file system elements or not. /// The created query to get files. - public static GetFilesQuery CreateGetFilesQuery(bool includeHiddenElements = false) + public GetFilesQuery Create(string? path = null, bool includeHiddenElements = false) { return new Faker() .CustomInstantiator(f => new GetFilesQuery( default!, default )) - .RuleFor(x => x.Path, f => f.System.FilePath()) + .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) .RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/Fixtures/GetTreeFilesQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryFixture.cs similarity index 51% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/Fixtures/GetTreeFilesQueryFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryFixture.cs index f9765f3d..195ee6ee 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/Fixtures/GetTreeFilesQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryFixture.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures; +namespace Lumina.Application.Fixtures.Core.FileSystemManagement.Files.Queries.GetTreeFiles; /// /// Fixture class for the class. @@ -13,18 +15,29 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.G public class GetTreeFilesQueryFixture { /// - /// Creates a random valid query to get files. + /// Creates a random valid query to get tree files. /// + /// Optional. The file system path. /// Whether to include hidden file system elements or not. - /// The created query to get files. - public static GetTreeFilesQuery CreateGetFilesQuery(bool includeHiddenElements = false) + /// The created query to get tree files. + public GetTreeFilesQuery Create(string? path = null, bool includeHiddenElements = false) { return new Faker() .CustomInstantiator(f => new GetTreeFilesQuery( default!, default )) - .RuleFor(x => x.Path, f => f.System.FilePath()) + .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) .RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandFixture.cs new file mode 100644 index 00000000..54e5b5ef --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Commands.CombinePath; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class CombinePathCommandFixture +{ + /// + /// Creates a random valid command to combine paths. + /// + /// Optional. The original path. + /// Optional. The new path to combine. + /// The created command. + public CombinePathCommand Create(string? originalPath = null, string? newPath = null) + { + return new Faker() + .CustomInstantiator(f => new CombinePathCommand( + default!, + default!)) + .RuleFor(x => x.OriginalPath, f => originalPath ?? f.System.FilePath()) + .RuleFor(x => x.NewPath, f => newPath ?? f.System.FilePath()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/Fixtures/SplitPathCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandFixture.cs similarity index 50% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/Fixtures/SplitPathCommandFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandFixture.cs index f502bd49..09356b05 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/Fixtures/SplitPathCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandFixture.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures; +namespace Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Commands.SplitPath; /// /// Fixture class for the class. @@ -15,13 +17,23 @@ public class SplitPathCommandFixture /// /// Creates a random valid command for splitting paths. /// + /// Optional. The file system path. /// The created command. - public static SplitPathCommand CreateSplitPathCommand() + public SplitPathCommand Create(string? path = null) { return new Faker() .CustomInstantiator(f => new SplitPathCommand( - default! - )) - .RuleFor(x => x.Path, f => f.System.FilePath()); + default!)) + .RuleFor(x => x.Path, f => path ?? f.System.FilePath()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/Fixtures/CheckPathExistsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryFixture.cs similarity index 57% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/Fixtures/CheckPathExistsQueryFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryFixture.cs index 7fd2a819..0fc9910a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/Fixtures/CheckPathExistsQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryFixture.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures; +namespace Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.CheckPathExists; /// /// Fixture class for the class. @@ -15,16 +17,27 @@ public class CheckPathExistsQueryFixture /// /// Creates a random valid query to check if paths exist. /// + /// Optional. The file system path. /// Whether to include hidden file system elements or not. /// The created query. - public static CheckPathExistsQuery CreateCheckPathExistsQuery(bool includeHiddenElements = true) + public CheckPathExistsQuery Create(string? path = null, bool includeHiddenElements = true) { return new Faker() .CustomInstantiator(f => new CheckPathExistsQuery( default!, default )) - .RuleFor(x => x.Path, f => f.System.FilePath()) + .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) .RuleFor(x => x.IncludeHiddenElements, includeHiddenElements); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryFixture.cs new file mode 100644 index 00000000..4de2e929 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.GetPathParent; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathParentQueryFixture +{ + /// + /// Creates a random valid query to get the parent of a path. + /// + /// Optional. The file system path. + /// The created query. + public GetPathParentQuery Create(string? path = null) + { + return new Faker() + .CustomInstantiator(f => new GetPathParentQuery( + default!)) + .RuleFor(x => x.Path, f => path ?? f.System.FilePath()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryFixture.cs new file mode 100644 index 00000000..cdd981b6 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.GetPathRoot; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathRootQueryFixture +{ + /// + /// Creates a random valid query to get the root of a path. + /// + /// Optional. The file system path. + /// The created query. + public GetPathRootQuery Create(string? path = null) + { + return new Faker() + .CustomInstantiator(f => new GetPathRootQuery( + default!)) + .RuleFor(x => x.Path, f => path ?? f.System.FilePath()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryFixture.cs new file mode 100644 index 00000000..6996d6e1 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.ValidatePath; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathQueryFixture +{ + /// + /// Creates a random valid query to validate a path. + /// + /// Optional. The file system path. + /// The created query. + public ValidatePathQuery Create(string? path = null) + { + return new Faker() + .CustomInstantiator(f => new ValidatePathQuery( + default!)) + .RuleFor(x => x.Path, f => path ?? f.System.FilePath()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryFixture.cs new file mode 100644 index 00000000..9d6e2a7d --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThumbnailQueryFixture +{ + /// + /// Creates a random valid query to get a thumbnail. + /// + /// Optional. The file system path. + /// Optional. The thumbnail quality. + /// The created query. + public GetThumbnailQuery Create(string? path = null, int? quality = null) + { + return new Faker() + .CustomInstantiator(f => new GetThumbnailQuery( + default!, + default + )) + .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) + .RuleFor(x => x.Quality, f => quality ?? f.Random.Int()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandFixture.cs new file mode 100644 index 00000000..d55ed0fe --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class SetupApplicationCommandFixture +{ + /// + /// Creates a random valid command for the application setup. + /// + /// Optional. The admin username. + /// Optional. The admin password. + /// Optional. The admin password confirmation. + /// Whether to use two-factor authentication. + /// The created command. + public SetupApplicationCommand Create( + string? username = null, + string? password = null, + string? passwordConfirm = null, + bool use2fa = true) + { + string resolvedPassword = password ?? "Abcd123$"; + return new Faker() + .CustomInstantiator(f => new SetupApplicationCommand( + default!, + default!, + default!, + true + )) + .RuleFor(x => x.Username, f => username ?? f.Internet.UserName()) + .RuleFor(x => x.Password, resolvedPassword) + .RuleFor(x => x.PasswordConfirm, passwordConfirm ?? resolvedPassword) + .RuleFor(x => x.Use2fa, use2fa) + .Generate(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandFixture.cs similarity index 75% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookCommandFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandFixture.cs index a1d06375..217d5283 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandFixture.cs @@ -2,19 +2,18 @@ using AutoFixture; using Bogus; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; -using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Application.Fixtures.Common.Setup; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; /// /// Fixture class for the class. @@ -22,26 +21,24 @@ namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.B [ExcludeFromCodeCoverage] public class AddBookCommandFixture { - private readonly Fixture _fixture; + private readonly Fixture _fixture = new(); private readonly Random _random = new(); - private readonly Faker _faker; + private readonly Faker _faker = new(); /// /// Initializes a new instance of the class. /// public AddBookCommandFixture() { - _fixture = new Fixture(); _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); - _faker = new Faker(); } /// /// Creates a random valid command to add a book. /// /// The created command to add a book. - public AddBookCommand CreateCommandBook() + public AddBookCommand Create() { int releaseYear = _random.Next(2000, 2010); int reReleaseYear = _random.Next(2010, 2020); @@ -82,6 +79,7 @@ public class AddBookCommandFixture )) .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50))); + Faker mediaContributorName = new Faker() .CustomInstantiator(f => new MediaContributorNameDto( default!, @@ -89,6 +87,7 @@ public class AddBookCommandFixture )) .RuleFor(e => e.DisplayName, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(e => e.LegalName, f => f.Random.String2(f.Random.Number(1, 50))); + Faker mediaContributor = new Faker() .CustomInstantiator(f => new MediaContributorDto( default!, @@ -98,16 +97,16 @@ public class AddBookCommandFixture .RuleFor(e => e.Role, mediaContributorRole); Faker rating = new Faker() - .CustomInstantiator(f => new BookRatingDto( + .CustomInstantiator(f => new BookRatingDto( default, default, default, default )) .RuleFor(e => e.Value, _random.Next(1, 5)) - .RuleFor(e => e.MaxValue, 5) - .RuleFor(e => e.Source, _fixture.Create()) - .RuleFor(e => e.VoteCount, _random.Next(1, 1000)); + .RuleFor(e => e.MaxValue, 5) + .RuleFor(e => e.Source, _fixture.Create()) + .RuleFor(e => e.VoteCount, _random.Next(1, 1000)); Faker language = new Faker() .CustomInstantiator(f => new LanguageInfoDto( @@ -221,9 +220,7 @@ public class AddBookCommandFixture .RuleFor(x => x.GoodreadsId, _random.Next(100000, 500000).ToString()) .RuleFor(x => x.LCCN, f => { - string letters = new(Enumerable.Range(0, f.Random.Number(0, 3)) - .Select(_ => f.Random.Char('a', 'z')) - .ToArray()); + string letters = new([.. Enumerable.Range(0, f.Random.Number(0, 3)).Select(_ => f.Random.Char('a', 'z'))]); string digits = f.Random.String2(f.Random.Number(8, 10), "0123456789"); return letters + digits; }) @@ -256,90 +253,19 @@ public class AddBookCommandFixture { int firstDigit = f.Random.Number(1, 9); string remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789"); - char suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' }); + char suffix = f.Random.ArrayElement(['A', 'M', 'W']); return $"OL{firstDigit}{remainingDigits}{suffix}"; }) .RuleFor(x => x.LibraryThingId, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(x => x.GoogleBooksId, f => { const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - return new string(Enumerable.Repeat(VALID_CHARS, 12) - .Select(s => s[f.Random.Number(VALID_CHARS.Length - 1)]) - .ToArray()); + return new string([.. Enumerable.Repeat(VALID_CHARS, 12).Select(s => s[f.Random.Number(VALID_CHARS.Length - 1)])]); }) .RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789")) .RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}") - .RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}") .RuleFor(p => p.ISBNs, f => isbn.Generate(f.Random.Number(1, 5))) .RuleFor(p => p.Ratings, f => rating.Generate(f.Random.Number(1, 5))) .RuleFor(x => x.Contributors, f => mediaContributor.Generate(f.Random.Number(1, 5))); } - - private void ConfigureCustomRequestTypes() - { - int releaseYear = _random.Next(2000, 2010); - int reReleaseYear = _random.Next(2010, 2020); - - _fixture.Register(() => new ReleaseInfoDto( - _faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)), - releaseYear, - _faker.DateOnlyBetween(new DateOnly(reReleaseYear, 1, 1), new DateOnly(reReleaseYear, 12, 31)), - reReleaseYear, - _fixture.Create()[2..], - _fixture.Create())); - - _fixture.Register(() => new GenreDto( - _fixture.Create() - )); - _fixture.Register(() => new TagDto( - _fixture.Create() - )); - _fixture.Register(() => new LanguageInfoDto( - _fixture.Create(), - _fixture.Create(), - _fixture.Create() - )); - _fixture.Register(() => new IsbnDto( - _fixture.Create(), - _fixture.Create() - )); - _fixture.Register(() => new BookRatingDto( - _fixture.Create(), - _fixture.Create(), - _fixture.Create(), - _fixture.Create() - )); - _fixture.Register(() => new WrittenContentMetadataDto( - _fixture.Create()[255..], - LimitStringLength(_fixture.Create(), 255), - LimitStringLength(_fixture.Create(), 2000), - _fixture.Create(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create(), - _fixture.Create(), - _fixture.Create(), - _fixture.Create() - )); - _fixture.Register(() => new BookSeriesDto( - _fixture.Create() - )); - _fixture.Register(() => new MediaContributorRoleDto( - _fixture.Create(), - _fixture.Create() - )); - _fixture.Register(() => new MediaContributorNameDto( - _fixture.Create(), - _fixture.Create() - )); - _fixture.Register(() => new MediaContributorDto( - _fixture.Create(), - _fixture.Create() - )); - } - - private static string? LimitStringLength(string? input, int maxLength) - { - return input?.Length > maxLength ? input[..maxLength] : input; - } } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandFixture.cs new file mode 100644 index 00000000..d9679c57 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.ChangePassword; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordCommandFixture +{ + /// + /// Creates a random valid command to change a password. + /// + /// Optional. The username. + /// Optional. The current password. + /// Optional. The new password. + /// Optional. The new password confirmation. + /// The created command. + public ChangePasswordCommand Create( + string? username = null, + string? currentPassword = null, + string? newPassword = null, + string? newPasswordConfirm = null) + { + string resolvedCurrentPassword = currentPassword ?? "CurrentP@ss123"; + string resolvedNewPassword = newPassword ?? "Abcd123$"; + return new Faker() + .CustomInstantiator(f => new ChangePasswordCommand( + default!, + default!, + default!, + default! + )) + .RuleFor(x => x.Username, f => username ?? f.Person.UserName) + .RuleFor(x => x.CurrentPassword, resolvedCurrentPassword) + .RuleFor(x => x.NewPassword, resolvedNewPassword) + .RuleFor(x => x.NewPasswordConfirm, newPasswordConfirm ?? resolvedNewPassword); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandFixture.cs new file mode 100644 index 00000000..2739e804 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.RecoverPassword; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordCommandFixture +{ + /// + /// Creates a random valid command to recover a password. + /// + /// Optional. The username. + /// Optional. The TOTP code. + /// The created command. + public RecoverPasswordCommand Create(string? username = null, string? totpCode = null) + { + return new Faker() + .CustomInstantiator(f => new RecoverPasswordCommand( + default!, + default! + )) + .RuleFor(x => x.Username, f => username ?? f.Person.UserName) + .RuleFor(x => x.TotpCode, f => totpCode ?? f.Random.Replace("######")); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandFixture.cs new file mode 100644 index 00000000..64320f44 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.RegisterUser; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterUserCommandFixture +{ + /// + /// Creates a random valid command for a new account registration. + /// + /// Optional. The username. + /// Optional. The password. + /// Optional. The password confirmation. + /// Whether to use two-factor authentication. + /// The created command. + public RegisterUserCommand Create( + string? username = null, + string? password = null, + string? passwordConfirm = null, + bool use2fa = true) + { + string resolvedPassword = password ?? "Abcd123$"; + return new Faker() + .CustomInstantiator(f => new RegisterUserCommand( + default!, + default!, + default!, + true + )) + .RuleFor(x => x.Username, f => username ?? f.Person.UserName) + .RuleFor(x => x.Password, resolvedPassword) + .RuleFor(x => x.PasswordConfirm, passwordConfirm ?? resolvedPassword) + .RuleFor(x => x.Use2fa, use2fa); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/Fixtures/GetUsersQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryFixture.cs similarity index 54% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/Fixtures/GetUsersQueryFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryFixture.cs index ec8762cd..f53a4646 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/Fixtures/GetUsersQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryFixture.cs @@ -1,9 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUsers; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.GetUsers.Fixtures; +namespace Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Queries.GetUsers; /// /// Fixture class for the class. @@ -15,8 +17,18 @@ public class GetUsersQueryFixture /// Creates a random valid query to get users. /// /// The created query. - public GetUsersQuery CreateQuery() + public GetUsersQuery Create() { return new GetUsersQuery(); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginUserQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryFixture.cs similarity index 52% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginUserQueryFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryFixture.cs index c3773353..35832e33 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginUserQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryFixture.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures; +namespace Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Queries.LoginUser; /// /// Fixture class for the class. @@ -15,22 +17,37 @@ public class LoginUserQueryFixture /// /// Creates a random valid query for user login. /// + /// Optional. The username. + /// Optional. The password. /// Whether to include a TOTP code in the query. /// The created query. - public static LoginUserQuery CreateLoginQuery(bool includeTotpCode = false) + public LoginUserQuery Create( + string? username = null, + string? password = null, + bool includeTotpCode = false) { - string password = "Abcd123$"; + string resolvedPassword = password ?? "Abcd123$"; Faker faker = new Faker() .CustomInstantiator(f => new LoginUserQuery( default!, default!, default )) - .RuleFor(x => x.Username, f => f.Person.UserName) - .RuleFor(x => x.Password, password); + .RuleFor(x => x.Username, f => username ?? f.Person.UserName) + .RuleFor(x => x.Password, resolvedPassword); if (includeTotpCode) faker.RuleFor(x => x.TotpCode, f => f.Random.Replace("######")); // generates 6 random digits - return faker; + return faker.Generate(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandFixture.cs new file mode 100644 index 00000000..2c6d7efc --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserRoleAndPermissionsCommandFixture +{ + /// + /// Creates a random valid command to update user role and permissions. + /// + /// Optional. The user Id. + /// Optional. The role Id to assign. If null, no role will be assigned. + /// Optional. The permission Ids to assign. + /// The number of permissions to generate when none are provided. + /// The created command. + public UpdateUserRoleAndPermissionsCommand Create( + Guid? userId = null, + Guid? roleId = null, + IEnumerable? permissions = null, + int permissionCount = 3) + { + return new Faker() + .CustomInstantiator(f => new UpdateUserRoleAndPermissionsCommand( + userId ?? Guid.NewGuid(), + roleId, + default!)) + .RuleFor(x => x.Permissions, f => [.. permissions ?? Enumerable.Range(0, permissionCount).Select(_ => Guid.NewGuid())]) + .Generate(); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryFixture.cs new file mode 100644 index 00000000..0b537b6e --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Queries.GetAuthorization; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAuthorizationQueryFixture +{ + /// + /// Creates a random valid query to get authorization details. + /// + /// Optional. The user Id to use. If null, a random GUID will be generated. + /// The created query. + public GetAuthorizationQuery Create(Guid? userId = null) + { + return new Faker() + .CustomInstantiator(f => new GetAuthorizationQuery( + userId ?? f.Random.Guid() + )) + .Generate(); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/Fixtures/GetUserPermissionsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryFixture.cs similarity index 51% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/Fixtures/GetUserPermissionsQueryFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryFixture.cs index d5ac0d84..59013332 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/Fixtures/GetUserPermissionsQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryFixture.cs @@ -2,10 +2,12 @@ using Bogus; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetUserPermissions.Fixtures; +namespace Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Queries.GetUserPermissions; /// /// Fixture class for the class. @@ -16,12 +18,23 @@ public class GetUserPermissionsQueryFixture /// /// Creates a random valid query to get user permissions. /// + /// Optional. The user Id. /// The created query. - public GetUserPermissionsQuery CreateQuery() + public GetUserPermissionsQuery Create(Guid? userId = null) { return new Faker() .CustomInstantiator(f => new GetUserPermissionsQuery( - Guid.NewGuid())) + userId ?? Guid.NewGuid())) .Generate(); } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/Fixtures/GetUserRoleQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryFixture.cs similarity index 51% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/Fixtures/GetUserRoleQueryFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryFixture.cs index be11029c..a9ffa0d9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/Fixtures/GetUserRoleQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryFixture.cs @@ -2,10 +2,12 @@ using Bogus; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetUserRole.Fixtures; +namespace Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Queries.GetUserRole; /// /// Fixture class for the class. @@ -16,12 +18,23 @@ public class GetUserRoleQueryFixture /// /// Creates a random valid query to get a user's role. /// + /// Optional. The user Id. /// The created query. - public GetUserRoleQuery CreateQuery() + public GetUserRoleQuery Create(Guid? userId = null) { return new Faker() .CustomInstantiator(f => new GetUserRoleQuery( - Guid.NewGuid())) + userId ?? Guid.NewGuid())) .Generate(); } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/Common/Lumina.Application.Fixtures/Lumina.Application.Fixtures.csproj b/tests/Common/Lumina.Application.Fixtures/Lumina.Application.Fixtures.csproj new file mode 100644 index 00000000..a6212580 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Lumina.Application.Fixtures.csproj @@ -0,0 +1,24 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + + false + false + false + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Application.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Application.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..665fb483 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,21 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Application.Fixtures")] +[assembly: AssemblyProduct("Lumina.Application.Fixtures")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("A1B2C3D4-0003-4A5B-9C0D-333333333333")] + +[assembly: InternalsVisibleTo("Lumina.Application.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.DataAccess.UnitTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/BogusExtensions.cs b/tests/Common/Lumina.Contracts.Fixtures/Common/Setup/BogusExtensions.cs similarity index 77% rename from tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/BogusExtensions.cs rename to tests/Common/Lumina.Contracts.Fixtures/Common/Setup/BogusExtensions.cs index ae6af416..2b9d43aa 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/BogusExtensions.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Common/Setup/BogusExtensions.cs @@ -1,10 +1,10 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Bogus; using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Common.Setup; +namespace Lumina.Contracts.Fixtures.Common.Setup; /// /// Contains extension methods for the class. @@ -16,7 +16,7 @@ public static class BogusExtensions /// Adds random data generation support to the class. /// /// The faker instance to extend. - /// A random instance. + /// A random instance. public static DateOnly DateOnly(this Faker faker) { return System.DateOnly.FromDateTime(faker.Date.Past()); @@ -28,11 +28,11 @@ public static class BogusExtensions /// The faker instance to extend. /// The start of the interval. /// The end of the interval. - /// A random instance. + /// A random instance. public static DateOnly DateOnlyBetween(this Faker faker, DateOnly start, DateOnly end) { DateTime startDateTime = start.ToDateTime(TimeOnly.MinValue); DateTime endDateTime = end.ToDateTime(TimeOnly.MinValue); return System.DateOnly.FromDateTime(faker.Date.Between(startDateTime, endDateTime)); } -} \ No newline at end of file +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs b/tests/Common/Lumina.Contracts.Fixtures/Common/Setup/DateOnlySpecimenBuilder.cs similarity index 94% rename from tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs rename to tests/Common/Lumina.Contracts.Fixtures/Common/Setup/DateOnlySpecimenBuilder.cs index 0caf419a..f939e081 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Common/Setup/DateOnlySpecimenBuilder.cs @@ -4,7 +4,7 @@ using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Common.Setup; +namespace Lumina.Contracts.Fixtures.Common.Setup; /// /// Represents a specimen builder for the type. diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs b/tests/Common/Lumina.Contracts.Fixtures/Common/Setup/NullableDateOnlySpecimenBuilder.cs similarity index 88% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs rename to tests/Common/Lumina.Contracts.Fixtures/Common/Setup/NullableDateOnlySpecimenBuilder.cs index 5b8dd9c8..015d227a 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Common/Setup/NullableDateOnlySpecimenBuilder.cs @@ -4,10 +4,10 @@ using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.DataAccess.UnitTests.Common.Setup; +namespace Lumina.Contracts.Fixtures.Common.Setup; /// -/// Represents a specimen builder for the type. +/// Represents a specimen builder for the type. /// [ExcludeFromCodeCoverage] public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/FileSystemItemDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/FileSystemManagement/FileSystemItemDtoFixture.cs similarity index 88% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/FileSystemItemDtoFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/DTO/FileSystemManagement/FileSystemItemDtoFixture.cs index 08488ee3..97c82f4a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/FileSystemItemDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/FileSystemManagement/FileSystemItemDtoFixture.cs @@ -6,7 +6,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.DTO.FileSystemManagement; /// /// Fixture class for the class. @@ -37,6 +37,6 @@ public class FileSystemItemDtoFixture /// The created list. public List CreateMany(int count = 3) { - return Enumerable.Range(0, count).Select(_ => Create()).ToList(); + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs new file mode 100644 index 00000000..4b6c7cec --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Fixture class for the . +/// +[ExcludeFromCodeCoverage] +public class BookRatingDtoFixture +{ + private readonly Fixture _fixture = new(); + private readonly Random _random = new(); + + /// + /// Creates a . + /// + /// Optional. The rating value. + /// Optional. The maximum possible rating value. + /// Optional. The rating source. + /// Optional. The number of votes. + /// Whether the optional source and vote count should be included. + /// The created . + public BookRatingDto Create( + decimal? value = null, + decimal? maxValue = null, + BookRatingSource? source = null, + int? voteCount = null, + bool includeOptionalProperties = true) + { + return new BookRatingDto( + value ?? _random.Next(1, 5), + maxValue ?? 5, + includeOptionalProperties ? (source ?? _fixture.Create()) : null, + includeOptionalProperties ? (voteCount ?? _random.Next(1, 1000)) : null + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs similarity index 63% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnDtoFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs index be5411cf..2b3fd680 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs @@ -2,10 +2,12 @@ using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; /// /// Fixture class for the . @@ -16,51 +18,28 @@ public class IsbnDtoFixture private readonly Random _random = new(); /// - /// Creates a valid ISBN-10 DTO. + /// Creates an with a random or explicitly requested format. /// - /// The created ISBN DTO. - public IsbnDto CreateIsbn10() + /// Optional. The ISBN value. If not provided, a valid ISBN is generated. + /// Optional. The ISBN format. If not provided, the format is left unspecified. + /// The created . + public IsbnDto Create(string? value = null, IsbnFormat? format = null) { + string resolvedValue = value ?? (format == IsbnFormat.Isbn10 ? GenerateValidIsbn10() : GenerateValidIsbn13()); return new IsbnDto( - GenerateValidIsbn10(), - IsbnFormat.Isbn10 + resolvedValue, + format ); } /// - /// Creates a valid ISBN-13 DTO. + /// Creates a list of . /// - /// The created ISBN DTO. - public IsbnDto CreateIsbn13() + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) { - return new IsbnDto( - GenerateValidIsbn13(), - IsbnFormat.Isbn13 - ); - } - - /// - /// Creates an invalid ISBN DTO. - /// - /// The created invalid ISBN DTO. - public IsbnDto CreateInvalid() - { - return new IsbnDto( - "invalid-isbn", - IsbnFormat.Isbn13 - ); - } - - /// - /// Creates an ISBN entity without format. - /// - /// The created ISBN entity. - public IsbnDto CreateWithoutFormat() - { - return new IsbnDto( - GenerateValidIsbn13(), - null - ); + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } private string GenerateValidIsbn10() diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/ChangePasswordRequestFixture.cs similarity index 61% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/ChangePasswordRequestFixture.cs index 28141e51..120b648d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/ChangePasswordRequestFixture.cs @@ -6,39 +6,36 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Requests.Authentication; /// -/// Fixture class for the class. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class ChangePasswordRequestFixture { - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public ChangePasswordRequestFixture() - { - _faker = new Faker(); - } + private readonly Faker _faker = new(); /// /// Creates a random valid . /// + /// Optional. The username for the password change. + /// Optional. The current password. + /// Optional. The new password. + /// Optional. The new password confirmation. /// The created . - public ChangePasswordRequest CreateChangePasswordRequest( + public ChangePasswordRequest Create( string? username = null, string? currentPassword = null, string? newPassword = null, string? newPasswordConfirm = null) { + string generatedNewPassword = newPassword ?? _faker.Internet.Password(); return new ChangePasswordRequest( username ?? _faker.Internet.UserName(), currentPassword ?? _faker.Internet.Password(), - newPassword ?? _faker.Internet.Password(), - newPasswordConfirm ?? _faker.Internet.Password() + generatedNewPassword, + newPasswordConfirm ?? generatedNewPassword ); } @@ -49,8 +46,6 @@ public class ChangePasswordRequestFixture /// The created list. public List CreateMany(int count = 3) { - return Enumerable.Range(0, count) - .Select(_ => CreateChangePasswordRequest()) - .ToList(); + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/LoginRequestFixture.cs similarity index 68% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginRequestFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/LoginRequestFixture.cs index 2d46f9cb..77ffd8d7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/LoginRequestFixture.cs @@ -6,29 +6,24 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Requests.Authentication; /// -/// Fixture class for the class. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class LoginRequestFixture { - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public LoginRequestFixture() - { - _faker = new Faker(); - } + private readonly Faker _faker = new(); /// /// Creates a random valid . /// + /// Optional. The username for login. + /// Optional. The password for login. + /// Optional. The TOTP code for two-factor authentication. /// The created . - public LoginRequest CreateLoginRequest( + public LoginRequest Create( string? username = null, string? password = null, string? totpCode = null) @@ -47,8 +42,6 @@ public class LoginRequestFixture /// The created list. public List CreateMany(int count = 3) { - return Enumerable.Range(0, count) - .Select(_ => CreateLoginRequest()) - .ToList(); + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/RecoverPasswordRequestFixture.cs similarity index 65% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/RecoverPasswordRequestFixture.cs index b5d1c413..1e0a8fac 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/RecoverPasswordRequestFixture.cs @@ -6,29 +6,23 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Requests.Authentication; /// -/// Fixture class for the class. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class RecoverPasswordRequestFixture { - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public RecoverPasswordRequestFixture() - { - _faker = new Faker(); - } + private readonly Faker _faker = new(); /// /// Creates a random valid . /// + /// Optional. The username for password recovery. + /// Optional. The TOTP code for verification. /// The created . - public RecoverPasswordRequest CreateRecoverPasswordRequest( + public RecoverPasswordRequest Create( string? username = null, string? totpCode = null) { @@ -45,8 +39,6 @@ public class RecoverPasswordRequestFixture /// The created list. public List CreateMany(int count = 3) { - return Enumerable.Range(0, count) - .Select(_ => CreateRecoverPasswordRequest()) - .ToList(); + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegistrationRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/RegistrationRequestFixture.cs similarity index 60% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegistrationRequestFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/RegistrationRequestFixture.cs index daa0679f..d0a620ff 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegistrationRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authentication/RegistrationRequestFixture.cs @@ -6,40 +6,35 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; +namespace Lumina.Contracts.Fixtures.Core.Requests.Authentication; /// -/// Fixture class for the class. +/// Fixture class for the record. /// [ExcludeFromCodeCoverage] public class RegistrationRequestFixture { - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public RegistrationRequestFixture() - { - _faker = new Faker(); - } + private readonly Faker _faker = new(); /// /// Creates a random valid . /// + /// Optional. The username for registration. + /// Optional. The password for registration. + /// Optional. The password confirmation. + /// Optional. Whether to use two-factor authentication. /// The created . - public RegistrationRequest CreateRegistrationRequest( + public RegistrationRequest Create( string? username = null, string? password = null, string? passwordConfirm = null, bool? use2fa = null) { - password ??= _faker.Internet.Password(); - + string generatedPassword = password ?? _faker.Internet.Password(); return new RegistrationRequest( username ?? _faker.Internet.UserName(), - password, - passwordConfirm ?? password, + generatedPassword, + passwordConfirm ?? generatedPassword, use2fa ?? _faker.Random.Bool() ); } @@ -51,8 +46,6 @@ public class RegistrationRequestFixture /// The created list. public List CreateMany(int count = 3) { - return Enumerable.Range(0, count) - .Select(_ => CreateRegistrationRequest()) - .ToList(); + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/Fixtures/GetAuthorizationRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetAuthorizationRequestFixture.cs similarity index 55% rename from tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/Fixtures/GetAuthorizationRequestFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetAuthorizationRequestFixture.cs index 56f810c6..e1565547 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/Fixtures/GetAuthorizationRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetAuthorizationRequestFixture.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Requests.Authorization; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authorization.GetAuthorization.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Requests.Authorization; /// /// Fixture class for the record. @@ -15,12 +17,22 @@ public class GetAuthorizationRequestFixture /// /// Creates a with default or specified values. /// - /// Optional user Id to use. + /// Optional. The user Id to use. /// The created . - public static GetAuthorizationRequest Create(Guid? userId = null) + public GetAuthorizationRequest Create(Guid? userId = null) { return new GetAuthorizationRequest( UserId: userId ?? Guid.NewGuid() ); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs new file mode 100644 index 00000000..45ac2a64 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Directories; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// Optional. The file system path for which to get the directories. + /// Optional. Whether to include hidden file system elements. + /// The created . + public GetDirectoriesRequest Create(string? path = null, bool? includeHiddenElements = null) + { + return new GetDirectoriesRequest( + Path: path ?? _faker.System.FilePath(), + IncludeHiddenElements: includeHiddenElements ?? _faker.Random.Bool() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetFilesRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetFilesRequestFixture.cs new file mode 100644 index 00000000..27b8e0ff --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetFilesRequestFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Files; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetFilesRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// Optional. The file system path for which to get the files. + /// Optional. Whether to include hidden file system elements. + /// The created . + public GetFilesRequest Create(string? path = null, bool? includeHiddenElements = null) + { + return new GetFilesRequest( + Path: path ?? _faker.System.FilePath(), + IncludeHiddenElements: includeHiddenElements ?? _faker.Random.Bool() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetTreeFilesRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetTreeFilesRequestFixture.cs new file mode 100644 index 00000000..a6892778 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetTreeFilesRequestFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Files; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetTreeFilesRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// Optional. The file system path for which to get the tree files. + /// Optional. Whether to include hidden file system elements. + /// The created . + public GetTreeFilesRequest Create(string? path = null, bool? includeHiddenElements = null) + { + return new GetTreeFilesRequest( + Path: path ?? _faker.System.FilePath(), + IncludeHiddenElements: includeHiddenElements ?? _faker.Random.Bool() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/CheckPathExistsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/CheckPathExistsRequestFixture.cs similarity index 60% rename from tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/CheckPathExistsRequestFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/CheckPathExistsRequestFixture.cs index 69448b86..438e7065 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/CheckPathExistsRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/CheckPathExistsRequestFixture.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; /// /// Fixture class for the record. @@ -17,8 +19,8 @@ public class CheckPathExistsRequestFixture /// /// Creates a with default or random values. /// - /// The path to check. - /// Whether to include hidden elements. + /// Optional. The path to check. + /// Optional. Whether to include hidden elements. /// The created . public CheckPathExistsRequest Create(string? path = null, bool? includeHiddenElements = null) { @@ -27,4 +29,14 @@ public class CheckPathExistsRequestFixture IncludeHiddenElements: includeHiddenElements ?? _faker.Random.Bool() ); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/CombinePathRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/CombinePathRequestFixture.cs similarity index 60% rename from tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/CombinePathRequestFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/CombinePathRequestFixture.cs index a6c65b43..ccdbd654 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/CombinePathRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/CombinePathRequestFixture.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; /// /// Fixture class for the record. @@ -17,8 +19,8 @@ public class CombinePathRequestFixture /// /// Creates a with default or random values. /// - /// The original path. - /// The new path to combine. + /// Optional. The original path. + /// Optional. The new path to combine. /// The created . public CombinePathRequest Create(string? originalPath = null, string? newPath = null) { @@ -27,4 +29,14 @@ public class CombinePathRequestFixture NewPath: newPath ?? _faker.System.FileName() ); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetPathParentRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/GetPathParentRequestFixture.cs similarity index 60% rename from tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetPathParentRequestFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/GetPathParentRequestFixture.cs index df3f0c82..99e487ab 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetPathParentRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/GetPathParentRequestFixture.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; /// /// Fixture class for the record. @@ -17,7 +19,7 @@ public class GetPathParentRequestFixture /// /// Creates a with a default or random value. /// - /// The path to get the parent of. + /// Optional. The path to get the parent of. /// The created . public GetPathParentRequest Create(string? path = null) { @@ -25,4 +27,14 @@ public class GetPathParentRequestFixture Path: path ?? _faker.System.FilePath() ); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetPathRootRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/GetPathRootRequestFixture.cs similarity index 60% rename from tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetPathRootRequestFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/GetPathRootRequestFixture.cs index e7bf83a6..f31984c7 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetPathRootRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/GetPathRootRequestFixture.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; /// /// Fixture class for the record. @@ -17,7 +19,7 @@ public class GetPathRootRequestFixture /// /// Creates a with a default or random value. /// - /// The path to get the root of. + /// Optional. The path to get the root of. /// The created . public GetPathRootRequest Create(string? path = null) { @@ -25,4 +27,14 @@ public class GetPathRootRequestFixture Path: path ?? _faker.System.FilePath() ); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/SplitPathRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/SplitPathRequestFixture.cs similarity index 61% rename from tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/SplitPathRequestFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/SplitPathRequestFixture.cs index 59b1d008..9068f4c2 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/SplitPathRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/SplitPathRequestFixture.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; /// /// Fixture class for the record. @@ -17,7 +19,7 @@ public class SplitPathRequestFixture /// /// Creates a with a default or random value. /// - /// The path to split. + /// Optional. The path to split. /// The created . public SplitPathRequest Create(string? path = null) { @@ -25,4 +27,14 @@ public class SplitPathRequestFixture Path: path ?? _faker.System.FilePath() ); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/ValidatePathRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/ValidatePathRequestFixture.cs similarity index 61% rename from tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/ValidatePathRequestFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/ValidatePathRequestFixture.cs index 3645ddfe..556af69c 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/ValidatePathRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/ValidatePathRequestFixture.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; /// /// Fixture class for the record. @@ -17,7 +19,7 @@ public class ValidatePathRequestFixture /// /// Creates a with a default or random value. /// - /// The path to validate. + /// Optional. The path to validate. /// The created . public ValidatePathRequest Create(string? path = null) { @@ -25,4 +27,14 @@ public class ValidatePathRequestFixture Path: path ?? _faker.System.FilePath() ); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetThumbnailRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequestFixture.cs similarity index 59% rename from tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetThumbnailRequestFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequestFixture.cs index b27cd17f..694cd1ec 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/GetThumbnailRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequestFixture.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Thumbnails; /// /// Fixture class for the record. @@ -17,8 +19,8 @@ public class GetThumbnailRequestFixture /// /// Creates a with default or random values. /// - /// The path of the file to get the thumbnail for. - /// The quality of the thumbnail. + /// Optional. The path of the file to get the thumbnail for. + /// Optional. The quality of the thumbnail. /// The created . public GetThumbnailRequest Create(string? path = null, int? quality = null) { @@ -27,4 +29,14 @@ public class GetThumbnailRequestFixture Quality: quality ?? _faker.Random.Int(1, 100) ); } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs similarity index 88% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookRequestFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs index 4aadaf2b..c8f5ad7d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/AddBookRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs @@ -1,19 +1,19 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using Bogus; -using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Common.Setup; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; /// /// Fixture class for the class. @@ -21,26 +21,24 @@ namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.B [ExcludeFromCodeCoverage] public class AddBookRequestFixture { - private readonly Fixture _fixture; + private readonly Fixture _fixture = new(); private readonly Random _random = new(); - private readonly Faker _faker; + private readonly Faker _faker = new(); /// /// Initializes a new instance of the class. /// public AddBookRequestFixture() { - _fixture = new Fixture(); _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); - _faker = new Faker(); } /// /// Creates a random valid request to add a book. /// /// The created request to add a book. - public AddBookRequest CreateRequestBook() + public AddBookRequest Create() { int releaseYear = _random.Next(2000, 2010); int reReleaseYear = _random.Next(2010, 2020); @@ -83,12 +81,12 @@ public class AddBookRequestFixture .RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50))); Faker mediaContributorName = new Faker() - .CustomInstantiator(f => new MediaContributorNameDto( - default!, - default! - )) - .RuleFor(e => e.DisplayName, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(e => e.LegalName, f => f.Random.String2(f.Random.Number(1, 50))); + .CustomInstantiator(f => new MediaContributorNameDto( + default!, + default! + )) + .RuleFor(e => e.DisplayName, f => f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(e => e.LegalName, f => f.Random.String2(f.Random.Number(1, 50))); Faker mediaContributor = new Faker() .CustomInstantiator(f => new MediaContributorDto( @@ -99,16 +97,16 @@ public class AddBookRequestFixture .RuleFor(e => e.Role, mediaContributorRole); Faker rating = new Faker() - .CustomInstantiator(f => new BookRatingDto( + .CustomInstantiator(f => new BookRatingDto( default, default, default, default )) .RuleFor(e => e.Value, _random.Next(1, 5)) - .RuleFor(e => e.MaxValue, 5) - .RuleFor(e => e.Source, _fixture.Create()) - .RuleFor(e => e.VoteCount, _random.Next(1, 1000)); + .RuleFor(e => e.MaxValue, 5) + .RuleFor(e => e.Source, _fixture.Create()) + .RuleFor(e => e.VoteCount, _random.Next(1, 1000)); Faker language = new Faker() .CustomInstantiator(f => new LanguageInfoDto( @@ -222,9 +220,7 @@ public class AddBookRequestFixture .RuleFor(x => x.GoodreadsId, _random.Next(100000, 500000).ToString()) .RuleFor(x => x.LCCN, f => { - string letters = new(Enumerable.Range(0, f.Random.Number(0, 3)) - .Select(_ => f.Random.Char('a', 'z')) - .ToArray()); + string letters = new([.. Enumerable.Range(0, f.Random.Number(0, 3)).Select(_ => f.Random.Char('a', 'z'))]); string digits = f.Random.String2(f.Random.Number(8, 10), "0123456789"); return letters + digits; }) @@ -257,20 +253,17 @@ public class AddBookRequestFixture { int firstDigit = f.Random.Number(1, 9); string remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789"); - char suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' }); + char suffix = f.Random.ArrayElement(['A', 'M', 'W']); return $"OL{firstDigit}{remainingDigits}{suffix}"; }) .RuleFor(x => x.LibraryThingId, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(x => x.GoogleBooksId, f => { const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - return new string(Enumerable.Repeat(VALID_CHARS, 12) - .Select(s => s[f.Random.Number(VALID_CHARS.Length - 1)]) - .ToArray()); + return new string([.. Enumerable.Repeat(VALID_CHARS, 12).Select(s => s[f.Random.Number(VALID_CHARS.Length - 1)])]); }) .RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789")) .RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}") - .RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}") .RuleFor(p => p.ISBNs, f => isbn.Generate(f.Random.Number(1, 5))) .RuleFor(p => p.Ratings, f => rating.Generate(f.Random.Number(1, 5))) .RuleFor(x => x.Contributors, f => mediaContributor.Generate(f.Random.Number(1, 5))); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/FileSystemTreeNodeResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponseFixture.cs similarity index 93% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/FileSystemTreeNodeResponseFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponseFixture.cs index f751d8f2..41deb723 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/FileSystemTreeNodeResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponseFixture.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Common; /// /// Fixture class for the class. @@ -53,6 +53,6 @@ public class FileSystemTreeNodeResponseFixture /// A list of objects with nested structures. public List CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3) { - return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList(); + return [.. Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren))]; } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Directories/DirectoryResponseFixture.cs similarity index 80% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryResponseFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Directories/DirectoryResponseFixture.cs index 20062e5e..93239e65 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Directories/DirectoryResponseFixture.cs @@ -1,12 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Bogus; +using Lumina.Contracts.Fixtures.Core.DTO.FileSystemManagement; using Lumina.Contracts.Responses.FileSystemManagement.Directories; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Directories; /// /// Fixture class for the class. @@ -20,7 +21,7 @@ public class DirectoryResponseFixture /// /// Creates a random valid . /// - /// The number of children elements to create. + /// Optional. The number of children elements to create. /// The created . public DirectoryResponse Create(int itemCount = 3) { @@ -37,10 +38,10 @@ public class DirectoryResponseFixture /// Creates a list of . /// /// The number of elements to create. - /// The number of children elemens to create for each element. + /// The number of children elements to create for each element. /// The created list. public List CreateMany(int count = 3, int itemCount = 3) { - return Enumerable.Range(0, count).Select(_ => Create(itemCount)).ToList(); + return [.. Enumerable.Range(0, count).Select(_ => Create(itemCount))]; } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Files/FileResponseFixture.cs similarity index 88% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileResponseFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Files/FileResponseFixture.cs index beb6f76c..1eae9a14 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Files/FileResponseFixture.cs @@ -6,7 +6,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Files; /// /// Fixture class for the class. @@ -38,6 +38,6 @@ public class FileResponseFixture /// The created list. public List CreateMany(int count = 3) { - return Enumerable.Range(0, count).Select(_ => Create()).ToList(); + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathSegmentResponseFixture.cs similarity index 74% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentResponseFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathSegmentResponseFixture.cs index cd0904e5..a33e07da 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathSegmentResponseFixture.cs @@ -6,7 +6,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; /// /// Fixture class for the class. @@ -19,10 +19,11 @@ public class PathSegmentResponseFixture /// /// Creates a random valid . /// + /// Optional. The path of the segment. /// The created . - public PathSegmentResponse Create() + public PathSegmentResponse Create(string? path = null) { - return new PathSegmentResponse(_faker.System.DirectoryPath()); + return new PathSegmentResponse(path ?? _faker.System.DirectoryPath()); } /// @@ -32,6 +33,6 @@ public class PathSegmentResponseFixture /// The created list. public List CreateMany(int count = 3) { - return Enumerable.Range(0, count).Select(_ => Create()).ToList(); + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSeparatorResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathSeparatorResponseFixture.cs similarity index 73% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSeparatorResponseFixture.cs rename to tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathSeparatorResponseFixture.cs index a23d6c4b..9d3be762 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSeparatorResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathSeparatorResponseFixture.cs @@ -6,7 +6,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; +namespace Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; /// /// Fixture class for the class. @@ -19,10 +19,11 @@ public class PathSeparatorResponseFixture /// /// Creates a random valid . /// + /// Optional. The path separator. /// The created . - public PathSeparatorResponse Create() + public PathSeparatorResponse Create(string? separator = null) { - return new PathSeparatorResponse(_faker.System.DirectoryPath()); + return new PathSeparatorResponse(separator ?? _faker.System.DirectoryPath()); } /// @@ -32,6 +33,6 @@ public class PathSeparatorResponseFixture /// The created list. public List CreateMany(int count = 3) { - return Enumerable.Range(0, count).Select(_ => Create()).ToList(); + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Thumbnails/ThumbnailResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Thumbnails/ThumbnailResponseFixture.cs new file mode 100644 index 00000000..a3112552 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Thumbnails/ThumbnailResponseFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Thumbnails; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ThumbnailResponseFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The thumbnail image type. + /// Optional. The thumbnail image bytes. + /// The created . + public ThumbnailResponse Create(ImageType? type = null, byte[]? bytes = null) + { + Faker faker = new(); + return new ThumbnailResponse( + type ?? faker.PickRandom(), + bytes ?? faker.Random.Bytes(20) + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Lumina.Contracts.Fixtures.csproj b/tests/Common/Lumina.Contracts.Fixtures/Lumina.Contracts.Fixtures.csproj new file mode 100644 index 00000000..62c81245 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Lumina.Contracts.Fixtures.csproj @@ -0,0 +1,24 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + + false + false + false + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Contracts.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Contracts.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..65857a23 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,22 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Contracts.Fixtures")] +[assembly: AssemblyProduct("Lumina.Contracts.Fixtures")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("A1B2C3D4-0002-4A5B-9C0D-222222222222")] + +[assembly: InternalsVisibleTo("Lumina.Application.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Presentation.Api.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Presentation.Api.IntegrationTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DateOnlySpecimenBuilder.cs b/tests/Common/Lumina.Domain.Fixtures/Common/Setup/DateOnlySpecimenBuilder.cs similarity index 93% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DateOnlySpecimenBuilder.cs rename to tests/Common/Lumina.Domain.Fixtures/Common/Setup/DateOnlySpecimenBuilder.cs index 4a356aa5..0bebd666 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DateOnlySpecimenBuilder.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Common/Setup/DateOnlySpecimenBuilder.cs @@ -4,7 +4,7 @@ using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; +namespace Lumina.Domain.Fixtures.Common.Setup; /// /// Represents a specimen builder for the type. diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs b/tests/Common/Lumina.Domain.Fixtures/Common/Setup/NullableDateOnlySpecimenBuilder.cs similarity index 87% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs rename to tests/Common/Lumina.Domain.Fixtures/Common/Setup/NullableDateOnlySpecimenBuilder.cs index 1d827c15..0b348bd7 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Common/Setup/NullableDateOnlySpecimenBuilder.cs @@ -4,10 +4,10 @@ using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; +namespace Lumina.Domain.Fixtures.Common.Setup; /// -/// Represents a specimen builder for the type. +/// Represents a specimen builder for the type. /// [ExcludeFromCodeCoverage] public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/DirectoryFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/DirectoryFixture.cs similarity index 90% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/DirectoryFixture.cs rename to tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/DirectoryFixture.cs index 59919282..a69d050d 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/DirectoryFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/DirectoryFixture.cs @@ -10,23 +10,15 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities.Fixtures; +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; /// -/// Fixture class for the class. +/// Fixture class for the entity. /// [ExcludeFromCodeCoverage] public class DirectoryFixture { - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public DirectoryFixture() - { - _faker = new Faker(); - } + private readonly Faker _faker = new(); /// /// Creates a random valid . @@ -39,7 +31,7 @@ public class DirectoryFixture /// Optional. A list of child items to be added to the directory. /// A newly created instance. /// Thrown if the creation fails. - public Directory CreateDirectory( + public Directory Create( string? path = null, string? name = null, Optional? dateCreated = null, @@ -72,7 +64,7 @@ public class DirectoryFixture /// The created list. public List CreateMany(int count = 3) { - return [.. Enumerable.Range(0, count).Select(_ => CreateDirectory())]; + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } /// @@ -104,6 +96,6 @@ public class DirectoryFixture for (int i = 0; i < childCount; i++) childItems.Add(CreateNestedDirectory(currentDepth + 1, maxDepth, maxChildrenPerDirectory)); } - return CreateDirectory(childItems: childItems); + return Create(childItems: childItems); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/FileFixture.cs similarity index 50% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileFixture.cs rename to tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/FileFixture.cs index 10e2e435..5e730d0d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Fixtures/FileFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/FileFixture.cs @@ -9,40 +9,40 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; /// -/// Fixture class for the class. +/// Fixture class for the entity. /// [ExcludeFromCodeCoverage] public class FileFixture { - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public FileFixture() - { - _faker = new Faker(); - } + private readonly Faker _faker = new(); /// /// Creates a random valid . /// + /// Optional. The file path. If not provided, a random path is generated. + /// Optional. The file name. If not provided, a random name is generated. + /// Optional. The file's creation date. If not provided, a random past date is generated. + /// Optional. The file's modification date. If not provided, a recent date is generated. + /// Optional. The file size. If not provided, a random size is generated. + /// Optional. The file's status. If not provided, a random status is assigned. + /// Whether the file should include creation and modification dates. /// The created . - public File CreateFile( - string? path = null, - string? name = null, - Optional? dateCreated = null, - Optional? dateModified = null, - long? size = null, - FileSystemItemStatus? status = null) + public File Create( + string? path = null, + string? name = null, + Optional? dateCreated = null, + Optional? dateModified = null, + long? size = null, + FileSystemItemStatus? status = null, + bool includeDates = true) { path ??= _faker.System.FilePath(); name ??= _faker.System.FileName(); - dateCreated ??= Optional.Some(_faker.Date.Past()); - dateModified ??= Optional.Some(_faker.Date.Recent()); + dateCreated ??= includeDates ? Optional.Some(_faker.Date.Past()) : Optional.None(); + dateModified ??= includeDates ? Optional.Some(_faker.Date.Recent()) : Optional.None(); size ??= _faker.Random.Long(); status ??= _faker.PickRandom(); @@ -60,22 +60,6 @@ public class FileFixture /// The created list. public List CreateMany(int count = 3) { - return [.. Enumerable.Range(0, count).Select(_ => CreateFile())]; - } - - /// - /// Creates a random valid , without creationg and modification dates. - /// - /// - public static File CreateFileWithoutDates() - { - return File.Create( - "/path/to/file_without_dates.txt", - "file_without_dates.txt", - Optional.None(), - Optional.None(), - 2048, - FileSystemItemStatus.Accessible - ).Value; + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/UnixRootItemFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItemFixture.cs similarity index 54% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/UnixRootItemFixture.cs rename to tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItemFixture.cs index 25702e7c..8fe5025e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/UnixRootItemFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItemFixture.cs @@ -4,13 +4,15 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.FileSystem.Fixtures; +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; /// -/// Fixture class for the class. +/// Fixture class for the entity. /// [ExcludeFromCodeCoverage] public class UnixRootItemFixture @@ -20,14 +22,25 @@ public class UnixRootItemFixture /// /// Creates a random valid . /// + /// Optional. The root item status. /// The created . - public UnixRootItem Create() + public UnixRootItem Create(FileSystemItemStatus? status = null) { Result unixRootItemResult = UnixRootItem.Create( - _faker.PickRandom() + status ?? _faker.PickRandom() ); if (unixRootItemResult.IsFailure) - throw new InvalidOperationException("Failed to create File: " + string.Join(", ", unixRootItemResult.Errors)); + throw new InvalidOperationException("Failed to create UnixRootItem: " + string.Join(", ", unixRootItemResult.Errors)); return unixRootItemResult.Value; } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItemFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItemFixture.cs new file mode 100644 index 00000000..b8eb5da8 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItemFixture.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; + +/// +/// Fixture class for the entity. +/// +[ExcludeFromCodeCoverage] +public class WindowsRootItemFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The root item path. + /// Optional. The root item name. + /// Optional. The root item status. + /// The created . + public WindowsRootItem Create( + string? path = null, + string? name = null, + FileSystemItemStatus? status = null) + { + Result windowsRootItemResult = WindowsRootItem.Create( + path ?? _faker.System.FilePath(), + name ?? _faker.System.FileName(), + status ?? _faker.PickRandom() + ); + if (windowsRootItemResult.IsFailure) + throw new InvalidOperationException("Failed to create WindowsRootItem: " + string.Join(", ", windowsRootItemResult.Errors)); + return windowsRootItemResult.Value; + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Fixtures/FileSystemItemFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/FileSystemItemFixture.cs similarity index 83% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Fixtures/FileSystemItemFixture.cs rename to tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/FileSystemItemFixture.cs index 4a231305..9e891a3a 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Fixtures/FileSystemItemFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/FileSystemItemFixture.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Fixtures; +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; /// -/// Fixture class for the class. +/// Test-support class that allows the abstract type to be instantiated in tests. /// [ExcludeFromCodeCoverage] public class FileSystemItemFixture : FileSystemItem diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/Fixtures/INonExistentPlatformContextFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/INonExistentPlatformContextFixture.cs similarity index 77% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/Fixtures/INonExistentPlatformContextFixture.cs rename to tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/INonExistentPlatformContextFixture.cs index 2bcfe0f5..e505a7fc 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/Fixtures/INonExistentPlatformContextFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/INonExistentPlatformContextFixture.cs @@ -2,7 +2,7 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Platform.Fixtures; +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; /// /// Fixture interface for non existing platform context. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Fixtures/FileSystemPathIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdFixture.cs similarity index 59% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Fixtures/FileSystemPathIdFixture.cs rename to tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdFixture.cs index e073633a..aa71867a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Fixtures/FileSystemPathIdFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdFixture.cs @@ -3,33 +3,27 @@ using Bogus; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Fixtures; +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; /// -/// Fixture class for the class. +/// Fixture class for the value object. /// [ExcludeFromCodeCoverage] public class FileSystemPathIdFixture { - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public FileSystemPathIdFixture() - { - _faker = new Faker(); - } + private readonly Faker _faker = new(); /// /// Creates a random valid . /// - /// The path of the file system path element. + /// Optional. The path of the file system path element. /// The created . - public FileSystemPathId CreateFileSystemPathId(string? path = null) + public FileSystemPathId Create(string? path = null) { path ??= _faker.System.FilePath(); @@ -39,4 +33,14 @@ public class FileSystemPathIdFixture throw new InvalidOperationException("Failed to create FileSystemPathId: " + string.Join(", ", fileSystemPathIdResult.Errors)); return fileSystemPathIdResult.Value; } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/PathSegmentFixture.cs similarity index 71% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs rename to tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/PathSegmentFixture.cs index 1d6fc891..e73fbb2d 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/PathSegmentFixture.cs @@ -8,32 +8,27 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; /// -/// Fixture class for the class. +/// Fixture class for the value object. /// [ExcludeFromCodeCoverage] public class PathSegmentFixture { - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public PathSegmentFixture() - { - _faker = new Faker(); - } + private readonly Faker _faker = new(); /// /// Creates a random valid . /// + /// Optional. The segment name. + /// Whether the segment is a directory. + /// Whether the segment is a drive. /// The created . - public PathSegment CreatePathSegment( - string? name = null, - bool? isDirectory = null, - bool? isDrive = null) + public PathSegment Create( + string? name = null, + bool? isDirectory = null, + bool? isDrive = null) { name ??= _faker.System.FileName(); isDirectory ??= true; @@ -53,6 +48,6 @@ public class PathSegmentFixture /// The created list. public List CreateMany(int count = 3) { - return [.. Enumerable.Range(0, count).Select(_ => CreatePathSegment())]; + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/StreamInfoFixture.cs similarity index 71% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs rename to tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/StreamInfoFixture.cs index 29f6d603..f66a9d6e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/StreamInfoFixture.cs @@ -8,37 +8,29 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; /// -/// Fixture class for the class. +/// Fixture class for the value object. /// [ExcludeFromCodeCoverage] public class StreamInfoFixture { - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public StreamInfoFixture() - { - _faker = new Faker(); - } + private readonly Faker _faker = new(); /// /// Creates a random valid . /// - /// Optional. The unique identifier for the stream. If not provided, a default value may be used. - /// Optional. The MIME type of the stream (e.g., video/mp4, audio/mpeg). If not provided, a default MIME type may be used. - /// Optional. The bitrate of the stream in kbps. If not provided, a default value may be used. - /// Optional. The codec used for the stream (e.g., H.264, AAC). If not provided, a default codec may be used. - /// Optional. The video resolution (e.g., 1920x1080). If not provided, a default resolution may be used. - /// Optional. The frame rate of the video stream in frames per second (fps). If not provided, a default frame rate may be used. - /// Optional. The sample rate of the audio stream in Hz. If not provided, a default sample rate may be used. - /// Optional. The number of audio channels (e.g., 2 for stereo, 6 for 5.1 surround). If not provided, a default channel count may be used. + /// Optional. The unique identifier for the stream. + /// Optional. The MIME type of the stream. + /// Optional. The bitrate of the stream in kbps. + /// Optional. The codec used for the stream. + /// Optional. The video resolution. + /// Optional. The frame rate of the video stream. + /// Optional. The sample rate of the audio stream. + /// Optional. The number of audio channels. /// The created . - public StreamInfo CreateStreamInfo( + public StreamInfo Create( string? streamId = null, string? mimeType = null, int? bitrate = null, @@ -72,6 +64,6 @@ public class StreamInfoFixture /// The created list. public List CreateMany(int count = 3) { - return [.. Enumerable.Range(0, count).Select(_ => CreateStreamInfo())]; + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/ThumbnailFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/ThumbnailFixture.cs similarity index 72% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/ThumbnailFixture.cs rename to tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/ThumbnailFixture.cs index 7b05d1b3..a2fcbb2b 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/ThumbnailFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/ThumbnailFixture.cs @@ -1,29 +1,21 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; /// -/// Fixture class for the class. +/// Fixture class for the value object. /// [ExcludeFromCodeCoverage] public class ThumbnailFixture { - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public ThumbnailFixture() - { - _faker = new Faker(); - } + private readonly Faker _faker = new(); /// /// Creates a random valid . @@ -31,7 +23,7 @@ public class ThumbnailFixture /// Optional. The of the thumbnail. If not provided, a random image type is selected. /// Optional. The byte array representing the image data. If not provided, a random 1KB byte array is generated. /// A newly created instance. - public Thumbnail CreateThumbnail(ImageType? type = null, byte[]? bytes = null) + public Thumbnail Create(ImageType? type = null, byte[]? bytes = null) { type ??= _faker.PickRandom(); bytes ??= _faker.Random.Bytes(1024); // Generate 1KB of random bytes @@ -46,6 +38,6 @@ public class ThumbnailFixture /// The created list. public List CreateMany(int count = 3) { - return Enumerable.Range(0, count).Select(_ => CreateThumbnail()).ToList(); + return [.. Enumerable.Range(0, count).Select(_ => Create())]; } } diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs new file mode 100644 index 00000000..b9ab4b10 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs @@ -0,0 +1,107 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; + +/// +/// Fixture class for the domain aggregate. +/// +[ExcludeFromCodeCoverage] +public class LibraryFixture +{ + private readonly Faker _faker = new(); + private readonly Random _random = new(); + + /// + /// Creates a random valid domain aggregate. + /// + /// Optional. The library Id. + /// Optional. The Id of the user that owns the library. + /// Optional. The library title. + /// Optional. The library type. + /// Optional. The content locations of the library. + /// Optional. The cover image of the library. + /// Whether the library is enabled. + /// Whether the library is locked. + /// Whether metadata download from the web is enabled. + /// Whether metadata should be saved in the media directories. + /// Whether unchanged directories should be skipped during scan. + /// Optional. The scan Ids associated with the library. + /// The created . + public Library Create( + Guid? id = null, + Guid? userId = null, + string? title = null, + LibraryType? libraryType = null, + IEnumerable? contentLocations = null, + string? coverImage = null, + bool isEnabled = true, + bool isLocked = false, + bool downloadMetadataFromWeb = true, + bool shouldSaveMetadataInMediaDirectories = false, + bool shouldSkipUnchangedDirectoriesDuringScan = false, + IEnumerable? scanIds = null) + { + List validPaths = + [ + "C:/Media", + "D:/Books", + "E:/Digital Library", + "F:/Content" + ]; + + List resolvedScanIds = scanIds is null ? [ScanId.CreateUnique(), ScanId.CreateUnique()] : [.. scanIds.Select(scanId => ScanId.Create(scanId))]; + + Result library = id is null ? + Library.Create( + userId is not null ? UserId.Create(userId.Value) : UserId.CreateUnique(), + title ?? _faker.Random.String2(_faker.Random.Number(1, 50)), + libraryType ?? _faker.PickRandom(), + contentLocations ?? validPaths.Take(_random.Next(1, validPaths.Count)), + coverImage ?? _faker.System.FilePath(), + isEnabled, + isLocked, + downloadMetadataFromWeb, + shouldSaveMetadataInMediaDirectories, + shouldSkipUnchangedDirectoriesDuringScan, + resolvedScanIds + ) : + Library.Create( + LibraryId.Create(id.Value), + userId is not null ? UserId.Create(userId.Value) : UserId.CreateUnique(), + title ?? _faker.Random.String2(_faker.Random.Number(1, 50)), + libraryType ?? _faker.PickRandom(), + contentLocations ?? validPaths.Take(_random.Next(1, validPaths.Count)), + coverImage ?? _faker.System.FilePath(), + isEnabled, + isLocked, + downloadMetadataFromWeb, + shouldSaveMetadataInMediaDirectories, + shouldSkipUnchangedDirectoriesDuringScan, + resolvedScanIds + ); + + return library.Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs similarity index 76% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookFixture.cs rename to tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs index 3886a9df..19f28754 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; -using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; @@ -9,6 +7,8 @@ using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.Boo using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Fixtures.Common.Setup; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Collections.Generic; @@ -16,36 +16,33 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; /// -/// Fixture class for the domain entity. +/// Fixture class for the domain aggregate. /// [ExcludeFromCodeCoverage] public class BookFixture { - private readonly Fixture _fixture; - private readonly IsbnFixture _isbnFixture; - private readonly BookRatingFixture _bookRatingFixture; + private readonly Fixture _fixture = new(); + private readonly IsbnFixture _isbnFixture = new(); + private readonly BookRatingFixture _bookRatingFixture = new(); /// /// Initializes a new instance of the class. /// public BookFixture() { - _fixture = new Fixture(); _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); - _isbnFixture = new IsbnFixture(); - _bookRatingFixture = new BookRatingFixture(); ConfigureCustomDomainTypes(); } /// - /// Creates a random valid book domain entity. + /// Creates a random valid domain aggregate. /// - /// The created book domain entity. - public Book CreateDomainBook() + /// The created domain aggregate. + public Book Create() { return Book.Create( LibraryId.Create(_fixture.Create()), @@ -70,6 +67,16 @@ public class BookFixture ).Value; } + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + private void ConfigureCustomDomainTypes() { _fixture.Register(() => Optional.Some(_fixture.Create())); @@ -77,8 +84,8 @@ public class BookFixture _fixture.Register(() => { - int originalYear = _fixture.Create>().First(y => y >= 1900 && y <= 2025); - int reReleaseYear = _fixture.Create>().First(y => y >= originalYear && y <= 2025); + int originalYear = _fixture.Create>().First(year => year >= 1900 && year <= 2025); + int reReleaseYear = _fixture.Create>().First(year => year >= originalYear && year <= 2025); return ReleaseInfo.Create( Optional.Some(DateOnly.FromDateTime(new DateTime(originalYear, 1, 1))), @@ -111,8 +118,8 @@ public class BookFixture _fixture.Create>() ).Value); - _fixture.Register(() => _isbnFixture.CreateIsbn13()); + _fixture.Register(() => _isbnFixture.Create()); - _fixture.Register(() => _bookRatingFixture.CreateBookRating()); + _fixture.Register(() => _bookRatingFixture.Create()); } } diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRatingFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRatingFixture.cs new file mode 100644 index 00000000..0305ecd6 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRatingFixture.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class BookRatingFixture +{ + private readonly Fixture _fixture = new(); + private readonly Random _random = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The rating value. + /// Optional. The maximum possible rating value. + /// Optional. The rating source. If not provided, a random source is selected. + /// Optional. The number of votes. If not provided, a random vote count is selected. + /// The created . + public BookRating Create( + decimal? value = null, + decimal? maxValue = null, + Optional? source = null, + Optional? voteCount = null) + { + maxValue ??= _random.Next(5, 10); + value ??= _random.Next(1, (int)maxValue.Value); + source ??= Optional.Some(_fixture.Create()); + voteCount ??= Optional.Some(_random.Next(1, 1000)); + + return BookRating.Create(value.Value, maxValue.Value, source.Value, voteCount.Value).Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + List result = []; + for (int i = 0; i < count; i++) + result.Add(Create()); + return result; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnFixture.cs similarity index 59% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnFixture.cs rename to tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnFixture.cs index aee2776d..eb0117f8 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/IsbnFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnFixture.cs @@ -1,14 +1,15 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; /// -/// Fixture class for the domain entity. +/// Fixture class for the domain value object. /// [ExcludeFromCodeCoverage] public class IsbnFixture @@ -16,23 +17,28 @@ public class IsbnFixture private readonly Random _random = new(); /// - /// Creates a valid ISBN-10. + /// Creates a valid with a random or explicitly requested format. /// - /// The created ISBN. - public Isbn CreateIsbn10() + /// Optional. The requested . If not provided, a random format is selected. + /// The created . + public Isbn Create(IsbnFormat? format = null) { - string isbn = GenerateValidIsbn10(); - return Isbn.Create(isbn, IsbnFormat.Isbn10).Value; + IsbnFormat targetFormat = format ?? (_random.Next(2) == 0 ? IsbnFormat.Isbn10 : IsbnFormat.Isbn13); + string isbn = targetFormat == IsbnFormat.Isbn10 ? GenerateValidIsbn10() : GenerateValidIsbn13(); + return Isbn.Create(isbn, targetFormat).Value; } /// - /// Creates a valid ISBN-13. + /// Creates multiple instances with randomized test data. /// - /// The created ISBN. - public Isbn CreateIsbn13() + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) { - string isbn = GenerateValidIsbn13(); - return Isbn.Create(isbn, IsbnFormat.Isbn13).Value; + List result = []; + for (int i = 0; i < count; i++) + result.Add(Create()); + return result; } private string GenerateValidIsbn10() diff --git a/tests/Common/Lumina.Domain.Fixtures/Lumina.Domain.Fixtures.csproj b/tests/Common/Lumina.Domain.Fixtures/Lumina.Domain.Fixtures.csproj new file mode 100644 index 00000000..36a8369e --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Lumina.Domain.Fixtures.csproj @@ -0,0 +1,24 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + + false + false + false + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Domain.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Domain.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..62ad45b5 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,21 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Domain.Fixtures")] +[assembly: AssemblyProduct("Lumina.Domain.Fixtures")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("A1B2C3D4-0001-4A5B-9C0D-111111111111")] + +[assembly: InternalsVisibleTo("Lumina.Domain.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Application.UnitTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/Fixtures/ImageTypeFixture.cs b/tests/Common/Lumina.Domain.SharedKernel.Fixtures/Common/Enums/PhotoLibrary/ImageTypeFixture.cs similarity index 89% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/Fixtures/ImageTypeFixture.cs rename to tests/Common/Lumina.Domain.SharedKernel.Fixtures/Common/Enums/PhotoLibrary/ImageTypeFixture.cs index d1984776..9aeb6c1b 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/Fixtures/ImageTypeFixture.cs +++ b/tests/Common/Lumina.Domain.SharedKernel.Fixtures/Common/Enums/PhotoLibrary/ImageTypeFixture.cs @@ -9,17 +9,17 @@ using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.PixelFormats; using System.Diagnostics.CodeAnalysis; using System.IO; +using Xunit; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services.Fixtures; +namespace Lumina.Domain.SharedKernel.Fixtures.Common.Enums.PhotoLibrary; /// -/// Fixture class for the enum. +/// Test-support class providing image byte data for each supported . /// [ExcludeFromCodeCoverage] public class ImageTypeFixture : TheoryData { - /// /// Initializes a new instance of the class. /// diff --git a/tests/Common/Lumina.Domain.SharedKernel.Fixtures/Lumina.Domain.SharedKernel.Fixtures.csproj b/tests/Common/Lumina.Domain.SharedKernel.Fixtures/Lumina.Domain.SharedKernel.Fixtures.csproj new file mode 100644 index 00000000..8df01af4 --- /dev/null +++ b/tests/Common/Lumina.Domain.SharedKernel.Fixtures/Lumina.Domain.SharedKernel.Fixtures.csproj @@ -0,0 +1,22 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + + false + false + false + + + + + + + + + + + \ No newline at end of file diff --git a/tests/Common/Lumina.Domain.SharedKernel.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Domain.SharedKernel.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..30821396 --- /dev/null +++ b/tests/Common/Lumina.Domain.SharedKernel.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,13 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("Lumina.Domain.SharedKernel.Fixtures")] +[assembly: AssemblyProduct("Lumina.Domain.SharedKernel.Fixtures")] + +[assembly: ComVisible(false)] + +[assembly: Guid("A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61")] + +[assembly: InternalsVisibleTo("Lumina.Domain.UnitTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] \ No newline at end of file diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/EncryptionSettingsDtoFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/EncryptionSettingsDtoFixture.cs new file mode 100644 index 00000000..e0972944 --- /dev/null +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/EncryptionSettingsDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Security.Cryptography; +#endregion + +namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class EncryptionSettingsDtoFixture +{ + /// + /// Creates a valid with a random 256-bit key. + /// + /// Optional. The secret key. If not provided, a valid 256-bit (32 byte) key for AES-256 is generated. + /// The created . + public EncryptionSettingsDto Create(string? secretKey = null) + { + byte[] key = new byte[32]; + RandomNumberGenerator.Fill(key); + + return new EncryptionSettingsDto + { + SecretKey = secretKey ?? Convert.ToBase64String(key) + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/JwtSettingsDtoFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/JwtSettingsDtoFixture.cs new file mode 100644 index 00000000..a83474a0 --- /dev/null +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/JwtSettingsDtoFixture.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Security.Cryptography; +#endregion + +namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class JwtSettingsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a valid . + /// + /// Optional. The secret key used to sign the JWT. + /// Optional. The duration (in minutes) for which the JWT is valid. + /// Optional. The issuer of the JWT. + /// Optional. The intended audience for the JWT. + /// The created . + public JwtSettingsDto Create( + string? secretKey = null, + int? expiryMinutes = null, + string? issuer = null, + string? audience = null) + { + byte[] key = new byte[32]; + RandomNumberGenerator.Fill(key); + + return new JwtSettingsDto + { + SecretKey = secretKey ?? Convert.ToBase64String(key), + ExpiryMinutes = expiryMinutes ?? _faker.Random.Int(1, 120), + Issuer = issuer ?? _faker.Company.CompanyName(), + Audience = audience ?? _faker.Company.CompanyName() + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/Fixtures/OptionsBuilderValidationUtilitiesFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Utilities/OptionsBuilderValidationUtilitiesFixture.cs similarity index 67% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/Fixtures/OptionsBuilderValidationUtilitiesFixture.cs rename to tests/Common/Lumina.Infrastructure.Fixtures/Common/Utilities/OptionsBuilderValidationUtilitiesFixture.cs index 4ead5274..e9264e5f 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/Fixtures/OptionsBuilderValidationUtilitiesFixture.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Utilities/OptionsBuilderValidationUtilitiesFixture.cs @@ -2,10 +2,10 @@ using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Infrastructure.UnitTests.Common.Utilities.Fixtures; +namespace Lumina.Infrastructure.Fixtures.Common.Utilities; /// -/// Contains unit tests for the class. +/// Test-support placeholder class for options builder validation utilities tests. /// [ExcludeFromCodeCoverage] public class OptionsBuilderValidationUtilitiesFixture diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/Fixtures/ValidationOptionsFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Validation/ValidationOptionsFixture.cs similarity index 68% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/Fixtures/ValidationOptionsFixture.cs rename to tests/Common/Lumina.Infrastructure.Fixtures/Common/Validation/ValidationOptionsFixture.cs index 8a793d55..32da0140 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/Fixtures/ValidationOptionsFixture.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Validation/ValidationOptionsFixture.cs @@ -2,10 +2,10 @@ using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Infrastructure.UnitTests.Common.Validation.Fixtures; +namespace Lumina.Infrastructure.Fixtures.Common.Validation; /// -/// Contains unit tests for the class. +/// Test-support placeholder class for validation options tests. /// [ExcludeFromCodeCoverage] public class ValidationOptionsFixture diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/JwtTokenGeneratorFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authentication/JwtTokenGeneratorFixture.cs similarity index 65% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/JwtTokenGeneratorFixture.cs rename to tests/Common/Lumina.Infrastructure.Fixtures/Core/Authentication/JwtTokenGeneratorFixture.cs index bbebb1b8..b5694ca3 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/JwtTokenGeneratorFixture.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authentication/JwtTokenGeneratorFixture.cs @@ -1,14 +1,15 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures; +namespace Lumina.Infrastructure.Fixtures.Core.Authentication; /// -/// Fixture class for JWT token generation tests. +/// Test-support class for JWT token generation tests. /// [ExcludeFromCodeCoverage] public class JwtTokenGeneratorFixture @@ -19,15 +20,7 @@ public class JwtTokenGeneratorFixture /// The created settings model. public static JwtSettingsDto CreateJwtSettings() { - return new Faker() - .CustomInstantiator(f => new JwtSettingsDto - { - SecretKey = "this-is-a-very-long-secret-key-for-testing-jwt-tokens", - ExpiryMinutes = 30, - Issuer = "test-issuer", - Audience = "test-audience" - }) - .Generate(); + return new JwtSettingsDtoFixture().Create(); } /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/QRCodeGeneratorFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authentication/QRCodeGeneratorFixture.cs similarity index 91% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/QRCodeGeneratorFixture.cs rename to tests/Common/Lumina.Infrastructure.Fixtures/Core/Authentication/QRCodeGeneratorFixture.cs index d9a27946..6aa7465e 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/QRCodeGeneratorFixture.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authentication/QRCodeGeneratorFixture.cs @@ -4,10 +4,10 @@ using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures; +namespace Lumina.Infrastructure.Fixtures.Core.Authentication; /// -/// Fixture class for QR code generation tests. +/// Test-support class for QR code generation tests. /// [ExcludeFromCodeCoverage] public class QRCodeGeneratorFixture diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Fixtures/AuthorizationServiceFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/AuthorizationServiceFixture.cs similarity index 68% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Fixtures/AuthorizationServiceFixture.cs rename to tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/AuthorizationServiceFixture.cs index 2b500744..4e351ce4 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Fixtures/AuthorizationServiceFixture.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/AuthorizationServiceFixture.cs @@ -2,15 +2,16 @@ using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using Lumina.Infrastructure.Core.Authorization; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Infrastructure.UnitTests.Core.Authorization.Fixtures; +namespace Lumina.Infrastructure.Fixtures.Core.Authorization; /// -/// Fixture class for the tests. +/// Test-support class for the tests. /// [ExcludeFromCodeCoverage] public class AuthorizationServiceFixture @@ -30,7 +31,6 @@ public class AuthorizationServiceFixture List userPermissions = []; UserRoleEntity? userRole = null; - // create role first if rolePermissions is provided if (rolePermissions is not null) { foreach (KeyValuePair> rolePerm in rolePermissions) @@ -72,11 +72,11 @@ public class AuthorizationServiceFixture { Id = Guid.NewGuid(), UserId = userId, + User = null!, RoleId = roleId, Role = role, CreatedOnUtc = utcNow, - CreatedBy = userId, - User = null! + CreatedBy = userId }; } } @@ -119,56 +119,6 @@ public class AuthorizationServiceFixture } } - if (rolePermissions is not null) - { - foreach (KeyValuePair> rolePerm in rolePermissions) - { - Guid roleId = Guid.NewGuid(); - RoleEntity role = new() - { - Id = roleId, - RoleName = rolePerm.Key, - CreatedOnUtc = utcNow, - CreatedBy = userId, - RolePermissions = [] - }; - - foreach (AuthorizationPermission permission in rolePerm.Value) - { - Guid permissionId = Guid.NewGuid(); - PermissionEntity permissionEntity = new() - { - Id = permissionId, - PermissionName = permission, - CreatedOnUtc = utcNow, - CreatedBy = userId - }; - - role.RolePermissions.Add(new RolePermissionEntity - { - Id = Guid.NewGuid(), - RoleId = roleId, - Role = role, - PermissionId = permissionId, - Permission = permissionEntity, - CreatedOnUtc = utcNow, - CreatedBy = userId - }); - } - - userRole = new UserRoleEntity - { - Id = Guid.NewGuid(), - UserId = userId, - User = user, - RoleId = roleId, - Role = role, - CreatedOnUtc = utcNow, - CreatedBy = userId - }; - } - } - return user; } -} +} \ No newline at end of file diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Fixtures/ITestAuthorizationPolicy.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/ITestAuthorizationPolicy.cs similarity index 85% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Fixtures/ITestAuthorizationPolicy.cs rename to tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/ITestAuthorizationPolicy.cs index bf8ef3f4..3f916f43 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Fixtures/ITestAuthorizationPolicy.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/ITestAuthorizationPolicy.cs @@ -2,7 +2,7 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; #endregion -namespace Lumina.Infrastructure.UnitTests.Core.Authorization.Fixtures; +namespace Lumina.Infrastructure.Fixtures.Core.Authorization; /// /// Example concrete policy for testing generic constraint. diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Common/Factory/Fixtures/IUnregisteredPolicy.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/IUnregisteredPolicy.cs similarity index 81% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Common/Factory/Fixtures/IUnregisteredPolicy.cs rename to tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/IUnregisteredPolicy.cs index 005699b7..fe0bf593 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Common/Factory/Fixtures/IUnregisteredPolicy.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/IUnregisteredPolicy.cs @@ -2,7 +2,7 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; #endregion -namespace Lumina.Infrastructure.UnitTests.Core.Authorization.Policies.Common.Factory.Fixtures; +namespace Lumina.Infrastructure.Fixtures.Core.Authorization; /// /// Test policy interface for unregistered policy scenarios. diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Common/Factory/Fixtures/TestAuthorizationPolicy.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/TestAuthorizationPolicy.cs similarity index 87% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Common/Factory/Fixtures/TestAuthorizationPolicy.cs rename to tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/TestAuthorizationPolicy.cs index 70196b0f..bd123f6e 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Common/Factory/Fixtures/TestAuthorizationPolicy.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/TestAuthorizationPolicy.cs @@ -6,7 +6,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Infrastructure.UnitTests.Core.Authorization.Policies.Common.Factory.Fixtures; +namespace Lumina.Infrastructure.Fixtures.Core.Authorization; /// /// Test policy implementation for registered policy scenarios. diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/Fixtures/CryptographyServiceFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Security/CryptographyServiceFixture.cs similarity index 92% rename from tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/Fixtures/CryptographyServiceFixture.cs rename to tests/Common/Lumina.Infrastructure.Fixtures/Core/Security/CryptographyServiceFixture.cs index 4d4a87d5..e00e0e2a 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/Fixtures/CryptographyServiceFixture.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Security/CryptographyServiceFixture.cs @@ -8,10 +8,10 @@ using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; #endregion -namespace Lumina.Infrastructure.UnitTests.Core.Security.Fixtures; +namespace Lumina.Infrastructure.Fixtures.Core.Security; /// -/// Fixture class for cryptography service tests. +/// Test-support class for cryptography service tests. /// [ExcludeFromCodeCoverage] public class CryptographyServiceFixture diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Lumina.Infrastructure.Fixtures.csproj b/tests/Common/Lumina.Infrastructure.Fixtures/Lumina.Infrastructure.Fixtures.csproj new file mode 100644 index 00000000..2d72755b --- /dev/null +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Lumina.Infrastructure.Fixtures.csproj @@ -0,0 +1,24 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + + false + false + false + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..7903ac6a --- /dev/null +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,20 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Infrastructure.Fixtures")] +[assembly: AssemblyProduct("Lumina.Infrastructure.Fixtures")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("A1B2C3D4-0004-4A5B-9C0D-444444444444")] + +[assembly: InternalsVisibleTo("Lumina.Infrastructure.UnitTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/Fixtures/BaseEndpointFixture.cs b/tests/Common/Lumina.Presentation.Api.Fixtures/Core/Endpoints/Common/BaseEndpointFixture.cs similarity index 95% rename from tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/Fixtures/BaseEndpointFixture.cs rename to tests/Common/Lumina.Presentation.Api.Fixtures/Core/Endpoints/Common/BaseEndpointFixture.cs index a256b0bc..a454948c 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/Fixtures/BaseEndpointFixture.cs +++ b/tests/Common/Lumina.Presentation.Api.Fixtures/Core/Endpoints/Common/BaseEndpointFixture.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using FastEndpoints; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; @@ -9,12 +10,13 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Common.Fixtures; +namespace Lumina.Presentation.Api.Fixtures.Core.Endpoints.Common; /// /// Fixture class for the class. /// [ExcludeFromCodeCoverage] +[DontRegister] public class BaseEndpointFixture : BaseEndpoint { /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Fixtures/FileSystemStructureFixture.cs b/tests/Common/Lumina.Presentation.Api.Fixtures/Core/Endpoints/FileSystemManagement/FileSystemStructureFixture.cs similarity index 86% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Fixtures/FileSystemStructureFixture.cs rename to tests/Common/Lumina.Presentation.Api.Fixtures/Core/Endpoints/FileSystemManagement/FileSystemStructureFixture.cs index dd264175..5ed716d9 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Fixtures/FileSystemStructureFixture.cs +++ b/tests/Common/Lumina.Presentation.Api.Fixtures/Core/Endpoints/FileSystemManagement/FileSystemStructureFixture.cs @@ -5,7 +5,7 @@ using System.Diagnostics.CodeAnalysis; using System.IO; #endregion -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures; +namespace Lumina.Presentation.Api.Fixtures.Core.Endpoints.FileSystemManagement; /// /// Fixture class for creating and managing a file system structure for integration testing purposes. @@ -27,7 +27,7 @@ public class FileSystemStructureFixture /// public FileSystemStructureFixture() { - _rootPath = System.IO.Path.Combine(AppContext.BaseDirectory, "TestFileSystemStructure_" + Guid.NewGuid()); + _rootPath = Path.Combine(AppContext.BaseDirectory, "TestFileSystemStructure_" + Guid.NewGuid()); } @@ -44,13 +44,13 @@ public class FileSystemStructureFixture for (int i = 1; i <= 3; i++) { // create a nested subdirectory - currentPath = System.IO.Path.Combine(currentPath, $"NestedDirectory_{i}"); + currentPath = Path.Combine(currentPath, $"NestedDirectory_{i}"); Directory.CreateDirectory(currentPath); // create two text files in the current directory for (int j = 1; j <= 2; j++) { - string filePath = System.IO.Path.Combine(currentPath, $"TestFile_{j}.txt"); + string filePath = Path.Combine(currentPath, $"TestFile_{j}.txt"); File.WriteAllText(filePath, _faker.Lorem.Paragraph()); // make the first file in each directory hidden if (j == 1) @@ -73,7 +73,7 @@ public class FileSystemStructureFixture if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) return true; // on Windows the fixture relies on the hidden file attribute, which some file systems (for example network drives) do not persist - string probePath = System.IO.Path.Combine(AppContext.BaseDirectory, "lumina_hidden_attribute_probe_" + Guid.NewGuid()); + string probePath = Path.Combine(AppContext.BaseDirectory, "lumina_hidden_attribute_probe_" + Guid.NewGuid()); try { File.WriteAllText(probePath, string.Empty); @@ -112,9 +112,9 @@ public class FileSystemStructureFixture else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) { // On Unix-like systems, rename the file/directory to start with a dot - string directory = System.IO.Path.GetDirectoryName(path)!; - string name = System.IO.Path.GetFileName(path); - string newPath = System.IO.Path.Combine(directory, "." + name); + string directory = Path.GetDirectoryName(path)!; + string name = Path.GetFileName(path); + string newPath = Path.Combine(directory, "." + name); if (Directory.Exists(path)) Directory.Move(path, newPath); else if (File.Exists(path)) diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Fixtures/TestImageFixture.cs b/tests/Common/Lumina.Presentation.Api.Fixtures/Core/Endpoints/FileSystemManagement/TestImageFixture.cs similarity index 86% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Fixtures/TestImageFixture.cs rename to tests/Common/Lumina.Presentation.Api.Fixtures/Core/Endpoints/FileSystemManagement/TestImageFixture.cs index 79a4ed7b..1e9d50ac 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Fixtures/TestImageFixture.cs +++ b/tests/Common/Lumina.Presentation.Api.Fixtures/Core/Endpoints/FileSystemManagement/TestImageFixture.cs @@ -7,7 +7,7 @@ using System.Diagnostics.CodeAnalysis; using System.IO; #endregion -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures; +namespace Lumina.Presentation.Api.Fixtures.Core.Endpoints.FileSystemManagement; /// /// Fixture class for creating and managing a test image for integration testing purposes. @@ -25,7 +25,7 @@ public class TestImageFixture : IDisposable /// public TestImageFixture() { - ImagePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"TestImage_{Guid.NewGuid()}.jpg"); + ImagePath = Path.Combine(Path.GetTempPath(), $"TestImage_{Guid.NewGuid()}.jpg"); CreateTestImage(); } diff --git a/tests/Common/Lumina.Presentation.Api.Fixtures/Lumina.Presentation.Api.Fixtures.csproj b/tests/Common/Lumina.Presentation.Api.Fixtures/Lumina.Presentation.Api.Fixtures.csproj new file mode 100644 index 00000000..fdecf674 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Api.Fixtures/Lumina.Presentation.Api.Fixtures.csproj @@ -0,0 +1,24 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + + false + false + false + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Presentation.Api.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Presentation.Api.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..abc52f98 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Api.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,21 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Presentation.Api.Fixtures")] +[assembly: AssemblyProduct("Lumina.Presentation.Api.Fixtures")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("A1B2C3D4-0005-4A5B-9C0D-555555555555")] + +[assembly: InternalsVisibleTo("Lumina.Presentation.Api.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Presentation.Api.IntegrationTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs index e85e1420..bd119684 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs @@ -25,7 +25,7 @@ namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; [ExcludeFromCodeCoverage] public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable { - private readonly PasswordHashService _hashService; + private readonly PasswordHashService _hashService = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -36,14 +36,6 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable /// public string? TestUsername { get; private set; } - /// - /// Initializes a new instance of the class. - /// - public AuthenticatedLuminaApiFactory() - { - _hashService = new PasswordHashService(); - } - /// /// Creates an HTTP client with authentication headers and a test user /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/BogusExtensions.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/BogusExtensions.cs deleted file mode 100644 index 85e4f2e2..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/BogusExtensions.cs +++ /dev/null @@ -1,38 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; - -/// -/// Contains extension methods for the class. -/// -[ExcludeFromCodeCoverage] -public static class BogusExtensions -{ - /// - /// Adds random data generation support to the class. - /// - /// The faker instance to extend. - /// A random instance. - public static DateOnly DateOnly(this Faker faker) - { - return System.DateOnly.FromDateTime(faker.Date.Past()); - } - - /// - /// Adds random data generation within a specified interval support to the class. - /// - /// The faker instance to extend. - /// The start of the interval. - /// The end of the interval. - /// A random instance. - public static DateOnly DateOnlyBetween(this Faker faker, DateOnly start, DateOnly end) - { - DateTime startDateTime = start.ToDateTime(TimeOnly.MinValue); - DateTime endDateTime = end.ToDateTime(TimeOnly.MinValue); - return System.DateOnly.FromDateTime(faker.Date.Between(startDateTime, endDateTime)); - } -} \ No newline at end of file diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/SkipWhenHiddenAttributeNotSupportedFactAttribute.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/SkipWhenHiddenAttributeNotSupportedFactAttribute.cs index 9c3348b5..ef35ee34 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/SkipWhenHiddenAttributeNotSupportedFactAttribute.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/SkipWhenHiddenAttributeNotSupportedFactAttribute.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Common; +using Lumina.Presentation.Api.Fixtures.Core.Endpoints.FileSystemManagement; using System; using System.IO; using Xunit; diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissionsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissionsEndpointTests.cs index 02f4f5e3..73108052 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissionsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissionsEndpointTests.cs @@ -54,7 +54,7 @@ public class GetPermissionsEndpointTests : IClassFixture } [Fact] - public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldCreateRole() + public async Task AddRole_WhenCalledWithValidRequest_ShouldCreateRole() { // Arrange using IServiceScope scope = _apiFactory.Services.CreateScope(); @@ -91,7 +91,7 @@ public class AddRoleEndpointTests : IClassFixture } [Fact] - public async Task ExecuteAsync_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult() + public async Task AddRole_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult() { // Arrange _client = await _apiFactory.CreateAuthenticatedClientAsync(); @@ -119,7 +119,7 @@ public class AddRoleEndpointTests : IClassFixture } [Fact] - public async Task ExecuteAsync_WhenRoleAlreadyExists_ShouldReturnConflict() + public async Task AddRole_WhenRoleAlreadyExists_ShouldReturnConflict() { // Arrange AddRoleRequest request = new( @@ -146,7 +146,7 @@ public class AddRoleEndpointTests : IClassFixture } [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException() + public async Task AddRole_WhenCancellationRequested_ShouldThrowTaskCanceledException() { // Arrange using CancellationTokenSource cts = new(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRoleEndpointTests.cs index 0ed554cd..ce531fd6 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRoleEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRoleEndpointTests.cs @@ -53,7 +53,7 @@ public class DeleteRoleEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -180,7 +180,7 @@ public class GetDirectoriesEndpointTests : IClassFixture } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTypeResponse() + public async Task GetType_WhenCalled_ShouldReturnOkResultWithFileSystemTypeResponse() { // Act HttpResponseMessage response = await _client.GetAsync("/api/v1/file-system/get-type"); @@ -62,7 +62,7 @@ public class GetTypeEndpointTests : IClassFixture } [Fact] - public async Task ExecuteAsync_WhenCalledMultipleTimes_ShouldReturnConsistentResults() + public async Task GetType_WhenCalledMultipleTimes_ShouldReturnConsistentResults() { // Act HttpResponseMessage response1 = await _client.GetAsync("/api/v1/file-system/get-type"); @@ -84,7 +84,7 @@ public class GetTypeEndpointTests : IClassFixture } [Fact] - public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + public async Task GetType_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() { // Arrange using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs index 3f9923c9..721f46cf 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Responses.FileSystemManagement.Files; +using Lumina.Presentation.Api.Fixtures.Core.Endpoints.FileSystemManagement; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; @@ -53,7 +53,7 @@ public class GetFilesEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -220,7 +220,7 @@ public class GetFilesEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -220,7 +220,7 @@ public class GetTreeFilesEndpointTests : IClassFixture -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class FileSystemTreeNodeResponseFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a single with a nested structure. - /// - /// The current depth in the tree structure. Default is 0 (root level). - /// The maximum depth of the tree structure. Default is 2. - /// The maximum number of children for each node. Default is 3. - /// A with a nested structure. - public FileSystemTreeNodeResponse Create(int currentDepth = 0, int maxDepth = 2, int maxChildren = 3) - { - FileSystemTreeNodeResponse response = new() - { - Path = _faker.System.FilePath(), - Name = _faker.System.FileName(), - ItemType = FileSystemItemType.Directory, - IsExpanded = _faker.Random.Bool(), - ChildrenLoaded = true, - Children = [] - }; - if (currentDepth < maxDepth) - { - int childCount = _faker.Random.Int(1, maxChildren); - for (int i = 0; i < childCount; i++) - response.Children.Add(Create(currentDepth + 1, maxDepth, maxChildren)); - } - return response; - } - - /// - /// Creates a list of objects, each with a nested structure. - /// - /// The number of root-level nodes to create. Default is 2. - /// The maximum depth of the tree structure for each root node. Default is 2. - /// The maximum number of children for each node. Default is 3. - /// A list of objects with nested structures. - public List CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3) - { - return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList(); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs index 206e5101..b97fb2d0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs @@ -49,7 +49,7 @@ public class CheckPathExistsEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -123,7 +123,7 @@ public class GetThumbnailEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -152,7 +152,7 @@ public class GetThumbnailEndpointTests : IClassFixture /// Contains integration tests for the class. @@ -39,7 +39,7 @@ public class AddBookEndpointTests : IClassFixture new BookJsonConverter() } }; - private readonly AddBookRequestFixture _requestBookFixture; + private readonly AddBookRequestFixture _requestBookFixture = new(); /// /// Initializes a new instance of the class. @@ -49,7 +49,6 @@ public class AddBookEndpointTests : IClassFixture { _client = apiFactory.CreateClient(); _apiFactory = apiFactory; - _requestBookFixture = new AddBookRequestFixture(); } /// @@ -64,7 +63,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithValidData_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); // Act HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); @@ -128,7 +127,7 @@ public class AddBookEndpointTests : IClassFixture // ISBNs checks Assert.Equal(bookRequest.ISBNs!.Count, bookResponse.ISBNs.Count); var requestIsbnData = bookRequest.ISBNs.Select(isbn => new { isbn.Value, isbn.Format }).OrderBy(x => x.Value).ToList(); - var responseIsbnData = bookResponse.ISBNs.Select(isbn => new { Value = isbn.Value, Format = isbn.Format }).OrderBy(x => x.Value).ToList(); + var responseIsbnData = bookResponse.ISBNs.Select(isbn => new { isbn.Value, isbn.Format }).OrderBy(x => x.Value).ToList(); Assert.Equal(requestIsbnData.Count, responseIsbnData.Count); for (int i = 0; i < requestIsbnData.Count; i++) { @@ -138,7 +137,7 @@ public class AddBookEndpointTests : IClassFixture // ratings checks Assert.Equal(bookRequest.Ratings!.Count, bookResponse.Ratings.Count); - var requestRatingData = bookRequest.Ratings.Select(r => new { Source = r.Source, r.Value, r.MaxValue, r.VoteCount }).OrderBy(x => x.Source).ToList(); + var requestRatingData = bookRequest.Ratings.Select(r => new { r.Source, r.Value, r.MaxValue, r.VoteCount }).OrderBy(x => x.Source).ToList(); var responseRatingData = bookResponse.Ratings.Select(r => new { Source = r.Source.Value, r.Value, r.MaxValue, VoteCount = r.VoteCount.Value }).OrderBy(x => x.Source).ToList(); Assert.Equal(requestRatingData.Count, responseRatingData.Count); for (int i = 0; i < requestRatingData.Count; i++) @@ -169,7 +168,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyTitle_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Title = null! } }; // Act @@ -183,7 +182,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthTitle_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Title = new Faker().Random.String2(300) } }; // Act @@ -197,7 +196,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalTitle_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalTitle = null! } }; // Act & Assert @@ -208,7 +207,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalTitle_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalTitle = new Faker().Random.String2(300) } }; // Act @@ -222,7 +221,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyDescription_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Description = null! } }; // Act & Assert @@ -233,7 +232,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthDescription_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Description = new Faker().Random.String2(2001) } }; // Act @@ -247,7 +246,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullReleaseInfo_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = null! } }; // Act @@ -261,7 +260,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalReleaseYear_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { OriginalReleaseYear = null! } } }; // Act & Assert @@ -272,7 +271,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidValueOriginalReleaseYear_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { OriginalReleaseYear = 10000 } } }; // Act @@ -286,7 +285,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyReReleaseYear_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { ReReleaseYear = null!, ReReleaseDate = null } } }; // Act & Assert @@ -297,7 +296,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidValueReReleaseYear_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -319,7 +318,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyReleaseCountry_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { ReleaseCountry = null! } } }; // Act & Assert @@ -330,7 +329,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidValueReleaseCountry_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -350,7 +349,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyReleaseVersion_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { ReleaseInfo = bookRequest.Metadata.ReleaseInfo! with { ReleaseVersion = null! } } }; // Act & Assert @@ -361,7 +360,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidValueReleasVersion_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -381,7 +380,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -400,7 +399,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenReReleaseYearIsBeforeReleaseYear_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -422,7 +421,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenReReleaseDateIsAfterOriginalReleaseDate_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -441,7 +440,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenReReleaseDateIsBeforeReleaseDate_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -463,7 +462,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullGenres_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Genres = null! } }; // Act @@ -477,12 +476,12 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyGenreName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { - Genres = bookRequest.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = null } : genre).ToList() + Genres = [.. bookRequest.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = null } : genre)] } }; @@ -497,12 +496,12 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthGenreName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { - Genres = bookRequest.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = new Faker().Random.String2(100) } : genre).ToList() + Genres = [.. bookRequest.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = new Faker().Random.String2(100) } : genre)] } }; // Act @@ -516,7 +515,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullTags_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Tags = null! } }; // Act @@ -530,12 +529,12 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyTagName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { - Tags = bookRequest.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = null } : tag).ToList() + Tags = [.. bookRequest.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = null } : tag)] } }; @@ -550,12 +549,12 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthTagName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { - Tags = bookRequest.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = new Faker().Random.String2(100) } : tag).ToList() + Tags = [.. bookRequest.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = new Faker().Random.String2(100) } : tag)] } }; // Act @@ -569,7 +568,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguage_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Language = null! } }; // Act & Assert @@ -580,7 +579,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Language = bookRequest.Metadata.Language! with { LanguageCode = null } } }; // Act @@ -594,7 +593,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -617,7 +616,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Language = bookRequest.Metadata.Language! with { LanguageName = null } } }; // Act @@ -631,7 +630,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -654,7 +653,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLanguageNativeName_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Language = bookRequest.Metadata.Language! with { NativeName = null } } }; // Act & Assert @@ -665,7 +664,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthNativeLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -688,7 +687,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguage_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalLanguage = null! } }; // Act & Assert @@ -699,7 +698,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalLanguage = bookRequest.Metadata.Language! with { LanguageCode = null } } }; // Act @@ -713,7 +712,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalLanguageCode_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -736,7 +735,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalLanguage = bookRequest.Metadata.Language! with { LanguageName = null } } }; // Act @@ -750,7 +749,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -773,7 +772,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthOriginalNativeLanguageName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with @@ -796,7 +795,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOriginalLanguageNativeName_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { OriginalLanguage = bookRequest.Metadata.Language! with { NativeName = null } } }; // Act & Assert @@ -807,7 +806,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyPublisher_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Publisher = null } }; // Act & Assert @@ -818,7 +817,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthPublisher_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { Publisher = new Faker().Random.String2(150) } }; // Act @@ -832,7 +831,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyPageCount_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { PageCount = null } }; // Act & Assert @@ -843,7 +842,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNegativePageCount_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Metadata = bookRequest.Metadata! with { PageCount = -1 } }; // Act @@ -857,7 +856,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyFormat_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Format = null }; // Act & Assert @@ -868,7 +867,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidFormat_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Format = (BookFormat)99 }; // Act @@ -882,7 +881,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyEdition_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Edition = null }; // Act & Assert @@ -893,7 +892,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthEdition_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Edition = new Faker().Random.String2(100) }; // Act @@ -907,7 +906,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyVolumeNumber_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { VolumeNumber = null }; // Act & Assert @@ -918,7 +917,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeVolumeNumber_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { VolumeNumber = -1 }; // Act @@ -932,7 +931,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptySeries_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Series = null }; // Act & Assert @@ -943,7 +942,7 @@ public class AddBookEndpointTests : IClassFixture //public async Task AddBook_WhenCalledWithEmptySeriesTitle_ShouldReturnUnprocessableEntity() //{ // // Arrange - // var bookRequest = _requestBookFixture.CreateRequestBook(); + // var bookRequest = _requestBookFixture.Create(); // bookRequest = bookRequest with // { // Series = bookRequest.Series! with { Title = null } @@ -960,7 +959,7 @@ public class AddBookEndpointTests : IClassFixture //public async Task AddBook_WhenCalledWithInvalidLengthSeriesTitle_ShouldReturnUnprocessableEntity() //{ // // Arrange - // var bookRequest = _requestBookFixture.CreateRequestBook(); + // var bookRequest = _requestBookFixture.Create(); // bookRequest = bookRequest with { Series = bookRequest.Series! with { Title = new Faker().Random.String2(300) } }; // // Act @@ -974,7 +973,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyAsin_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { ASIN = null }; // Act & Assert @@ -985,7 +984,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthAsin_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { ASIN = new Faker().Random.String2(15) }; // Act @@ -999,7 +998,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyGoodreadsId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { GoodreadsId = null }; // Act & Assert @@ -1010,7 +1009,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidGoodreadsId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { GoodreadsId = new Faker().Random.String2(2) }; // Act @@ -1024,7 +1023,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLccn_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { LCCN = null }; // Act & Assert @@ -1035,7 +1034,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLccn_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { LCCN = new Faker().Random.String2(200) }; // Act @@ -1049,7 +1048,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOclcNumber_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { OCLCNumber = null }; // Act & Assert @@ -1060,7 +1059,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidOclcNumber_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { OCLCNumber = new Faker().Random.String2(200) }; // Act @@ -1074,7 +1073,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyOpenLibraryId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { OpenLibraryId = null }; // Act & Assert @@ -1085,7 +1084,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidOpenLibraryId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { OpenLibraryId = new Faker().Random.String2(200) }; // Act @@ -1099,7 +1098,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyLibraryThingId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { LibraryThingId = null }; // Act & Assert @@ -1110,7 +1109,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthLibraryThingId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { LibraryThingId = new Faker().Random.String2(200) }; // Act @@ -1124,7 +1123,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyGoogleBooksId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { GoogleBooksId = null }; // Act & Assert @@ -1135,7 +1134,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthGoogleBooksId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { GoogleBooksId = new Faker().Random.String2(20) }; // Act @@ -1149,7 +1148,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidGoogleBooksId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { GoogleBooksId = new Faker().Random.String2(11) + " " }; // Act @@ -1163,7 +1162,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyBarnesAndNobleId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { BarnesAndNobleId = null }; // Act & Assert @@ -1174,7 +1173,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthBarnesAndNobleId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { BarnesAndNobleId = new Faker().Random.String2(20) }; // Act @@ -1188,7 +1187,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidBarnesAndNobleId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { BarnesAndNobleId = new Faker().Random.String2(10) }; // Act @@ -1202,7 +1201,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyAppleBooksId_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { AppleBooksId = null }; // Act & Assert @@ -1213,7 +1212,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidAppleBooksId_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { AppleBooksId = new Faker().Random.String2(10) }; // Act @@ -1227,7 +1226,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullIsbns_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { ISBNs = null! }; // Act @@ -1241,10 +1240,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyIsbnValue_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - ISBNs = bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = null } : isbn).ToList() + ISBNs = [.. bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = null } : isbn)] }; // Act @@ -1258,10 +1257,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidIsbn10Value_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - ISBNs = bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn10 } : isbn).ToList() + ISBNs = [.. bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn10 } : isbn)] }; // Act @@ -1275,10 +1274,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidIsbn13Value_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - ISBNs = bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn13 } : isbn).ToList() + ISBNs = [.. bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn13 } : isbn)] }; // Act @@ -1292,10 +1291,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidIsbnFormat_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - ISBNs = bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Format = (IsbnFormat)99 } : isbn).ToList() + ISBNs = [.. bookRequest.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Format = (IsbnFormat)99 } : isbn)] }; // Act HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); @@ -1308,7 +1307,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullContributors_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Contributors = null! }; // Act @@ -1322,10 +1321,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullContributorName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = null! } : contributor).ToList() + Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = null! } : contributor)] }; // Act @@ -1339,10 +1338,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyContributorDisplayName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = string.Empty } } : contributor).ToList() + Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = string.Empty } } : contributor)] }; // Act @@ -1356,10 +1355,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullContributorDisplayName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = null! } } : contributor).ToList() + Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = null! } } : contributor)] }; // Act @@ -1373,10 +1372,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthContributorDisplayName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = new Faker().Random.String2(150) } } : contributor).ToList() + Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = new Faker().Random.String2(150) } } : contributor)] }; // Act @@ -1390,10 +1389,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthContributorLegalName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { LegalName = new Faker().Random.String2(150) } } : contributor).ToList() + Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { LegalName = new Faker().Random.String2(150) } } : contributor)] }; // Act @@ -1407,10 +1406,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyContributorRole_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = null } : contributor).ToList() + Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = null } : contributor)] }; // Act @@ -1424,11 +1423,11 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyContributorRoleName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with - { Role = contributor.Role! with { Name = null } } : contributor).ToList() + Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with + { Role = contributor.Role! with { Name = null } } : contributor)] }; // Act @@ -1442,11 +1441,11 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthContributorRoleName_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with - { Role = contributor.Role! with { Name = new Faker().Random.String2(100) } } : contributor).ToList() + Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with + { Role = contributor.Role! with { Name = new Faker().Random.String2(100) } } : contributor)] }; // Act @@ -1460,11 +1459,11 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyContributorRoleCategory_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with - { Role = contributor.Role! with { Category = null } } : contributor).ToList() + Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with + { Role = contributor.Role! with { Category = null } } : contributor)] }; // Act @@ -1478,11 +1477,11 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithInvalidLengthContributorRoleCategory_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - Contributors = bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with - { Role = contributor.Role! with { Category = new Faker().Random.String2(100) } } : contributor).ToList() + Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with + { Role = contributor.Role! with { Category = new Faker().Random.String2(100) } } : contributor)] }; // Act @@ -1496,7 +1495,7 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNullRatings_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { Ratings = null! }; // Act @@ -1510,10 +1509,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeRatingValue_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - Ratings = bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = -3 } : rating).ToList() + Ratings = [.. bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = -3 } : rating)] }; // Act HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); @@ -1526,10 +1525,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithRatingValueGreaterThanMaxValue_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - Ratings = bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = 3, MaxValue = 2 } : rating).ToList() + Ratings = [.. bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = 3, MaxValue = 2 } : rating)] }; // Act HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); @@ -1542,10 +1541,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeMaxRatingValue_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - Ratings = bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { MaxValue = -3 } : rating).ToList() + Ratings = [.. bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { MaxValue = -3 } : rating)] }; // Act HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); @@ -1558,10 +1557,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithEmptyRatingVoteCount_ShouldAddBook() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - Ratings = bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = null } : rating).ToList() + Ratings = [.. bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = null } : rating)] }; // Act & Assert await AssertCreated(bookRequest); @@ -1571,10 +1570,10 @@ public class AddBookEndpointTests : IClassFixture public async Task AddBook_WhenCalledWithNegativeVoteCount_ShouldReturnUnprocessableEntity() { // Arrange - AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook(); + AddBookRequest bookRequest = _requestBookFixture.Create(); bookRequest = bookRequest with { - Ratings = bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = -3 } : rating).ToList() + Ratings = [.. bookRequest.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = -3 } : rating)] }; // Act HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); @@ -1597,7 +1596,7 @@ public class AddBookEndpointTests : IClassFixture Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); Assert.NotNull(problemDetails["traceId"].GetString()); - Assert.NotEmpty(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooksEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs similarity index 92% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooksEndpointTests.cs rename to tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs index 46a2dacd..260e1779 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooksEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs @@ -13,7 +13,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books; +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks; /// /// Contains integration tests for the class. @@ -65,7 +65,7 @@ public class GetBooksEndpointTests : IClassFixture(); + dbContext.Users.RemoveRange(dbContext.Users); + await dbContext.SaveChangesAsync(); + } + // Act HttpResponseMessage response = await _client.GetAsync("/api/v1/initialization"); @@ -70,7 +78,7 @@ public class CheckInitializationEndpointTests : IClassFixture, { private HttpClient _client; private readonly AuthenticatedLuminaApiFactory _apiFactory; - private readonly PasswordHashService _hashService; + private readonly PasswordHashService _hashService = new(); private readonly ICryptographyService _cryptographyService; - private readonly TotpTokenGenerator _totpTokenGenerator; + private readonly TotpTokenGenerator _totpTokenGenerator = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true, @@ -50,8 +50,6 @@ public class LoginEndpointTests : IClassFixture, { _client = apiFactory.CreateClient(); _apiFactory = apiFactory; - _hashService = new PasswordHashService(); - _totpTokenGenerator = new TotpTokenGenerator(); _testUsername = $"testuser_{Guid.NewGuid()}"; using IServiceScope scope = apiFactory.Services.CreateScope(); @@ -68,7 +66,7 @@ public class LoginEndpointTests : IClassFixture, } [Fact] - public async Task ExecuteAsync_WhenCalledWithValidCredentials_ShouldLoginSuccessfully() + public async Task Login_WhenCalledWithValidCredentials_ShouldLoginSuccessfully() { // Arrange UserEntity user = await CreateTestUser(); @@ -95,7 +93,7 @@ public class LoginEndpointTests : IClassFixture, } [Fact] - public async Task ExecuteAsync_WhenCalledWithValidCredentialsAndTotp_ShouldLoginSuccessfully() + public async Task Login_WhenCalledWithValidCredentialsAndTotp_ShouldLoginSuccessfully() { // Arrange UserEntity user = await CreateTestUserWithTotp(); @@ -127,7 +125,7 @@ public class LoginEndpointTests : IClassFixture, } [Fact] - public async Task ExecuteAsync_WhenCalledWithTempPassword_ShouldLoginSuccessfully() + public async Task Login_WhenCalledWithTempPassword_ShouldLoginSuccessfully() { // Arrange UserEntity user = await CreateTestUserWithTempPassword(); @@ -153,7 +151,7 @@ public class LoginEndpointTests : IClassFixture, } [Fact] - public async Task ExecuteAsync_WhenCalledWithExpiredTempPassword_ShouldReturnUnauthorized() + public async Task Login_WhenCalledWithExpiredTempPassword_ShouldReturnUnauthorized() { // Arrange UserEntity user = await CreateTestUserWithExpiredTempPassword(); @@ -181,7 +179,7 @@ public class LoginEndpointTests : IClassFixture, } [Fact] - public async Task ExecuteAsync_WhenCalledWithInvalidCredentials_ShouldReturnUnauthorized() + public async Task Login_WhenCalledWithInvalidCredentials_ShouldReturnUnauthorized() { // Arrange UserEntity user = await CreateTestUser(); @@ -209,7 +207,7 @@ public class LoginEndpointTests : IClassFixture, } [Fact] - public async Task ExecuteAsync_WhenCalledWithInvalidTotpCode_ShouldReturnUnauthorized() + public async Task Login_WhenCalledWithInvalidTotpCode_ShouldReturnUnauthorized() { // Arrange UserEntity user = await CreateTestUserWithTotp(); @@ -249,6 +247,7 @@ public class LoginEndpointTests : IClassFixture, UserEntity user = new() { + Id = Guid.NewGuid(), Username = _testUsername, Password = _hashService.HashString("TestPass123!"), Libraries = [], @@ -271,6 +270,7 @@ public class LoginEndpointTests : IClassFixture, byte[] totpSecret = _totpTokenGenerator.GenerateSecret(); UserEntity user = new() { + Id = Guid.NewGuid(), Username = _testUsername, Password = _hashService.HashString("TestPass123!"), TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)), @@ -293,6 +293,7 @@ public class LoginEndpointTests : IClassFixture, UserEntity user = new() { + Id = Guid.NewGuid(), Username = _testUsername, Password = _hashService.HashString("TestPass123!"), TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")), @@ -316,6 +317,7 @@ public class LoginEndpointTests : IClassFixture, UserEntity user = new() { + Id = Guid.NewGuid(), Username = _testUsername, Password = _hashService.HashString("TestPass123!"), TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")), diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs index 3867d841..94803f37 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs @@ -34,9 +34,9 @@ public class RecoverPasswordEndpointTests : IClassFixture(); UserEntity userWithoutTotp = new() { + Id = Guid.NewGuid(), Username = "userwithoutotp2", Password = _hashService.HashString("OldPass123!"), TotpSecret = null, // No TOTP configured @@ -290,7 +289,7 @@ public class RecoverPasswordEndpointTests : IClassFixture -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class AddBookRequestFixture -{ - private readonly Fixture _fixture; - private readonly Random _random = new(); - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public AddBookRequestFixture() - { - _fixture = new Fixture(); - _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); - _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); - _faker = new Faker(); - } - - /// - /// Creates a random valid request to add a book. - /// - /// The created request to add a book. - public AddBookRequest CreateRequestBook() - { - int releaseYear = _random.Next(2000, 2010); - int reReleaseYear = _random.Next(2010, 2020); - - ReleaseInfoDto releaseInfo = new Faker() - .CustomInstantiator(f => new ReleaseInfoDto( - default, - default, - default, - default, - default, - default - )) - .RuleFor(x => x.OriginalReleaseDate, _faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31))) - .RuleFor(x => x.OriginalReleaseYear, releaseYear) - .RuleFor(x => x.ReReleaseDate, _faker.DateOnlyBetween(new DateOnly(reReleaseYear, 1, 1), new DateOnly(reReleaseYear, 12, 31))) - .RuleFor(x => x.ReReleaseYear, reReleaseYear) - .RuleFor(x => x.ReleaseCountry, f => f.Random.String2(2)) - .RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50))) - .Generate(); - - Faker genre = new Faker() - .CustomInstantiator(f => new GenreDto( - default! - )) - .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); - - Faker tag = new Faker() - .CustomInstantiator(f => new TagDto( - default! - )) - .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); - - Faker mediaContributorRole = new Faker() - .CustomInstantiator(f => new MediaContributorRoleDto( - default!, - default! - )) - .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50))); - - Faker mediaContributorName = new Faker() - .CustomInstantiator(f => new MediaContributorNameDto( - default!, - default! - )) - .RuleFor(e => e.DisplayName, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(e => e.LegalName, f => f.Random.String2(f.Random.Number(1, 50))); - - Faker mediaContributor = new Faker() - .CustomInstantiator(f => new MediaContributorDto( - default!, - default! - )) - .RuleFor(e => e.Name, mediaContributorName) - .RuleFor(e => e.Role, mediaContributorRole); - - Faker rating = new Faker() - .CustomInstantiator(f => new BookRatingDto( - default, - default, - default, - default - )) - .RuleFor(e => e.Value, _random.Next(1, 5)) - .RuleFor(e => e.MaxValue, 5) - .RuleFor(e => e.Source, _fixture.Create()) - .RuleFor(e => e.VoteCount, _random.Next(1, 1000)); - - Faker language = new Faker() - .CustomInstantiator(f => new LanguageInfoDto( - default!, - default!, - default - )) - .RuleFor(e => e.LanguageName, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(e => e.LanguageCode, f => f.Random.String2(2)) - .RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50))); - - Faker originalLanguage = new Faker() - .CustomInstantiator(f => new LanguageInfoDto( - default!, - default!, - default - )) - .RuleFor(e => e.LanguageName, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(e => e.LanguageCode, f => f.Random.String2(2)) - .RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50))); - - Faker metadata = new Faker() - .CustomInstantiator(f => new WrittenContentMetadataDto( - default!, - default, - default, - default!, - default!, - default!, - default, - default, - default, - default - )) - .RuleFor(x => x.Title, f => f.Random.String2(f.Random.Number(1, 255))) - .RuleFor(x => x.OriginalTitle, f => f.Random.String2(f.Random.Number(1, 255))) - .RuleFor(x => x.Description, f => f.Random.String2(f.Random.Number(1, 2000))) - .RuleFor(x => x.ReleaseInfo, releaseInfo) - .RuleFor(p => p.Genres, f => genre.Generate(f.Random.Number(1, 5))) - .RuleFor(x => x.Tags, f => tag.Generate(f.Random.Number(1, 5))) - .RuleFor(x => x.Language, language) - .RuleFor(x => x.OriginalLanguage, originalLanguage) - .RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100))) - .RuleFor(x => x.PageCount, _random.Next(100, 300)); - - Faker isbn = new Faker() - .CustomInstantiator(f => new IsbnDto( - default!, - default - )) - .RuleFor(i => i.Value, f => - { - bool isIsbn13 = f.Random.Bool(); - if (isIsbn13) - { - string prefix = f.Random.Bool() ? "978" : "979"; - string group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0'); - string publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0'); - string title = f.Random.Number(0, 99).ToString().PadLeft(2, '0'); - string isbn = $"{prefix}{group[..1]}{publisher}{title}"; - int sum = 0; - for (int i = 0; i < 12; i++) - sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString()); - int checkDigit = (10 - (sum % 10)) % 10; - return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}"; - } - else - { - int[] digits = new int[9]; - for (int i = 0; i < 9; i++) - digits[i] = f.Random.Number(0, 9); - int sum = 0; - for (int i = 0; i < 9; i++) - sum += (10 - i) * digits[i]; - int checkDigit = (11 - (sum % 11)) % 11; - string checkChar = checkDigit == 10 ? "X" : checkDigit.ToString(); - return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}"; - } - }) - .RuleFor(i => i.Format, (f, i) => i.Value!.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10); - - return new Faker() - .CustomInstantiator(f => new AddBookRequest( - default, - default!, - default!, - default, - default, - default, - default, - default, - default, - default, - default, - default, - default, - default, - default!, - default!, - default!, - default!, - default! - )) - .RuleFor(x => x.LibraryId, _fixture.Create()) - .RuleFor(x => x.Path, f => f.System.FilePath()) - .RuleFor(x => x.Metadata, metadata) - .RuleFor(x => x.Format, _fixture.Create()) - .RuleFor(x => x.Edition, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(x => x.VolumeNumber, _random.Next(1, 3)) - .RuleFor(x => x.ASIN, f => f.Random.String2(10)) - .RuleFor(x => x.GoodreadsId, _random.Next(100000, 500000).ToString()) - .RuleFor(x => x.LCCN, f => - { - string letters = new(Enumerable.Range(0, f.Random.Number(0, 3)) - .Select(_ => f.Random.Char('a', 'z')) - .ToArray()); - string digits = f.Random.String2(f.Random.Number(8, 10), "0123456789"); - return letters + digits; - }) - .RuleFor(x => x.OCLCNumber, f => - { - string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"]; - string prefix = f.Random.ArrayElement(prefixes); - string number; - switch (prefix) - { - case "ocm": - number = f.Random.String2(8, "0123456789"); - break; - case "ocn": - number = f.Random.String2(f.Random.Number(9, 11), "0123456789"); - break; - case "on": - number = f.Random.String2(10, "0123456789"); - break; - case "(OCoLC)": - number = f.Random.String2(f.Random.Number(8, 10), "0123456789"); - break; - default: - number = f.Random.String2(f.Random.Number(8, 10), "0123456789"); - return number; - } - return prefix + number; - }) - .RuleFor(x => x.OpenLibraryId, f => - { - int firstDigit = f.Random.Number(1, 9); - string remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789"); - char suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' }); - return $"OL{firstDigit}{remainingDigits}{suffix}"; - }) - .RuleFor(x => x.LibraryThingId, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(x => x.GoogleBooksId, f => - { - const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - return new string(Enumerable.Repeat(VALID_CHARS, 12) - .Select(s => s[f.Random.Number(VALID_CHARS.Length - 1)]) - .ToArray()); - }) - .RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789")) - .RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}") - .RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}") - .RuleFor(p => p.ISBNs, f => isbn.Generate(f.Random.Number(1, 5))) - .RuleFor(p => p.Ratings, f => rating.Generate(f.Random.Number(1, 5))) - .RuleFor(x => x.Contributors, f => mediaContributor.Generate(f.Random.Number(1, 5))); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/Fixtures/DomainBookFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/Fixtures/DomainBookFixture.cs deleted file mode 100644 index 7d000c2a..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/Fixtures/DomainBookFixture.cs +++ /dev/null @@ -1,110 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Common.ValueObjects.Metadata; -using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.Fixtures; - -/// -/// Fixture class for the domain entity. -/// -[ExcludeFromCodeCoverage] -public class DomainBookFixture -{ - private readonly Fixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public DomainBookFixture() - { - _fixture = new Fixture(); - _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); - _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); - ConfigureCustomDomainTypes(); - } - - public Book CreateDomainBook() - { - return Book.Create( - LibraryId.Create(_fixture.Create()), - _fixture.Create(), - _fixture.Create(), - _fixture.Create(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>() - ).Value; - } - - private void ConfigureCustomDomainTypes() - { - _fixture.Register(() => Optional.Some(_fixture.Create())); - _fixture.Register(() => Optional.Some(_fixture.Create())); - - _fixture.Register(() => ReleaseInfo.Create( - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>() - ).Value); - - _fixture.Register(() => Genre.Create( - _fixture.Create() - ).Value); - - _fixture.Register(() => Tag.Create( - _fixture.Create() - ).Value); - - _fixture.Register(() => WrittenContentMetadata.Create( - _fixture.Create(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>(), - _fixture.Create>() - ).Value); - - _fixture.Register(() => Isbn.Create( - _fixture.Create(), - _fixture.Create() - ).Value); - - _fixture.Register(() => BookRating.Create( - _fixture.Create(), - _fixture.Create(), - _fixture.Create>(), - _fixture.Create>() - ).Value); - } -} \ No newline at end of file diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Lumina.Presentation.Api.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Lumina.Presentation.Api.IntegrationTests.csproj index eb93fd65..902c9954 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Lumina.Presentation.Api.IntegrationTests.csproj +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Lumina.Presentation.Api.IntegrationTests.csproj @@ -41,5 +41,7 @@ + + diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs index 57c424fa..bca24809 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs @@ -25,7 +25,7 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis { private readonly LuminaApiFactory _apiFactory; private readonly HttpClient _client; - private readonly PasswordHashService _hashService; + private readonly PasswordHashService _hashService = new(); private readonly string _testUsername; private readonly JsonSerializerOptions _jsonOptions = new() { @@ -42,7 +42,6 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis _client = apiFactory.CreateClient(); _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.12"); - _hashService = new PasswordHashService(); _testUsername = $"testuser_{Guid.NewGuid()}"; } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs index d7be4d45..810079cb 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs @@ -26,9 +26,9 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A [ExcludeFromCodeCoverage] public class LoginEndpointTests : IClassFixture, IDisposable { - private readonly PasswordHashService _hashService; + private readonly PasswordHashService _hashService = new(); private readonly ICryptographyService _cryptographyService; - private readonly TotpTokenGenerator _totpTokenGenerator; + private readonly TotpTokenGenerator _totpTokenGenerator = new(); private readonly LuminaApiFactory _apiFactory; private readonly HttpClient _client; private readonly JsonSerializerOptions _jsonOptions = new() @@ -49,8 +49,6 @@ public class LoginEndpointTests : IClassFixture, IDisposable // set a fake IP for this test instance _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.1"); - _hashService = new PasswordHashService(); - _totpTokenGenerator = new TotpTokenGenerator(); _testUsername = $"testuser_{Guid.NewGuid()}"; using IServiceScope scope = apiFactory.Services.CreateScope(); @@ -145,7 +143,7 @@ public class LoginEndpointTests : IClassFixture, IDisposable } [Fact] - public async Task ExecuteAsync_WhenRateLimitExceeded_ShouldReturnTooManyRequests() + public async Task Login_WhenRateLimitExceeded_ShouldReturnTooManyRequests() { // Arrange // set a fake IP for this test instance diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs index 6a3e6da5..2e0b2dfe 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs @@ -44,7 +44,7 @@ public class RecoverPasswordEndpointTests : IClassFixture, IDi } [Fact] - public async Task ExecuteAsync_WhenRateLimitExceeded_ShouldReturnTooManyRequests() + public async Task RecoverPassword_WhenRateLimitExceeded_ShouldReturnTooManyRequests() { // Arrange RecoverPasswordRequest request = new( diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs index 40d63a07..7222650d 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs @@ -22,7 +22,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A [ExcludeFromCodeCoverage] public class RegisterEndpointTests : IClassFixture, IDisposable { - private readonly PasswordHashService _hashService; + private readonly PasswordHashService _hashService = new(); private readonly LuminaApiFactory _apiFactory; private readonly HttpClient _client; private readonly JsonSerializerOptions _jsonOptions = new() @@ -38,7 +38,6 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl _client = apiFactory.CreateClient(); _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.5"); - _hashService = new PasswordHashService(); _testUsername = $"testuser_{Guid.NewGuid()}"; } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/ChangePasswordRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/ChangePasswordRequestMappingTests.cs index 7b027b6e..5d0544b9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/ChangePasswordRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/ChangePasswordRequestMappingTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Authentication; using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; -using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using System.Diagnostics.CodeAnalysis; -using Lumina.Application.Common.Mapping.Authentication; #endregion namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; @@ -14,21 +14,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; [ExcludeFromCodeCoverage] public class ChangePasswordRequestMappingTests { - private readonly ChangePasswordRequestFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public ChangePasswordRequestMappingTests() - { - _fixture = new(); - } + private readonly ChangePasswordRequestFixture _fixture = new(); [Fact] public void ToCommand_WhenMappingRequest_ShouldMapCorrectly() { // Arrange - ChangePasswordRequest request = _fixture.CreateChangePasswordRequest(); + ChangePasswordRequest request = _fixture.Create(); // Act ChangePasswordCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/LoginRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/LoginRequestMappingTests.cs index 496fd124..5e2a7705 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/LoginRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/LoginRequestMappingTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Authentication; using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; -using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using System.Diagnostics.CodeAnalysis; #endregion @@ -14,21 +14,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; [ExcludeFromCodeCoverage] public class LoginRequestMappingTests { - private readonly LoginRequestFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public LoginRequestMappingTests() - { - _fixture = new(); - } + private readonly LoginRequestFixture _fixture = new(); [Fact] public void ToQuery_WhenMappingRequest_ShouldMapCorrectly() { // Arrange - LoginRequest request = _fixture.CreateLoginRequest(); + LoginRequest request = _fixture.Create(); // Act LoginUserQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RecoverPasswordRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RecoverPasswordRequestMappingTests.cs index 2a1555cf..2191d1eb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RecoverPasswordRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RecoverPasswordRequestMappingTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Authentication; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; -using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using System.Diagnostics.CodeAnalysis; #endregion @@ -14,21 +14,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; [ExcludeFromCodeCoverage] public class RecoverPasswordRequestMappingTests { - private readonly RecoverPasswordRequestFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public RecoverPasswordRequestMappingTests() - { - _fixture = new(); - } + private readonly RecoverPasswordRequestFixture _fixture = new(); [Fact] public void ToCommand_WhenMappingRequest_ShouldMapCorrectly() { // Arrange - RecoverPasswordRequest request = _fixture.CreateRecoverPasswordRequest(); + RecoverPasswordRequest request = _fixture.Create(); // Act RecoverPasswordCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RegistrationRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RegistrationRequestMappingTests.cs index b3ad333b..414607f3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RegistrationRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RegistrationRequestMappingTests.cs @@ -2,7 +2,7 @@ using Lumina.Application.Common.Mapping.Authentication; using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; -using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using System.Diagnostics.CodeAnalysis; #endregion @@ -15,21 +15,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; [ExcludeFromCodeCoverage] public class RegistrationRequestMappingTests { - private readonly RegistrationRequestFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public RegistrationRequestMappingTests() - { - _fixture = new(); - } + private readonly RegistrationRequestFixture _fixture = new(); [Fact] public void ToSetupCommand_WhenMappingRequest_ShouldMapCorrectly() { // Arrange - RegistrationRequest request = _fixture.CreateRegistrationRequest(); + RegistrationRequest request = _fixture.Create(); // Act SetupApplicationCommand result = request.ToSetupCommand(); @@ -46,7 +38,7 @@ public class RegistrationRequestMappingTests public void ToCommand_WhenMappingRequest_ShouldMapCorrectly() { // Arrange - RegistrationRequest request = _fixture.CreateRegistrationRequest(); + RegistrationRequest request = _fixture.Create(); // Act RegisterUserCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMappingTests.cs index 74a81a4b..a4cf2112 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Common/FileSystemTreeNodeResponseMappingTests.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.FileSystemManagement.Common; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Common; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; @@ -16,15 +16,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Commo [ExcludeFromCodeCoverage] public class FileSystemTreeNodeResponseMappingTests { - private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; - - /// - /// Initializes a new instance of the class. - /// - public FileSystemTreeNodeResponseMappingTests() - { - _fileSystemTreeNodeResponseFixture = new(); - } + private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture = new(); [Fact] public void ToWindowsRootItem_WhenMappingFileSystemTreeNodeResponse_ShouldMapCorrectly() diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/DirectoryMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/DirectoryMappingTests.cs index 9072bd33..64c87103 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/DirectoryMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/DirectoryMappingTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Contracts.Responses.FileSystemManagement.Directories; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -18,25 +18,17 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Direc [ExcludeFromCodeCoverage] public class DirectoryMappingTests { - private readonly DirectoryFixture _directoryFixture; - - /// - /// Initializes a new instance of the class. - /// - public DirectoryMappingTests() - { - _directoryFixture = new DirectoryFixture(); - } + private readonly DirectoryFixture _directoryFixture = new(); [Fact] public void ToFileSystemTreeNodeResponse_WhenMappingDirectory_ShouldMapCorrectly() { // Arrange - Directory directory = _directoryFixture.CreateDirectory(); + Directory directory = _directoryFixture.Create(); List childItems = [ - _directoryFixture.CreateDirectory(), - _directoryFixture.CreateDirectory() + _directoryFixture.Create(), + _directoryFixture.Create() ]; foreach (FileSystemItem item in childItems) directory.AddItem(item); @@ -88,11 +80,11 @@ public class DirectoryMappingTests public void ToResponse_WhenMappingDirectory_ShouldMapCorrectly() { // Arrange - Directory directory = _directoryFixture.CreateDirectory(); + Directory directory = _directoryFixture.Create(); List childItems = [ - _directoryFixture.CreateDirectory(), - _directoryFixture.CreateDirectory() + _directoryFixture.Create(), + _directoryFixture.Create() ]; foreach (FileSystemItem item in childItems) directory.AddItem(item); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMappingTests.cs index 1c4d1d93..1e12bef4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMappingTests.cs @@ -1,8 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Directories; using Lumina.Contracts.Requests.FileSystemManagement.Directories; using System.Diagnostics.CodeAnalysis; #endregion @@ -15,21 +14,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Direc [ExcludeFromCodeCoverage] public class GetDirectoriesRequestMappingTests { - private readonly IFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public GetDirectoriesRequestMappingTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - } + private readonly GetDirectoriesRequestFixture _getDirectoriesRequestFixture = new(); [Fact] public void ToQuery_WhenMappingGetDirectoriesRequest_ShouldMapCorrectly() { // Arrange - GetDirectoriesRequest request = _fixture.Create(); + GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(); // Act GetDirectoriesQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/FileSystemItemMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/FileSystemItemMappingTests.cs index 1287327d..89032fd7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/FileSystemItemMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/FileSystemItemMappingTests.cs @@ -1,20 +1,18 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; -using Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem.Fixtures; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; -using Lumina.Application.UnitTests.Core.FileSystemManagement.FileSystem.Fixtures; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Fixtures; +using Lumina.Contracts.DTO.FileSystemManagement; using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; -using Lumina.Contracts.DTO.FileSystemManagement; #endregion namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem; @@ -25,29 +23,17 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileS [ExcludeFromCodeCoverage] public class FileSystemItemMappingTests { - private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; - private readonly DirectoryFixture _directoryFixture; - private readonly FileFixture _fileFixture; - private readonly WindowsRootItemFixture _windowsRootItemFixture; - private readonly UnixRootItemFixture _unixRootItemFixture; - - /// - /// Initializes a new instance of the class. - /// - public FileSystemItemMappingTests() - { - _fileSystemPathIdFixture = new FileSystemPathIdFixture(); - _directoryFixture = new DirectoryFixture(); - _fileFixture = new FileFixture(); - _windowsRootItemFixture = new WindowsRootItemFixture(); - _unixRootItemFixture = new UnixRootItemFixture(); - } + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly DirectoryFixture _directoryFixture = new(); + private readonly FileFixture _fileFixture = new(); + private readonly WindowsRootItemFixture _windowsRootItemFixture = new(); + private readonly UnixRootItemFixture _unixRootItemFixture = new(); [Fact] public void ToFileSystemItemModel_WhenMappingFileSystemItem_ShouldMapCorrectly() { // Arrange - FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId id = _fileSystemPathIdFixture.Create(); string name = "TestItem"; FileSystemItemType type = FileSystemItemType.File; FileSystemItemFixture domainModel = new(id, name, type); @@ -69,7 +55,7 @@ public class FileSystemItemMappingTests public void ToTreeNodeResponse_WhenMappingDirectory_ShouldMapCorrectly() { // Arrange - Directory directory = _directoryFixture.CreateDirectory(); + Directory directory = _directoryFixture.Create(); // Act FileSystemTreeNodeResponse result = directory.ToTreeNodeResponse(); @@ -85,7 +71,7 @@ public class FileSystemItemMappingTests public void ToTreeNodeResponse_WhenMappingFile_ShouldMapCorrectly() { // Arrange - File file = _fileFixture.CreateFile(); + File file = _fileFixture.Create(); // Act FileSystemTreeNodeResponse result = file.ToTreeNodeResponse(); @@ -141,7 +127,7 @@ public class FileSystemItemMappingTests public void ToFileSystemItemModel_WhenMappingDifferentFileSystemItems_ShouldMapCorrectly(string name, FileSystemItemType type) { // Arrange - FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId id = _fileSystemPathIdFixture.Create(); FileSystemItemFixture domainModel = new(id, name, type); // Act @@ -161,8 +147,8 @@ public class FileSystemItemMappingTests // Arrange List domainModels = [ - _directoryFixture.CreateDirectory(), - _fileFixture.CreateFile(), + _directoryFixture.Create(), + _fileFixture.Create(), _windowsRootItemFixture.Create(), _unixRootItemFixture.Create() ]; @@ -174,7 +160,7 @@ public class FileSystemItemMappingTests Assert.NotNull(result); Assert.Equal(domainModels.Count, result.Count()); - List resultList = result.ToList(); + List resultList = [.. result]; for (int i = 0; i < resultList.Count; i++) { Assert.Equal(domainModels[i].Name, resultList[i].Name); @@ -189,7 +175,7 @@ public class FileSystemItemMappingTests public void ToTreeNodeResponse_WhenMappingInvalidFileSystemItem_ShouldThrowArgumentException() { // Arrange - FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId id = _fileSystemPathIdFixture.Create(); string name = "TestItem"; FileSystemItemType type = FileSystemItemType.File; FileSystemItemFixture invalidItem = new(id, name, type); @@ -212,8 +198,8 @@ public class FileSystemItemMappingTests Assert.NotNull(result); Assert.Equal(domainModels.Count(), result.Count()); - List resultList = result.ToList(); - List domainModelsList = domainModels.ToList(); + List resultList = [.. result]; + List domainModelsList = [.. domainModels]; for (int i = 0; i < resultList.Count; i++) { Assert.Equal(domainModelsList[i].Name, resultList[i].Name); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/Fixtures/FileSystemItemFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/Fixtures/FileSystemItemFixture.cs deleted file mode 100644 index e6d2a564..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/Fixtures/FileSystemItemFixture.cs +++ /dev/null @@ -1,26 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class FileSystemItemFixture : FileSystemItem -{ - /// - /// Initializes a new instance of the class. - /// - /// The unique identifier for the file system path. - /// The name of the file system item. - /// The type of the file system item. - public FileSystemItemFixture(FileSystemPathId id, string name, FileSystemItemType fileSystemItemType) - : base(id, name, fileSystemItemType) - { - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/FileMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/FileMappingTests.cs index 6777564c..b6ba1e9d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/FileMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/FileMappingTests.cs @@ -1,10 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.FileSystemManagement.Files; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Contracts.Responses.FileSystemManagement.Files; -using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -19,21 +18,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Files [ExcludeFromCodeCoverage] public class FileMappingTests { - private readonly FileFixture _fileFixture; - - /// - /// Initializes a new instance of the class. - /// - public FileMappingTests() - { - _fileFixture = new(); - } + private readonly FileFixture _fileFixture = new(); [Fact] public void ToFileSystemTreeNodeResponse_WhenMappingFile_ShouldMapCorrectly() { // Arrange - File domainModel = _fileFixture.CreateFile(); + File domainModel = _fileFixture.Create(); // Act FileSystemTreeNodeResponse result = domainModel.ToFileSystemTreeNodeResponse(); @@ -60,8 +51,8 @@ public class FileMappingTests Assert.NotNull(result); Assert.Equal(domainModels.Count(), result.Count()); - List resultList = result.ToList(); - List domainModelsList = domainModels.ToList(); + List resultList = [.. result]; + List domainModelsList = [.. domainModels]; for (int i = 0; i < resultList.Count; i++) { Assert.Equal(domainModelsList[i].Name, resultList[i].Name); @@ -77,7 +68,7 @@ public class FileMappingTests public void ToResponse_WhenMappingFile_ShouldMapCorrectly() { // Arrange - File domainModel = _fileFixture.CreateFile(); + File domainModel = _fileFixture.Create(); // Act FileResponse result = domainModel.ToResponse(); @@ -104,8 +95,8 @@ public class FileMappingTests Assert.NotNull(result); Assert.Equal(domainModels.Count(), result.Count()); - List resultList = result.ToList(); - List domainModelsList = domainModels.ToList(); + List resultList = [.. result]; + List domainModelsList = [.. domainModels]; for (int i = 0; i < resultList.Count; i++) { Assert.Equal(domainModelsList[i].Name, resultList[i].Name); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMappingTests.cs index 77ea56d2..aafecb2d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMappingTests.cs @@ -1,8 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Mapping.FileSystemManagement.Files; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Files; using Lumina.Contracts.Requests.FileSystemManagement.Files; using System.Diagnostics.CodeAnalysis; #endregion @@ -15,21 +14,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Files [ExcludeFromCodeCoverage] public class GetFilesRequestMappingTests { - private readonly IFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public GetFilesRequestMappingTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - } + private readonly GetFilesRequestFixture _getFilesRequestFixture = new(); [Fact] public void ToQuery_WhenMappingGetFilesRequest_ShouldMapCorrectly() { // Arrange - GetFilesRequest request = _fixture.Create(); + GetFilesRequest request = _getFilesRequestFixture.Create(); // Act GetFilesQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMappingTests.cs index 9fe58845..41644ab7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMappingTests.cs @@ -1,8 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Mapping.FileSystemManagement.Files; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Files; using Lumina.Contracts.Requests.FileSystemManagement.Files; using System.Diagnostics.CodeAnalysis; #endregion @@ -15,21 +14,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Files [ExcludeFromCodeCoverage] public class GetTreeFilesRequestMappingTests { - private readonly IFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public GetTreeFilesRequestMappingTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - } + private readonly GetTreeFilesRequestFixture _getTreeFilesRequestFixture = new(); [Fact] public void ToQuery_WhenMappingGetTreeFilesRequest_ShouldMapCorrectly() { // Arrange - GetTreeFilesRequest request = _fixture.Create(); + GetTreeFilesRequest request = _getTreeFilesRequestFixture.Create(); // Act GetTreeFilesQuery result = request.ToQuery(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMappingTests.cs index 4bb47516..2ee1b6ab 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMappingTests.cs @@ -1,8 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; using Lumina.Contracts.Requests.FileSystemManagement.Path; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -17,21 +16,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths [ExcludeFromCodeCoverage] public class CheckPathExistsRequestMappingTests { - private readonly IFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public CheckPathExistsRequestMappingTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - } + private readonly CheckPathExistsRequestFixture _checkPathExistsRequestFixture = new(); [Fact] public void ToQuery_WhenMappingCheckPathExistsRequest_ShouldMapCorrectly() { // Arrange - CheckPathExistsRequest request = _fixture.Create(); + CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(); // Act CheckPathExistsQuery result = request.ToQuery(); @@ -64,7 +55,7 @@ public class CheckPathExistsRequestMappingTests public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly() { // Arrange - List requests = _fixture.CreateMany().ToList(); + List requests = _checkPathExistsRequestFixture.CreateMany(); // Act List results = requests.Select(r => r.ToQuery()).ToList(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMappingTests.cs index 9330cb7e..7f8331db 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/CombinePathRequestMappingTests.cs @@ -1,8 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; using Lumina.Contracts.Requests.FileSystemManagement.Path; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -17,21 +16,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths [ExcludeFromCodeCoverage] public class CombinePathRequestMappingTests { - private readonly IFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public CombinePathRequestMappingTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - } + private readonly CombinePathRequestFixture _combinePathRequestFixture = new(); [Fact] public void ToCommand_WhenMappingCombinePathRequest_ShouldMapCorrectly() { // Arrange - CombinePathRequest request = _fixture.Create(); + CombinePathRequest request = _combinePathRequestFixture.Create(); // Act CombinePathCommand result = request.ToCommand(); @@ -64,10 +55,10 @@ public class CombinePathRequestMappingTests public void ToCommand_WhenMappingMultipleRequests_ShouldMapAllCorrectly() { // Arrange - List requests = _fixture.CreateMany().ToList(); + List requests = _combinePathRequestFixture.CreateMany(); // Act - List results = requests.Select(r => r.ToCommand()).ToList(); + List results = [.. requests.Select(r => r.ToCommand())]; // Assert Assert.NotNull(results); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMappingTests.cs index d260e560..2ff9cf64 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathParentRequestMappingTests.cs @@ -1,8 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; using Lumina.Contracts.Requests.FileSystemManagement.Path; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -17,21 +16,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths [ExcludeFromCodeCoverage] public class GetPathParentRequestMappingTests { - private readonly IFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public GetPathParentRequestMappingTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - } + private readonly GetPathParentRequestFixture _getPathParentRequestFixture = new(); [Fact] public void ToQuery_WhenMappingGetPathParentRequest_ShouldMapCorrectly() { // Arrange - GetPathParentRequest request = _fixture.Create(); + GetPathParentRequest request = _getPathParentRequestFixture.Create(); // Act GetPathParentQuery result = request.ToQuery(); @@ -62,10 +53,10 @@ public class GetPathParentRequestMappingTests public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly() { // Arrange - List requests = _fixture.CreateMany().ToList(); + List requests = _getPathParentRequestFixture.CreateMany(); // Act - List results = requests.Select(r => r.ToQuery()).ToList(); + List results = [.. requests.Select(r => r.ToQuery())]; // Assert Assert.NotNull(results); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMappingTests.cs index 6622a57d..c771675e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/GetPathRootRequestMappingTests.cs @@ -1,8 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; using Lumina.Contracts.Requests.FileSystemManagement.Path; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -17,21 +16,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths [ExcludeFromCodeCoverage] public class GetPathRootRequestMappingTests { - private readonly IFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public GetPathRootRequestMappingTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - } + private readonly GetPathRootRequestFixture _getPathRootRequestFixture = new(); [Fact] public void ToQuery_WhenMappingGetPathRootRequest_ShouldMapCorrectly() { // Arrange - GetPathRootRequest request = _fixture.Create(); + GetPathRootRequest request = _getPathRootRequestFixture.Create(); // Act GetPathRootQuery result = request.ToQuery(); @@ -63,10 +54,10 @@ public class GetPathRootRequestMappingTests public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly() { // Arrange - List requests = _fixture.CreateMany().ToList(); + List requests = _getPathRootRequestFixture.CreateMany(); // Act - List results = requests.Select(r => r.ToQuery()).ToList(); + List results = [.. requests.Select(r => r.ToQuery())]; // Assert Assert.NotNull(results); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMappingTests.cs index 49709a54..64572d14 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/SplitPathRequestMappingTests.cs @@ -1,8 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; using Lumina.Contracts.Requests.FileSystemManagement.Path; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -17,21 +16,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths [ExcludeFromCodeCoverage] public class SplitPathRequestMappingTests { - private readonly IFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public SplitPathRequestMappingTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - } + private readonly SplitPathRequestFixture _splitPathRequestFixture = new(); [Fact] public void ToCommand_WhenMappingSplitPathRequest_ShouldMapCorrectly() { // Arrange - SplitPathRequest request = _fixture.Create(); + SplitPathRequest request = _splitPathRequestFixture.Create(); // Act SplitPathCommand result = request.ToCommand(); @@ -63,10 +54,10 @@ public class SplitPathRequestMappingTests public void ToCommand_WhenMappingMultipleRequests_ShouldMapAllCorrectly() { // Arrange - List requests = _fixture.CreateMany().ToList(); + List requests = _splitPathRequestFixture.CreateMany(); // Act - List results = requests.Select(r => r.ToCommand()).ToList(); + List results = [.. requests.Select(r => r.ToCommand())]; // Assert Assert.NotNull(results); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMappingTests.cs index 950dbddd..d55ea39d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/ValidatePathRequestMappingTests.cs @@ -1,8 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; using Lumina.Contracts.Requests.FileSystemManagement.Path; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -17,21 +16,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths [ExcludeFromCodeCoverage] public class ValidatePathRequestMappingTests { - private readonly IFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public ValidatePathRequestMappingTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - } + private readonly ValidatePathRequestFixture _validatePathRequestFixture = new(); [Fact] public void ToQuery_WhenMappingValidatePathRequest_ShouldMapCorrectly() { // Arrange - ValidatePathRequest request = _fixture.Create(); + ValidatePathRequest request = _validatePathRequestFixture.Create(); // Act ValidatePathQuery result = request.ToQuery(); @@ -65,10 +56,10 @@ public class ValidatePathRequestMappingTests public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly() { // Arrange - List requests = _fixture.CreateMany().ToList(); + List requests = _validatePathRequestFixture.CreateMany(); // Act - List results = requests.Select(r => r.ToQuery()).ToList(); + List results = [.. requests.Select(r => r.ToQuery())]; // Assert Assert.NotNull(results); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMappingTests.cs index b73aedd1..119e6166 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/GetThumbnailRequestMappingTests.cs @@ -1,8 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails; using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Thumbnails; using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -17,21 +16,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Thumb [ExcludeFromCodeCoverage] public class GetThumbnailRequestMappingTests { - private readonly IFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public GetThumbnailRequestMappingTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - } + private readonly GetThumbnailRequestFixture _getThumbnailRequestFixture = new(); [Fact] public void ToQuery_WhenMappingGetThumbnailRequest_ShouldMapCorrectly() { // Arrange - GetThumbnailRequest request = _fixture.Create(); + GetThumbnailRequest request = _getThumbnailRequestFixture.Create(); // Act GetThumbnailQuery result = request.ToQuery(); @@ -64,10 +55,10 @@ public class GetThumbnailRequestMappingTests public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly() { // Arrange - List requests = _fixture.CreateMany().ToList(); + List requests = _getThumbnailRequestFixture.CreateMany(); // Act - List results = requests.Select(r => r.ToQuery()).ToList(); + List results = [.. requests.Select(r => r.ToQuery())]; // Assert Assert.NotNull(results); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMappingTests.cs index f6d5d81b..26c977a6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Thumbnails/ThumbnailMappingTests.cs @@ -2,9 +2,10 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails; -using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -19,6 +20,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Thumb public class ThumbnailMappingTests { private readonly IFixture _fixture; + private readonly ThumbnailFixture _thumbnailFixture = new(); /// /// Initializes a new instance of the class. @@ -32,7 +34,7 @@ public class ThumbnailMappingTests public void ToResponse_WhenMappingThumbnail_ShouldMapCorrectly() { // Arrange - Thumbnail domainModel = _fixture.Create(); + Thumbnail domainModel = _thumbnailFixture.Create(); // Act ThumbnailResponse result = domainModel.ToResponse(); @@ -50,7 +52,7 @@ public class ThumbnailMappingTests public void ToResponse_WhenMappingDifferentImageTypes_ShouldMapCorrectly(ImageType imageType) { // Arrange - byte[] bytes = _fixture.CreateMany(100).ToArray(); + byte[] bytes = [.. _fixture.CreateMany(100)]; Thumbnail domainModel = new(imageType, bytes); // Act @@ -83,10 +85,10 @@ public class ThumbnailMappingTests public void ToResponse_WhenMappingMultipleThumbnails_ShouldMapAllCorrectly() { // Arrange - List thumbnails = _fixture.CreateMany(3).ToList(); + List thumbnails = _thumbnailFixture.CreateMany(3); // Act - List results = thumbnails.Select(t => t.ToResponse()).ToList(); + List results = [.. thumbnails.Select(t => t.ToResponse())]; // Assert Assert.NotNull(results); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs index 98a641e8..53f28f53 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; -using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; @@ -18,21 +18,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class AddBookRequestMappingTests { - private readonly AddBookRequestFixture _requestFixture; - - /// - /// Initializes a new instance of the class. - /// - public AddBookRequestMappingTests() - { - _requestFixture = new AddBookRequestFixture(); - } + private readonly AddBookRequestFixture _requestFixture = new(); [Fact] public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() { // Arrange - AddBookRequest request = _requestFixture.CreateRequestBook(); + AddBookRequest request = _requestFixture.Create(); // Act AddBookCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs index 5a4aa400..7dcbadc5 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs @@ -2,7 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Primitives; @@ -20,21 +20,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class BookEntityMappingTests { - private readonly BookEntityFixture _bookEntityFixture; - - /// - /// Initializes a new instance of the class. - /// - public BookEntityMappingTests() - { - _bookEntityFixture = new BookEntityFixture(); - } + private readonly BookEntityFixture _bookEntityFixture = new(); [Fact] public void ToDomainEntity_WhenMappingValidBookEntity_ShouldMapCorrectly() { // Arrange - BookEntity bookEntity = _bookEntityFixture.CreateBook(); + BookEntity bookEntity = _bookEntityFixture.Create(); // Act Result result = bookEntity.ToDomainEntity(); @@ -264,7 +256,7 @@ public class BookEntityMappingTests public void ToResponse_WhenMappingBookEntity_ShouldMapAllPropertiesCorrectly() { // Arrange - BookEntity bookEntity = _bookEntityFixture.CreateBook(); + BookEntity bookEntity = _bookEntityFixture.Create(); // Act BookResponse result = bookEntity.ToResponse(); @@ -318,11 +310,7 @@ public class BookEntityMappingTests public void ToDomainModels_WhenMappingMultipleBookEntities_ShouldMapAllCorrectly() { // Arrange - List bookEntities = - [ - _bookEntityFixture.CreateBook(), - _bookEntityFixture.CreateBook() - ]; + List bookEntities = _bookEntityFixture.CreateMany(2); // Act IEnumerable> results = bookEntities.ToDomainEntities(); @@ -337,11 +325,8 @@ public class BookEntityMappingTests public void ToResponses_WhenMappingMultipleBookEntities_ShouldMapAllCorrectly() { // Arrange - List bookEntities = - [ - _bookEntityFixture.CreateBook(), - _bookEntityFixture.CreateBook() - ]; + List bookEntities = _bookEntityFixture.CreateMany(2); + // Act IEnumerable results = bookEntities.ToResponses(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs index fdb42e58..315c7a11 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using System.Diagnostics.CodeAnalysis; -using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; #endregion namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -16,21 +16,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class BookMappingTests { - private readonly BookFixture _bookFixture; - - /// - /// Initializes a new instance of the class. - /// - public BookMappingTests() - { - _bookFixture = new BookFixture(); - } + private readonly BookFixture _bookFixture = new(); [Fact] public void ToRepositoryEntity_WhenMappingCompleteBook_ShouldMapAllPropertiesCorrectly() { // Arrange - Book book = _bookFixture.CreateDomainBook(); + Book book = _bookFixture.Create(); // Act BookEntity result = book.ToRepositoryEntity(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs index 453c8a41..61296609 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; #endregion @@ -22,7 +22,7 @@ public class BookMetadataDtoMappingTests public void ApplyMetadata_WhenCalledWithValidMetadata_ShouldApplyItAndMarkTheBookAsEnriched() { // Arrange - Book book = _bookFixture.CreateDomainBook(); + Book book = _bookFixture.Create(); BookMetadataDto metadata = CreateBookMetadata("The Fellowship of the Ring", "3"); // Act @@ -44,7 +44,7 @@ public class BookMetadataDtoMappingTests public void ApplyMetadata_WhenCalledWithInvalidGenres_ShouldReturnError() { // Arrange - Book book = _bookFixture.CreateDomainBook(); + Book book = _bookFixture.Create(); BookMetadataDto metadata = CreateBookMetadata("The Fellowship of the Ring", "3") with { Genres = [new GenreDto("")] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMappingTests.cs index 33735503..fe558119 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingDtoMappingTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; -using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using System.Collections.Generic; @@ -18,21 +18,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class BookRatingDtoMappingTests { - private readonly BookRatingDtoFixture _bookRatingDtoFixture; - - /// - /// Initializes a new instance of the class. - /// - public BookRatingDtoMappingTests() - { - _bookRatingDtoFixture = new BookRatingDtoFixture(); - } + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); [Fact] public void ToDomainEntity_WhenMappingCompleteBookRatinDto_ShouldMapAllPropertiesCorrectly() { // Arrange - BookRatingDto dto = _bookRatingDtoFixture.CreateComplete(); + BookRatingDto dto = _bookRatingDtoFixture.Create(); // Act Result result = dto.ToDomainEntity(); @@ -64,7 +56,7 @@ public class BookRatingDtoMappingTests public void ToDomainEntity_WhenMappingMinimalBookRatingDto_ShouldMapRequiredPropertiesCorrectly() { // Arrange - BookRatingDto dto = _bookRatingDtoFixture.CreateMinimal(); + BookRatingDto dto = _bookRatingDtoFixture.Create(includeOptionalProperties: false); // Act Result result = dto.ToDomainEntity(); @@ -82,7 +74,7 @@ public class BookRatingDtoMappingTests public void ToDomainEntity_WhenMappingInvalidBookRatingDto_ShouldReturnError() { // Arrange - BookRatingDto dto = _bookRatingDtoFixture.CreateInvalid(); + BookRatingDto dto = _bookRatingDtoFixture.Create(value: 10, maxValue: 5); // Act Result result = dto.ToDomainEntity(); @@ -97,8 +89,8 @@ public class BookRatingDtoMappingTests // Arrange List dtos = [ - _bookRatingDtoFixture.CreateComplete(), - _bookRatingDtoFixture.CreateMinimal() + _bookRatingDtoFixture.Create(), + _bookRatingDtoFixture.Create(includeOptionalProperties: false) ]; // Act @@ -131,9 +123,9 @@ public class BookRatingDtoMappingTests // Arrange List dtos = [ - _bookRatingDtoFixture.CreateComplete(), - _bookRatingDtoFixture.CreateInvalid(), - _bookRatingDtoFixture.CreateMinimal() + _bookRatingDtoFixture.Create(), + _bookRatingDtoFixture.Create(value: 10, maxValue: 5), + _bookRatingDtoFixture.Create(includeOptionalProperties: false) ]; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMappingTests.cs index b54392d6..465a89eb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingEntityMappingTests.cs @@ -2,7 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; -using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; @@ -19,21 +19,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class BookRatingEntityMappingTests { - private readonly BookRatingEntityFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public BookRatingEntityMappingTests() - { - _fixture = new BookRatingEntityFixture(); - } + private readonly BookRatingEntityFixture _fixture = new(); [Fact] public void ToResponse_WhenMappingValidBookRatingEntity_ShouldMapCorrectly() { // Arrange - BookRatingEntity entity = _fixture.CreateBookRating(); + BookRatingEntity entity = _fixture.Create(); // Act BookRatingDto result = entity.ToResponse(); @@ -50,7 +42,7 @@ public class BookRatingEntityMappingTests public void ToResponse_WhenMappingInvalidBookRatingEntity_ShouldMapToDefaults() { // Arrange - BookRatingEntity entity = _fixture.CreateInvalidBookRating(); + BookRatingEntity entity = _fixture.Create(includeValues: false); // Act BookRatingDto result = entity.ToResponse(); @@ -67,12 +59,7 @@ public class BookRatingEntityMappingTests public void ToResponses_WhenMappingMultipleBookRatingEntities_ShouldMapAllCorrectly() { // Arrange - List entities = - [ - _fixture.CreateBookRating(), - _fixture.CreateBookRating() - ]; - + List entities = _fixture.CreateMany(2); // Act IEnumerable results = entities.ToResponses(); @@ -92,7 +79,7 @@ public class BookRatingEntityMappingTests public void ToDomainEntity_WhenMappingValidBookRatingEntity_ShouldMapCorrectly() { // Arrange - BookRatingEntity entity = _fixture.CreateBookRating(); + BookRatingEntity entity = _fixture.Create(); // Act Result result = entity.ToDomainEntity(); @@ -110,7 +97,7 @@ public class BookRatingEntityMappingTests public void ToDomainEntity_WhenMappingInvalidBookRatingEntity_ShouldMapToDefaults() { // Arrange - BookRatingEntity entity = _fixture.CreateInvalidBookRating(); + BookRatingEntity entity = _fixture.Create(includeValues: false); // Act Result result = entity.ToDomainEntity(); @@ -128,11 +115,7 @@ public class BookRatingEntityMappingTests public void ToDomainEntities_WhenMappingMultipleBookRatingEntities_ShouldMapAllCorrectly() { // Arrange - List entities = - [ - _fixture.CreateBookRating(), - _fixture.CreateBookRating() - ]; + List entities = _fixture.CreateMany(2); // Act IEnumerable> results = entities.ToDomainEntities(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingMappingTests.cs index df798878..7913f255 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/BookRatingMappingTests.cs @@ -2,8 +2,10 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; -using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -17,21 +19,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class BookRatingMappingTests { - private readonly BookRatingFixture _bookRatingFixture; - - /// - /// Initializes a new instance of the class. - /// - public BookRatingMappingTests() - { - _bookRatingFixture = new BookRatingFixture(); - } + private readonly BookRatingFixture _bookRatingFixture = new(); [Fact] public void ToRepositoryEntity_WhenMappingCompleteBookRating_ShouldMapAllPropertiesCorrectly() { // Arrange - BookRating bookRating = _bookRatingFixture.CreateBookRating(); + BookRating bookRating = _bookRatingFixture.Create(); // Act BookRatingEntity result = bookRating.ToRepositoryEntity(); @@ -48,7 +42,7 @@ public class BookRatingMappingTests public void ToRepositoryEntity_WhenMappingBookRatingWithoutSource_ShouldMapCorrectly() { // Arrange - BookRating bookRating = _bookRatingFixture.CreateBookRatingWithoutSource(); + BookRating bookRating = _bookRatingFixture.Create(source: Optional.None()); // Act BookRatingEntity result = bookRating.ToRepositoryEntity(); @@ -65,7 +59,7 @@ public class BookRatingMappingTests public void ToRepositoryEntity_WhenMappingBookRatingWithoutVoteCount_ShouldMapCorrectly() { // Arrange - BookRating bookRating = _bookRatingFixture.CreateBookRatingWithoutVoteCount(); + BookRating bookRating = _bookRatingFixture.Create(voteCount: Optional.None()); // Act BookRatingEntity result = bookRating.ToRepositoryEntity(); @@ -84,9 +78,9 @@ public class BookRatingMappingTests // Arrange List bookRatings = [ - _bookRatingFixture.CreateBookRating(), - _bookRatingFixture.CreateBookRatingWithoutSource(), - _bookRatingFixture.CreateBookRatingWithoutVoteCount() + _bookRatingFixture.Create(), + _bookRatingFixture.Create(source: Optional.None()), + _bookRatingFixture.Create(voteCount: Optional.None()) ]; // Act @@ -96,7 +90,7 @@ public class BookRatingMappingTests Assert.NotNull(results); Assert.Equal(bookRatings.Count, results.Count()); - List resultList = results.ToList(); + List resultList = [.. results]; // complete rating Assert.Equal(bookRatings[0].Value, resultList[0].Value); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMappingTests.cs index 7bee8e6e..96b6737d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnDtoMappingTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; -using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; @@ -19,21 +19,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class IsbnDtoMappingTests { - private readonly IsbnDtoFixture _isbnDtoFixture; - - /// - /// Initializes a new instance of the class. - /// - public IsbnDtoMappingTests() - { - _isbnDtoFixture = new IsbnDtoFixture(); - } + private readonly IsbnDtoFixture _isbnDtoFixture = new(); [Fact] public void ToDomainEntity_WhenMappingValidIsbn10Dto_ShouldMapCorrectly() { // Arrange - IsbnDto dto = _isbnDtoFixture.CreateIsbn10(); + IsbnDto dto = _isbnDtoFixture.Create(format: IsbnFormat.Isbn10); // Act Result result = dto.ToDomainEntity(); @@ -49,7 +41,7 @@ public class IsbnDtoMappingTests public void ToDomainEntity_WhenMappingValidIsbn13Dto_ShouldMapCorrectly() { // Arrange - IsbnDto dto = _isbnDtoFixture.CreateIsbn13(); + IsbnDto dto = _isbnDtoFixture.Create(format: IsbnFormat.Isbn13); // Act Result result = dto.ToDomainEntity(); @@ -65,7 +57,7 @@ public class IsbnDtoMappingTests public void ToDomainEntity_WhenMappingDtoWithoutFormat_ShouldUseDefaultFormat() { // Arrange - IsbnDto dto = _isbnDtoFixture.CreateWithoutFormat(); + IsbnDto dto = _isbnDtoFixture.Create(); // Act Result result = dto.ToDomainEntity(); @@ -81,7 +73,7 @@ public class IsbnDtoMappingTests public void ToDomainEntity_WhenMappingInvalidIsbnDto_ShouldReturnError() { // Arrange - IsbnDto dto = _isbnDtoFixture.CreateInvalid(); + IsbnDto dto = _isbnDtoFixture.Create("invalid-isbn", IsbnFormat.Isbn13); // Act Result result = dto.ToDomainEntity(); @@ -96,9 +88,9 @@ public class IsbnDtoMappingTests // Arrange List dtos = [ - _isbnDtoFixture.CreateIsbn10(), - _isbnDtoFixture.CreateIsbn13(), - _isbnDtoFixture.CreateWithoutFormat() + _isbnDtoFixture.Create(format: IsbnFormat.Isbn10), + _isbnDtoFixture.Create(format: IsbnFormat.Isbn13), + _isbnDtoFixture.Create(), ]; // Act @@ -127,9 +119,9 @@ public class IsbnDtoMappingTests // Arrange List dtos = [ - _isbnDtoFixture.CreateIsbn10(), - _isbnDtoFixture.CreateInvalid(), - _isbnDtoFixture.CreateIsbn13() + _isbnDtoFixture.Create(format: IsbnFormat.Isbn10), + _isbnDtoFixture.Create("invalid-isbn", IsbnFormat.Isbn13), + _isbnDtoFixture.Create(format: IsbnFormat.Isbn13) ]; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnMappingTests.cs index 448ff743..5f4f826a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnMappingTests.cs @@ -2,9 +2,9 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; -using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -18,21 +18,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class IsbnMappingTests { - private readonly IsbnFixture _isbnFixture; - - /// - /// Initializes a new instance of the class. - /// - public IsbnMappingTests() - { - _isbnFixture = new IsbnFixture(); - } + private readonly IsbnFixture _isbnFixture = new(); [Fact] public void ToRepositoryEntity_WhenMappingIsbn10_ShouldMapCorrectly() { // Arrange - Isbn isbn = _isbnFixture.CreateIsbn10(); + Isbn isbn = _isbnFixture.Create(IsbnFormat.Isbn10); // Act IsbnEntity result = isbn.ToRepositoryEntity(); @@ -47,7 +39,7 @@ public class IsbnMappingTests public void ToRepositoryEntity_WhenMappingIsbn13_ShouldMapCorrectly() { // Arrange - Isbn isbn = _isbnFixture.CreateIsbn13(); + Isbn isbn = _isbnFixture.Create(IsbnFormat.Isbn13); // Act IsbnEntity result = isbn.ToRepositoryEntity(); @@ -64,9 +56,9 @@ public class IsbnMappingTests // Arrange List isbns = [ - _isbnFixture.CreateIsbn10(), - _isbnFixture.CreateIsbn13(), - _isbnFixture.CreateIsbn10() + _isbnFixture.Create(IsbnFormat.Isbn10), + _isbnFixture.Create(IsbnFormat.Isbn13), + _isbnFixture.Create(IsbnFormat.Isbn10) ]; // Act @@ -76,7 +68,7 @@ public class IsbnMappingTests Assert.NotNull(results); Assert.Equal(isbns.Count, results.Count()); - List resultList = results.ToList(); + List resultList = [.. results]; for (int i = 0; i < isbns.Count; i++) { Assert.Equal(isbns[i].Value, resultList[i].Value); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserEntityMappingTests.cs index b70cca98..0fadf1db 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserEntityMappingTests.cs @@ -3,7 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; using Lumina.Application.Common.Mapping.UsersManagement.Users; -using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Responses.UsersManagement.Users; using System; using System.Collections.Generic; @@ -19,11 +19,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users; [ExcludeFromCodeCoverage] public class UserEntityMappingTests { + private readonly UserEntityFixture _userEntityFixture = new(); + [Fact] public void ToResponse_WhenMappingValidUserEntity_ShouldMapCorrectly() { // Arrange - UserEntity entity = UserEntityFixture.CreateUserEntity(); + UserEntity entity = _userEntityFixture.Create(); // Act UserResponse result = entity.ToResponse(); @@ -44,7 +46,7 @@ public class UserEntityMappingTests public void ToResponse_WhenMappingDifferentUsernames_ShouldMapCorrectly(string username) { // Arrange - UserEntity entity = UserEntityFixture.CreateUserEntity(); + UserEntity entity = _userEntityFixture.Create(); entity.Username = username; // Act @@ -59,7 +61,7 @@ public class UserEntityMappingTests public void ToResponse_WhenMappingWithUpdatedDateTime_ShouldMapCorrectly() { // Arrange - UserEntity entity = UserEntityFixture.CreateUserEntity(); + UserEntity entity = _userEntityFixture.Create(); entity.UpdatedOnUtc = DateTime.UtcNow.AddDays(-1); // Act @@ -74,7 +76,7 @@ public class UserEntityMappingTests public void ToResponse_WhenMappingWithLibraries_ShouldNotAffectMapping() { // Arrange - UserEntity entity = UserEntityFixture.CreateUserEntity(2); + UserEntity entity = _userEntityFixture.Create(2); // Act UserResponse result = entity.ToResponse(); @@ -91,7 +93,7 @@ public class UserEntityMappingTests public void ToResponses_WhenMappingMultipleEntities_ShouldMapCorrectly() { // Arrange - List entities = UserEntityFixture.CreateMany(3); + List entities = _userEntityFixture.CreateMany(3); // Act IEnumerable results = entities.ToResponses(); @@ -127,7 +129,7 @@ public class UserEntityMappingTests public void ToResponse_WhenMappingWithoutUpdatedDateTime_ShouldMapCorrectly() { // Arrange - UserEntity entity = UserEntityFixture.CreateUserEntity(); + UserEntity entity = _userEntityFixture.Create(); entity.UpdatedOnUtc = null; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs index 1b2ade05..873db101 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs @@ -7,7 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; -using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.AddRole.Fixtures; +using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.AddRole; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; @@ -32,7 +32,7 @@ public class AddRoleCommandHandlerTests private readonly ICurrentUserService _mockCurrentUserService; private readonly IRoleRepository _mockRoleRepository; private readonly AddRoleCommandHandler _sut; - private readonly AddRoleCommandFixture _addRoleCommandFixture; + private readonly AddRoleCommandFixture _addRoleCommandFixture = new(); private readonly Guid _userId; /// @@ -47,7 +47,6 @@ public class AddRoleCommandHandlerTests _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockRoleRepository = Substitute.For(); - _addRoleCommandFixture = new AddRoleCommandFixture(); _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); @@ -64,7 +63,7 @@ public class AddRoleCommandHandlerTests public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange - AddRoleCommand command = _addRoleCommandFixture.CreateCommand(); + AddRoleCommand command = _addRoleCommandFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(false); @@ -81,7 +80,7 @@ public class AddRoleCommandHandlerTests public async Task HandleAsync_WhenInsertRoleFails_ShouldReturnError() { // Arrange - AddRoleCommand command = _addRoleCommandFixture.CreateCommand(); + AddRoleCommand command = _addRoleCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to insert role"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -102,7 +101,7 @@ public class AddRoleCommandHandlerTests public async Task HandleAsync_WhenGetRoleByNameFails_ShouldReturnError() { // Arrange - AddRoleCommand command = _addRoleCommandFixture.CreateCommand(); + AddRoleCommand command = _addRoleCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get role"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -124,7 +123,7 @@ public class AddRoleCommandHandlerTests public async Task HandleAsync_WhenGetRoleByNameReturnsNull_ShouldReturnError() { // Arrange - AddRoleCommand command = _addRoleCommandFixture.CreateCommand(); + AddRoleCommand command = _addRoleCommandFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); @@ -145,7 +144,7 @@ public class AddRoleCommandHandlerTests public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccessResponse() { // Arrange - AddRoleCommand command = _addRoleCommandFixture.CreateCommand(); + AddRoleCommand command = _addRoleCommandFixture.Create(); Guid roleId = Guid.NewGuid(); RoleEntity role = new() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs index 47eb0c52..9ed9e01c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Errors; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; +using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.AddRole; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.AddRole.Fixtures; using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; @@ -17,23 +17,14 @@ namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.A [ExcludeFromCodeCoverage] public class AddRoleCommandValidatorTests { - private readonly AddRoleCommandValidator _validator; - private readonly AddRoleCommandFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public AddRoleCommandValidatorTests() - { - _validator = new AddRoleCommandValidator(); - _fixture = new AddRoleCommandFixture(); - } + private readonly AddRoleCommandValidator _validator = new(); + private readonly AddRoleCommandFixture _fixture = new(); [Fact] public void Validate_WhenRoleNameIsNull_ShouldHaveValidationError() { // Arrange - AddRoleCommand command = _fixture.CreateCommand(); + AddRoleCommand command = _fixture.Create(); command = command with { RoleName = null! }; // Act @@ -47,7 +38,7 @@ public class AddRoleCommandValidatorTests public void Validate_WhenRoleNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddRoleCommand command = _fixture.CreateCommand(); + AddRoleCommand command = _fixture.Create(); command = command with { RoleName = string.Empty }; // Act @@ -61,7 +52,7 @@ public class AddRoleCommandValidatorTests public void Validate_WhenRoleNameIsWhitespace_ShouldHaveValidationError() { // Arrange - AddRoleCommand command = _fixture.CreateCommand(); + AddRoleCommand command = _fixture.Create(); command = command with { RoleName = " " }; // Act @@ -75,7 +66,7 @@ public class AddRoleCommandValidatorTests public void Validate_WhenPermissionsIsNull_ShouldHaveValidationError() { // Arrange - AddRoleCommand command = _fixture.CreateCommand(); + AddRoleCommand command = _fixture.Create(); command = command with { Permissions = null! }; // Act @@ -89,7 +80,7 @@ public class AddRoleCommandValidatorTests public void Validate_WhenPermissionsIsEmpty_ShouldHaveValidationError() { // Arrange - AddRoleCommand command = _fixture.CreateCommand(); + AddRoleCommand command = _fixture.Create(); command = command with { Permissions = [] }; // Act @@ -103,7 +94,7 @@ public class AddRoleCommandValidatorTests public void Validate_WhenPermissionContainsEmptyGuid_ShouldHaveValidationError() { // Arrange - AddRoleCommand command = _fixture.CreateCommand(); + AddRoleCommand command = _fixture.Create(); command = command with { Permissions = [Guid.Empty, Guid.NewGuid()] }; // Act @@ -117,7 +108,7 @@ public class AddRoleCommandValidatorTests public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { // Arrange - AddRoleCommand command = _fixture.CreateCommand(); + AddRoleCommand command = _fixture.Create(); // Act List result = _validator.TestValidate(command); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/Fixtures/AddRoleCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/Fixtures/AddRoleCommandFixture.cs deleted file mode 100644 index d479ba3e..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/Fixtures/AddRoleCommandFixture.cs +++ /dev/null @@ -1,34 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.AddRole.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class AddRoleCommandFixture -{ - /// - /// Creates a random valid command to add a role. - /// - /// The number of permissions to generate. - /// The created command to add a role. - public AddRoleCommand CreateCommand(int permissionCount = 3) - { - return new Faker() - .CustomInstantiator(f => new AddRoleCommand( - default!, - default!)) - .RuleFor(x => x.RoleName, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(x => x.Permissions, f => Enumerable.Range(0, permissionCount) - .Select(_ => Guid.NewGuid()) - .ToList()) - .Generate(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs index 6f313560..1b5b8a7d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs @@ -7,7 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; -using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.DeleteRole.Fixtures; +using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.DeleteRole; using Lumina.Domain.Common.Primitives; using NSubstitute; using System; @@ -29,7 +29,7 @@ public class DeleteRoleCommandHandlerTests private readonly ICurrentUserService _mockCurrentUserService; private readonly IRoleRepository _mockRoleRepository; private readonly DeleteRoleCommandHandler _sut; - private readonly DeleteRoleCommandFixture _deleteRoleCommandFixture; + private readonly DeleteRoleCommandFixture _deleteRoleCommandFixture = new(); private readonly Guid _userId; /// @@ -44,7 +44,6 @@ public class DeleteRoleCommandHandlerTests _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockRoleRepository = Substitute.For(); - _deleteRoleCommandFixture = new DeleteRoleCommandFixture(); _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); @@ -61,7 +60,7 @@ public class DeleteRoleCommandHandlerTests public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange - DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand(); + DeleteRoleCommand command = _deleteRoleCommandFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(false); @@ -78,7 +77,7 @@ public class DeleteRoleCommandHandlerTests public async Task HandleAsync_WhenRoleDoesNotExist_ShouldReturnRoleNotFoundError() { // Arrange - DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand(); + DeleteRoleCommand command = _deleteRoleCommandFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); @@ -98,7 +97,7 @@ public class DeleteRoleCommandHandlerTests public async Task HandleAsync_WhenDeletingAdminRole_ShouldReturnAdminRoleCannotBeDeletedError() { // Arrange - DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand(); + DeleteRoleCommand command = _deleteRoleCommandFixture.Create(); RoleEntity adminRole = new() { Id = command.RoleId, RoleName = "Admin" }; _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -119,7 +118,7 @@ public class DeleteRoleCommandHandlerTests public async Task HandleAsync_WhenGetRoleByIdFails_ShouldReturnError() { // Arrange - DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand(); + DeleteRoleCommand command = _deleteRoleCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get role"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -140,7 +139,7 @@ public class DeleteRoleCommandHandlerTests public async Task HandleAsync_WhenDeleteRoleFails_ShouldReturnError() { // Arrange - DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand(); + DeleteRoleCommand command = _deleteRoleCommandFixture.Create(); RoleEntity role = new() { Id = command.RoleId, RoleName = "TestRole" }; Error error = Error.Failure("Database.Error", "Failed to delete role"); @@ -164,7 +163,7 @@ public class DeleteRoleCommandHandlerTests public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccess() { // Arrange - DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand(); + DeleteRoleCommand command = _deleteRoleCommandFixture.Create(); RoleEntity role = new() { Id = command.RoleId, RoleName = "TestRole" }; _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs index 4f0203ad..2869e5be 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidatorTests.cs @@ -16,15 +16,7 @@ namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.D [ExcludeFromCodeCoverage] public class DeleteRoleCommandValidatorTests { - private readonly DeleteRoleCommandValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public DeleteRoleCommandValidatorTests() - { - _validator = new DeleteRoleCommandValidator(); - } + private readonly DeleteRoleCommandValidator _validator = new(); [Fact] public void Validate_WhenRoleIdIsEmpty_ShouldHaveValidationError() diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/Fixtures/UpdateRoleCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/Fixtures/UpdateRoleCommandFixture.cs deleted file mode 100644 index 9b71981b..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/Fixtures/UpdateRoleCommandFixture.cs +++ /dev/null @@ -1,46 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.UpdateRole.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class UpdateRoleCommandFixture -{ - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public UpdateRoleCommandFixture() - { - _faker = new Faker(); - } - - /// - /// Creates a random valid command to update a role. - /// - /// The number of permissions to generate. - /// The created command to update a role. - public UpdateRoleCommand CreateCommand(int permissionCount = 3) - { - return new Faker() - .CustomInstantiator(f => new UpdateRoleCommand( - default, - default!, - default!)) - .RuleFor(x => x.RoleId, f => Guid.NewGuid()) - .RuleFor(x => x.RoleName, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(x => x.Permissions, f => Enumerable.Range(0, permissionCount) - .Select(_ => Guid.NewGuid()) - .ToList()) - .Generate(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs index 748957f9..4cb7bc75 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs @@ -7,7 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; -using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.UpdateRole.Fixtures; +using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.UpdateRole; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; @@ -32,7 +32,7 @@ public class UpdateRoleCommandHandlerTests private readonly ICurrentUserService _mockCurrentUserService; private readonly IRoleRepository _mockRoleRepository; private readonly UpdateRoleCommandHandler _sut; - private readonly UpdateRoleCommandFixture _updateRoleCommandFixture; + private readonly UpdateRoleCommandFixture _updateRoleCommandFixture = new(); private readonly Guid _userId; /// @@ -47,7 +47,6 @@ public class UpdateRoleCommandHandlerTests _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockRoleRepository = Substitute.For(); - _updateRoleCommandFixture = new UpdateRoleCommandFixture(); _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); @@ -64,7 +63,7 @@ public class UpdateRoleCommandHandlerTests public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange - UpdateRoleCommand command = _updateRoleCommandFixture.CreateCommand(); + UpdateRoleCommand command = _updateRoleCommandFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(false); @@ -81,7 +80,7 @@ public class UpdateRoleCommandHandlerTests public async Task HandleAsync_WhenUpdateRoleFails_ShouldReturnError() { // Arrange - UpdateRoleCommand command = _updateRoleCommandFixture.CreateCommand(); + UpdateRoleCommand command = _updateRoleCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to update role"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -102,7 +101,7 @@ public class UpdateRoleCommandHandlerTests public async Task HandleAsync_WhenGetRoleByIdFails_ShouldReturnError() { // Arrange - UpdateRoleCommand command = _updateRoleCommandFixture.CreateCommand(); + UpdateRoleCommand command = _updateRoleCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get role"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -124,7 +123,7 @@ public class UpdateRoleCommandHandlerTests public async Task HandleAsync_WhenGetRoleByIdReturnsNull_ShouldReturnError() { // Arrange - UpdateRoleCommand command = _updateRoleCommandFixture.CreateCommand(); + UpdateRoleCommand command = _updateRoleCommandFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); @@ -145,7 +144,7 @@ public class UpdateRoleCommandHandlerTests public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccessResponse() { // Arrange - UpdateRoleCommand command = _updateRoleCommandFixture.CreateCommand(); + UpdateRoleCommand command = _updateRoleCommandFixture.Create(); RoleEntity role = new() { Id = command.RoleId, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs index 3bdd1653..4a0554f6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidatorTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Errors; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; +using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.UpdateRole; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.UpdateRole.Fixtures; using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; @@ -17,23 +17,14 @@ namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.U [ExcludeFromCodeCoverage] public class UpdateRoleCommandValidatorTests { - private readonly UpdateRoleCommandValidator _validator; - private readonly UpdateRoleCommandFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public UpdateRoleCommandValidatorTests() - { - _validator = new UpdateRoleCommandValidator(); - _fixture = new UpdateRoleCommandFixture(); - } + private readonly UpdateRoleCommandValidator _validator = new(); + private readonly UpdateRoleCommandFixture _fixture = new(); [Fact] public void Validate_WhenRoleIdIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.CreateCommand(); + UpdateRoleCommand command = _fixture.Create(); command = command with { RoleId = Guid.Empty }; // Act @@ -47,7 +38,7 @@ public class UpdateRoleCommandValidatorTests public void Validate_WhenRoleNameIsNull_ShouldHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.CreateCommand(); + UpdateRoleCommand command = _fixture.Create(); command = command with { RoleName = null! }; // Act @@ -61,7 +52,7 @@ public class UpdateRoleCommandValidatorTests public void Validate_WhenRoleNameIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.CreateCommand(); + UpdateRoleCommand command = _fixture.Create(); command = command with { RoleName = string.Empty }; // Act @@ -75,7 +66,7 @@ public class UpdateRoleCommandValidatorTests public void Validate_WhenRoleNameIsWhitespace_ShouldHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.CreateCommand(); + UpdateRoleCommand command = _fixture.Create(); command = command with { RoleName = " " }; // Act @@ -89,7 +80,7 @@ public class UpdateRoleCommandValidatorTests public void Validate_WhenPermissionsIsNull_ShouldHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.CreateCommand(); + UpdateRoleCommand command = _fixture.Create(); command = command with { Permissions = null! }; // Act @@ -103,7 +94,7 @@ public class UpdateRoleCommandValidatorTests public void Validate_WhenPermissionsIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.CreateCommand(); + UpdateRoleCommand command = _fixture.Create(); command = command with { Permissions = [] }; // Act @@ -117,7 +108,7 @@ public class UpdateRoleCommandValidatorTests public void Validate_WhenPermissionContainsEmptyGuid_ShouldHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.CreateCommand(); + UpdateRoleCommand command = _fixture.Create(); command = command with { Permissions = [Guid.Empty, Guid.NewGuid()] }; // Act @@ -131,7 +122,7 @@ public class UpdateRoleCommandValidatorTests public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { // Arrange - UpdateRoleCommand command = _fixture.CreateCommand(); + UpdateRoleCommand command = _fixture.Create(); // Act List result = _validator.TestValidate(command); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs index d1807feb..4cf3eaab 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs @@ -7,7 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; -using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.GetRolePermissions.Fixtures; +using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; @@ -31,7 +31,7 @@ public class GetRolePermissionsQueryHandlerTests private readonly ICurrentUserService _mockCurrentUserService; private readonly IRoleRepository _mockRoleRepository; private readonly GetRolePermissionsQueryHandler _sut; - private readonly GetRolePermissionsQueryFixture _getRolePermissionsQueryFixture; + private readonly GetRolePermissionsQueryFixture _getRolePermissionsQueryFixture = new(); private readonly Guid _userId; /// @@ -46,7 +46,6 @@ public class GetRolePermissionsQueryHandlerTests _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockRoleRepository = Substitute.For(); - _getRolePermissionsQueryFixture = new GetRolePermissionsQueryFixture(); _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); @@ -63,7 +62,7 @@ public class GetRolePermissionsQueryHandlerTests public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange - GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.CreateQuery(); + GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(false); @@ -80,7 +79,7 @@ public class GetRolePermissionsQueryHandlerTests public async Task HandleAsync_WhenGetRoleByIdFails_ShouldReturnError() { // Arrange - GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.CreateQuery(); + GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get role"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -100,7 +99,7 @@ public class GetRolePermissionsQueryHandlerTests public async Task HandleAsync_WhenRoleNotFound_ShouldReturnRoleNotFoundError() { // Arrange - GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.CreateQuery(); + GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); @@ -119,7 +118,7 @@ public class GetRolePermissionsQueryHandlerTests public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnRolePermissions() { // Arrange - GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.CreateQuery(); + GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create(); RoleEntity role = new() { Id = query.RoleId, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs index 041f3e86..8a3595e0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs @@ -16,15 +16,7 @@ namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.Ge [ExcludeFromCodeCoverage] public class GetRolePermissionsQueryValidatorTests { - private readonly GetRolePermissionsQueryValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public GetRolePermissionsQueryValidatorTests() - { - _validator = new GetRolePermissionsQueryValidator(); - } + private readonly GetRolePermissionsQueryValidator _validator = new(); [Fact] public void Validate_WhenRoleIdIsEmpty_ShouldHaveValidationError() diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs index 8333ce72..4d3fe590 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs @@ -6,7 +6,7 @@ using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; -using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.GetRoles.Fixtures; +using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Queries.GetRoles; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -30,7 +30,7 @@ public class GetRolesQueryHandlerTests private readonly ICurrentUserService _mockCurrentUserService; private readonly IRoleRepository _mockRoleRepository; private readonly GetRolesQueryHandler _sut; - private readonly GetRolesQueryFixture _getRolesQueryFixture; + private readonly GetRolesQueryFixture _getRolesQueryFixture = new(); private readonly Guid _userId; /// @@ -42,7 +42,6 @@ public class GetRolesQueryHandlerTests _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockRoleRepository = Substitute.For(); - _getRolesQueryFixture = new GetRolesQueryFixture(); _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); @@ -58,7 +57,7 @@ public class GetRolesQueryHandlerTests public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange - GetRolesQuery query = _getRolesQueryFixture.CreateQuery(); + GetRolesQuery query = _getRolesQueryFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(false); @@ -75,7 +74,7 @@ public class GetRolesQueryHandlerTests public async Task HandleAsync_WhenGetRolesFails_ShouldReturnError() { // Arrange - GetRolesQuery query = _getRolesQueryFixture.CreateQuery(); + GetRolesQuery query = _getRolesQueryFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get roles"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -95,7 +94,7 @@ public class GetRolesQueryHandlerTests public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnRoles() { // Arrange - GetRolesQuery query = _getRolesQueryFixture.CreateQuery(); + GetRolesQuery query = _getRolesQueryFixture.Create(); IEnumerable roles = [ new RoleEntity { Id = Guid.NewGuid(), RoleName = "Admin" }, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryFixture.cs deleted file mode 100644 index 46439b3c..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Fixtures/DirectoryFixture.cs +++ /dev/null @@ -1,115 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class DirectoryFixture -{ - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public DirectoryFixture() - { - _faker = new Faker(); - } - - /// - /// Creates a random valid . - /// - /// Optional. The directory path. If not provided, a random path is generated. - /// Optional. The directory name. If not provided, a random name is generated. - /// Optional. The directory's creation date. If not provided, a random past date is generated. - /// Optional. The directory's modification date. If not provided, a recent date is generated. - /// Optional. The directory's status. If not provided, a random status is assigned. - /// Optional. A list of child items to be added to the directory. - /// A newly created Directory instance. - /// Thrown if the Directory creation fails. - public Directory CreateDirectory( - string? path = null, - string? name = null, - Optional? dateCreated = null, - Optional? dateModified = null, - FileSystemItemStatus? status = null, - List? childItems = null) - { - path ??= _faker.System.FilePath(); - name ??= _faker.System.FileName(); - dateCreated ??= Optional.Some(_faker.Date.Past()); - dateModified ??= Optional.Some(_faker.Date.Recent()); - status ??= _faker.PickRandom(); - - Result directoryResult = Directory.Create(path, name, dateCreated.Value, dateModified.Value, status.Value); - - if (directoryResult.IsFailure) - throw new InvalidOperationException("Failed to create Directory: " + string.Join(", ", directoryResult.Errors)); - Directory directory = directoryResult.Value; - - if (childItems != null) - foreach (FileSystemItem item in childItems) - directory.AddItem(item); - return directory; - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => CreateDirectory())]; - } - - /// - /// Creates a list of nested objects with a hierarchical structure. - /// - /// The number of top-level directories to create. Default is 3. - /// The maximum depth of the directory hierarchy. Default is 3. - /// The maximum number of child items (files or directories) per directory. Default is 3. - /// A list of objects with nested structures. - public List CreateManyNested(int count = 3, int maxDepth = 3, int maxChildrenPerDirectory = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => CreateNestedDirectory(1, maxDepth, maxChildrenPerDirectory))]; - } - - /// - /// Recursively creates a nested structure. - /// - /// The current depth in the directory hierarchy. - /// The maximum allowed depth for the directory hierarchy. - /// The maximum number of child items (files or directories) allowed per directory. - /// A object that may contain nested directories and files. - private Directory CreateNestedDirectory(int currentDepth, int maxDepth, int maxChildrenPerDirectory) - { - List childItems = []; - // ensure we create at least one child if we haven't reached max depth - if (currentDepth < maxDepth) - { - // force at least 1 child, up to maxChildrenPerDirectory - int childCount = _faker.Random.Int(1, maxChildrenPerDirectory); - for (int i = 0; i < childCount; i++) - { - Directory childDirectory = CreateNestedDirectory(currentDepth + 1, maxDepth, maxChildrenPerDirectory); - Result addResult = childDirectory.SetParent(childDirectory); - if (!addResult.IsFailure) - childItems.Add(childDirectory); - } - } - return CreateDirectory(childItems: childItems); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs index 87239c91..0efb2263 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs @@ -3,12 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Directories.Queries.GetDirectories; using Lumina.Contracts.Responses.FileSystemManagement.Directories; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using NSubstitute; using System; using System.Collections.Generic; @@ -29,7 +29,8 @@ public class GetDirectoriesQueryHandlerTests private readonly IFixture _fixture; private readonly IDirectoryService _mockDirectoryService; private readonly GetDirectoriesQueryHandler _sut; - private readonly DirectoryFixture _directoryFixture; + private readonly DirectoryFixture _directoryFixture = new(); + private readonly GetDirectoriesQueryFixture _getDirectoriesQueryFixture = new(); /// /// Initializes a new instance of the class. @@ -42,14 +43,13 @@ public class GetDirectoriesQueryHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); _sut = new GetDirectoriesQueryHandler(_mockDirectoryService, mockValidator); - _directoryFixture = new DirectoryFixture(); } [Fact] public async Task HandleAsync_WhenCalledWithValidQueryWithoutFilesIncluded_ShouldReturnSuccessResult() { // Arrange - GetDirectoriesQuery getDirectoriesQuery = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(false); + GetDirectoriesQuery getDirectoriesQuery = _getDirectoriesQueryFixture.Create(includeHiddenElements: false); IEnumerable directories = _directoryFixture.CreateMany(); @@ -83,7 +83,7 @@ public class GetDirectoriesQueryHandlerTests public async Task HandleAsync_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult() { // Arrange - GetDirectoriesQuery getDirectoriesQuery = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(true); + GetDirectoriesQuery getDirectoriesQuery = _getDirectoriesQueryFixture.Create(includeHiddenElements: true); IEnumerable directories = _directoryFixture.CreateMany(); @@ -117,7 +117,7 @@ public class GetDirectoriesQueryHandlerTests public async Task HandleAsync_WhenDirectoryServiceReturnsError_ShouldReturnFailureResult() { // Arrange - GetDirectoriesQuery query = _fixture.Create(); + GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create(); Error error = Error.Failure("DirectoryService.Error", "An error occurred"); _mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements) .Returns(error); @@ -135,7 +135,7 @@ public class GetDirectoriesQueryHandlerTests public async Task HandleAsync_WhenDirectoryServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() { // Arrange - GetDirectoriesQuery query = _fixture.Create(); + GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create(); Result> emptyList = Result.From(Enumerable.Empty()); _mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements) .Returns(emptyList); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs index 72e62536..055c3ef5 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Directories.Queries.GetDirectories; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; @@ -16,21 +16,14 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Que [ExcludeFromCodeCoverage] public class GetDirectoriesQueryValidatorTests { - private readonly GetDirectoriesQueryValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public GetDirectoriesQueryValidatorTests() - { - _validator = new GetDirectoriesQueryValidator(); - } + private readonly GetDirectoriesQueryValidator _validator = new(); + private readonly GetDirectoriesQueryFixture _getDirectoriesQueryFixture = new(); [Fact] public void Validate_WhenPathIsNull_ShouldHaveValidationError() { // Arrange - GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(); + GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create(); query = query with { Path = null! }; // Act @@ -44,7 +37,7 @@ public class GetDirectoriesQueryValidatorTests public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() { // Arrange - GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(); + GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create(); query = query with { Path = string.Empty }; // Act @@ -58,7 +51,7 @@ public class GetDirectoriesQueryValidatorTests public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() { // Arrange - GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(); + GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create(); query = query with { Path = " " }; // Act @@ -72,7 +65,7 @@ public class GetDirectoriesQueryValidatorTests public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() { // Arrange - GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(); + GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create(); query = query with { Path = "/valid/path" }; // Act @@ -86,7 +79,7 @@ public class GetDirectoriesQueryValidatorTests public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() { // Arrange - GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(); + GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create(); query = query with { IncludeHiddenElements = true }; // Act @@ -100,7 +93,7 @@ public class GetDirectoriesQueryValidatorTests public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() { // Arrange - GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(); + GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create(); query = query with { IncludeHiddenElements = false }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/Fixtures/GetDrivesQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/Fixtures/GetDrivesQueryFixture.cs deleted file mode 100644 index 51ced826..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/Fixtures/GetDrivesQueryFixture.cs +++ /dev/null @@ -1,58 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Drives.Queries.GetDrives.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class GetDrivesQueryFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a single with a nested structure. - /// - /// The current depth in the tree structure. Default is 0 (root level). - /// The maximum depth of the tree structure. Default is 2. - /// The maximum number of children for each node. Default is 3. - /// A with a nested structure. - public FileSystemTreeNodeResponse Create(int currentDepth = 0, int maxDepth = 2, int maxChildren = 3) - { - FileSystemTreeNodeResponse response = new() - { - Path = _faker.System.FilePath(), - Name = _faker.System.FileName(), - ItemType = FileSystemItemType.Directory, - IsExpanded = _faker.Random.Bool(), - ChildrenLoaded = true, - Children = [] - }; - if (currentDepth < maxDepth) - { - int childCount = _faker.Random.Int(1, maxChildren); - for (int i = 0; i < childCount; i++) - response.Children.Add(Create(currentDepth + 1, maxDepth, maxChildren)); - } - return response; - } - - /// - /// Creates a list of objects, each with a nested structure. - /// - /// The number of root-level nodes to create. Default is 2. - /// The maximum depth of the tree structure for each root node. Default is 2. - /// The maximum number of children for each node. Default is 3. - /// A list of objects with nested structures. - public List CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3) - { - return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs index dcde9de5..1acaa59b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Drives.Queries.GetDrives; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; @@ -24,16 +23,15 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Drives.Queries. [ExcludeFromCodeCoverage] public class GetDrivesQueryHandlerTests { - private readonly IFixture _fixture; private readonly IDriveService _mockDriveService; private readonly GetDrivesQueryHandler _sut; + private readonly GetDrivesQueryFixture _getDrivesQueryFixture = new(); /// /// Initializes a new instance of the class. /// public GetDrivesQueryHandlerTests() { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockDriveService = Substitute.For(); _sut = new GetDrivesQueryHandler(_mockDriveService); } @@ -42,7 +40,7 @@ public class GetDrivesQueryHandlerTests public async Task HandleAsync_WhenCalled_ShouldReturnSuccessResult() { // Arrange - GetDrivesQuery getDrivesQuery = _fixture.Create(); + GetDrivesQuery getDrivesQuery = _getDrivesQueryFixture.Create(); IEnumerable drives = [ @@ -84,7 +82,7 @@ public class GetDrivesQueryHandlerTests public async Task HandleAsync_WhenDriveServiceReturnsError_ShouldReturnFailureResult() { // Arrange - GetDrivesQuery query = _fixture.Create(); + GetDrivesQuery query = _getDrivesQueryFixture.Create(); Error error = Error.Failure("DriveService.Error", "An error occurred"); _mockDriveService.GetDrives() .Returns(error); @@ -102,7 +100,7 @@ public class GetDrivesQueryHandlerTests public async Task HandleAsync_WhenDriveServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() { // Arrange - GetDrivesQuery query = _fixture.Create(); + GetDrivesQuery query = _getDrivesQueryFixture.Create(); Result> emptyList = Result.From(Enumerable.Empty()); _mockDriveService.GetDrives() .Returns(emptyList); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/WindowsRootItemFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/WindowsRootItemFixture.cs deleted file mode 100644 index 7acc0bc8..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Fixtures/WindowsRootItemFixture.cs +++ /dev/null @@ -1,35 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.FileSystem.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class WindowsRootItemFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a random valid . - /// - /// The created . - public WindowsRootItem Create() - { - Result windowsRootItemResult = WindowsRootItem.Create( - _faker.System.FilePath(), - _faker.System.FileName(), - _faker.PickRandom() - ); - if (windowsRootItemResult.IsFailure) - throw new InvalidOperationException("Failed to create File: " + string.Join(", ", windowsRootItemResult.Errors)); - return windowsRootItemResult.Value; - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs index a0fa6b16..09c36028 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs @@ -2,9 +2,10 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using Lumina.Application.Fixtures.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -24,6 +25,7 @@ public class GetFileSystemQueryHandlerTests private readonly IPlatformContextManager _mockPlatformContextManager; private readonly IPlatformContext _mockPlatformContext; private readonly GetFileSystemQueryHandler _sut; + private readonly GetFileSystemQueryFixture _getFileSystemQueryFixture = new(); /// /// Initializes a new instance of the class. @@ -43,7 +45,7 @@ public class GetFileSystemQueryHandlerTests public async Task HandleAsync_WhenCalled_ShouldReturnCorrectFileSystemTypeResponse(PlatformType platformType) { // Arrange - GetFileSystemQuery query = _fixture.Create(); + GetFileSystemQuery query = _getFileSystemQueryFixture.Create(); _mockPlatformContext.Platform.Returns(platformType); // Act @@ -59,7 +61,7 @@ public class GetFileSystemQueryHandlerTests public async Task HandleAsync_WhenCalled_ShouldReturnValueTaskResult() { // Arrange - GetFileSystemQuery query = _fixture.Create(); + GetFileSystemQuery query = _getFileSystemQueryFixture.Create(); _mockPlatformContext.Platform.Returns(PlatformType.Unix); // Act @@ -76,8 +78,8 @@ public class GetFileSystemQueryHandlerTests public async Task HandleAsync_WhenCalled_ShouldNotDependOnQueryContent() { // Arrange - GetFileSystemQuery query1 = _fixture.Create(); - GetFileSystemQuery query2 = _fixture.Create(); + GetFileSystemQuery query1 = _getFileSystemQueryFixture.Create(); + GetFileSystemQuery query2 = _getFileSystemQueryFixture.Create(); _mockPlatformContext.Platform.Returns(PlatformType.Windows); // Act @@ -93,7 +95,7 @@ public class GetFileSystemQueryHandlerTests public async Task HandleAsync_WhenCalled_ShouldIgnoreCancellationToken() { // Arrange - GetFileSystemQuery query = _fixture.Create(); + GetFileSystemQuery query = _getFileSystemQueryFixture.Create(); _mockPlatformContext.Platform.Returns(PlatformType.Unix); CancellationToken cancellationToken = new(true); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs index 95e95d31..0ffcb560 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs @@ -3,12 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Files.Queries.GetFiles; using Lumina.Contracts.Responses.FileSystemManagement.Files; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using NSubstitute; using System; using System.Collections.Generic; @@ -29,7 +29,8 @@ public class GetFilesQueryHandlerTests private readonly IFixture _fixture; private readonly IFileService _mockFileService; private readonly GetFilesQueryHandler _sut; - private readonly FileFixture _fileFixture; + private readonly FileFixture _fileFixture = new(); + private readonly GetFilesQueryFixture _getFilesQueryFixture = new(); /// /// Initializes a new instance of the class. @@ -42,14 +43,13 @@ public class GetFilesQueryHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); _sut = new GetFilesQueryHandler(_mockFileService, mockValidator); - _fileFixture = new FileFixture(); } [Fact] public async Task HandleAsync_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult() { // Arrange - GetFilesQuery getFilesQuery = GetFilesQueryFixture.CreateGetFilesQuery(false); + GetFilesQuery getFilesQuery = _getFilesQueryFixture.Create(includeHiddenElements: false); IEnumerable files = _fileFixture.CreateMany(); @@ -83,7 +83,7 @@ public class GetFilesQueryHandlerTests public async Task HandleAsync_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult() { // Arrange - GetFilesQuery getFilesQuery = GetFilesQueryFixture.CreateGetFilesQuery(true); + GetFilesQuery getFilesQuery = _getFilesQueryFixture.Create(includeHiddenElements: true); IEnumerable files = _fileFixture.CreateMany(); @@ -117,7 +117,7 @@ public class GetFilesQueryHandlerTests public async Task HandleAsync_WhenFileServiceReturnsError_ShouldReturnFailureResult() { // Arrange - GetFilesQuery query = _fixture.Create(); + GetFilesQuery query = _getFilesQueryFixture.Create(); Error error = Error.Failure("FileService.Error", "An error occurred"); _mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements) .Returns(error); @@ -135,7 +135,7 @@ public class GetFilesQueryHandlerTests public async Task HandleAsync_WhenFileServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() { // Arrange - GetFilesQuery query = _fixture.Create(); + GetFilesQuery query = _getFilesQueryFixture.Create(); Result> emptyList = Result.From(Enumerable.Empty()); _mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements) .Returns(emptyList); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs index 7b0bcb57..4cd5eeb6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Files.Queries.GetFiles; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; @@ -16,21 +16,14 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.G [ExcludeFromCodeCoverage] public class GetFilesQueryValidatorTests { - private readonly GetFilesQueryValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public GetFilesQueryValidatorTests() - { - _validator = new GetFilesQueryValidator(); - } + private readonly GetFilesQueryValidator _validator = new(); + private readonly GetFilesQueryFixture _getFilesQueryFixture = new(); [Fact] public void Validate_WhenPathIsNull_ShouldHaveValidationError() { // Arrange - GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery(); + GetFilesQuery query = _getFilesQueryFixture.Create(); query = query with { Path = null! }; // Act @@ -44,7 +37,7 @@ public class GetFilesQueryValidatorTests public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() { // Arrange - GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery(); + GetFilesQuery query = _getFilesQueryFixture.Create(); query = query with { Path = string.Empty }; // Act @@ -58,7 +51,7 @@ public class GetFilesQueryValidatorTests public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() { // Arrange - GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery(); + GetFilesQuery query = _getFilesQueryFixture.Create(); query = query with { Path = " " }; // Act @@ -72,7 +65,7 @@ public class GetFilesQueryValidatorTests public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() { // Arrange - GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery(); + GetFilesQuery query = _getFilesQueryFixture.Create(); query = query with { Path = "/valid/path" }; // Act @@ -86,7 +79,7 @@ public class GetFilesQueryValidatorTests public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() { // Arrange - GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery(); + GetFilesQuery query = _getFilesQueryFixture.Create(); query = query with { IncludeHiddenElements = true }; // Act @@ -100,7 +93,7 @@ public class GetFilesQueryValidatorTests public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() { // Arrange - GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery(); + GetFilesQuery query = _getFilesQueryFixture.Create(); query = query with { IncludeHiddenElements = false }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs index 312c61cf..8d0809db 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs @@ -3,12 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Files.Queries.GetTreeFiles; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using NSubstitute; using System.Collections.Generic; @@ -29,7 +29,8 @@ public class GetTreeFilesQueryHandlerTests private readonly IFixture _fixture; private readonly IFileService _mockFileService; private readonly GetTreeFilesQueryHandler _sut; - private readonly FileFixture _fileFixture; + private readonly FileFixture _fileFixture = new(); + private readonly GetTreeFilesQueryFixture _getTreeFilesQueryFixture = new(); /// /// Initializes a new instance of the class. @@ -42,14 +43,13 @@ public class GetTreeFilesQueryHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); _sut = new GetTreeFilesQueryHandler(_mockFileService, mockValidator); - _fileFixture = new FileFixture(); } [Fact] public async Task HandleAsync_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult() { // Arrange - GetTreeFilesQuery getFilesQuery = GetTreeFilesQueryFixture.CreateGetFilesQuery(false); + GetTreeFilesQuery getFilesQuery = _getTreeFilesQueryFixture.Create(includeHiddenElements: false); IEnumerable files = _fileFixture.CreateMany(); @@ -84,7 +84,7 @@ public class GetTreeFilesQueryHandlerTests public async Task HandleAsync_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult() { // Arrange - GetTreeFilesQuery getFilesQuery = GetTreeFilesQueryFixture.CreateGetFilesQuery(true); + GetTreeFilesQuery getFilesQuery = _getTreeFilesQueryFixture.Create(includeHiddenElements: true); IEnumerable files = _fileFixture.CreateMany(); @@ -119,7 +119,7 @@ public class GetTreeFilesQueryHandlerTests public async Task HandleAsync_WhenFileServiceReturnsError_ShouldReturnFailureResult() { // Arrange - GetTreeFilesQuery query = _fixture.Create(); + GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create(); Error error = Error.Failure("FileService.Error", "An error occurred"); _mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements) .Returns(error); @@ -137,7 +137,7 @@ public class GetTreeFilesQueryHandlerTests public async Task HandleAsync_WhenFileServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() { // Arrange - GetTreeFilesQuery query = _fixture.Create(); + GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create(); Result> emptyList = Result.From(Enumerable.Empty()); _mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements) .Returns(emptyList); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs index e46661f3..af7e9e65 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Files.Queries.GetTreeFiles; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; @@ -16,21 +16,14 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.G [ExcludeFromCodeCoverage] public class GetTreeFilesQueryValidatorTests { - private readonly GetTreeFilesQueryValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public GetTreeFilesQueryValidatorTests() - { - _validator = new GetTreeFilesQueryValidator(); - } + private readonly GetTreeFilesQueryValidator _validator = new(); + private readonly GetTreeFilesQueryFixture _getTreeFilesQueryFixture = new(); [Fact] public void Validate_WhenPathIsNull_ShouldHaveValidationError() { // Arrange - GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery(); + GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create(); query = query with { Path = null! }; // Act @@ -44,7 +37,7 @@ public class GetTreeFilesQueryValidatorTests public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() { // Arrange - GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery(); + GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create(); query = query with { Path = string.Empty }; // Act @@ -58,7 +51,7 @@ public class GetTreeFilesQueryValidatorTests public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() { // Arrange - GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery(); + GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create(); query = query with { Path = " " }; // Act @@ -72,7 +65,7 @@ public class GetTreeFilesQueryValidatorTests public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() { // Arrange - GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery(); + GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create(); query = query with { Path = "/valid/path" }; // Act @@ -86,7 +79,7 @@ public class GetTreeFilesQueryValidatorTests public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() { // Arrange - GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery(); + GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create(); query = query with { IncludeHiddenElements = true }; // Act @@ -100,7 +93,7 @@ public class GetTreeFilesQueryValidatorTests public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() { // Arrange - GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery(); + GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create(); query = query with { IncludeHiddenElements = false }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/Fixtures/CombinePathCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/Fixtures/CombinePathCommandFixture.cs deleted file mode 100644 index 99869197..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/Fixtures/CombinePathCommandFixture.cs +++ /dev/null @@ -1,29 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class CombinePathCommandFixture -{ - /// - /// Creates a random valid command to combine paths. - /// - /// The created command. - public static CombinePathCommand CreateCombinePathCommand() - { - return new Faker() - .CustomInstantiator(f => new CombinePathCommand( - default!, - default! - )) - .RuleFor(x => x.OriginalPath, f => f.System.FilePath()) - .RuleFor(x => x.NewPath, f => f.System.FilePath()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentFixture.cs deleted file mode 100644 index 2f0932ff..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Fixtures/PathSegmentFixture.cs +++ /dev/null @@ -1,58 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class PathSegmentFixture -{ - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public PathSegmentFixture() - { - _faker = new Faker(); - } - - /// - /// Creates a random valid . - /// - /// The created . - public PathSegment CreatePathSegment( - string? name = null, - bool? isDirectory = null, - bool? isDrive = null) - { - name ??= _faker.System.FileName(); - isDirectory ??= true; - isDrive ??= false; - - Result pathResult = PathSegment.Create(name, isDirectory.Value, isDrive.Value); - - if (pathResult.IsFailure) - throw new InvalidOperationException("Failed to create PathSegment: " + string.Join(", ", pathResult.Errors)); - return pathResult.Value; - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return Enumerable.Range(0, count).Select(_ => CreatePathSegment()).ToList(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/Fixtures/GetPathParentQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/Fixtures/GetPathParentQueryFixture.cs deleted file mode 100644 index 21529dff..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/Fixtures/GetPathParentQueryFixture.cs +++ /dev/null @@ -1,27 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class GetPathParentQueryFixture -{ - /// - /// Creates a random valid query to check if paths exist. - /// - /// The created query. - public static GetPathParentQuery CreateGetPathParentQuery() - { - return new Faker() - .CustomInstantiator(f => new GetPathParentQuery( - default! - )) - .RuleFor(x => x.Path, f => f.System.FilePath()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/Fixtures/GetPathRootQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/Fixtures/GetPathRootQueryFixture.cs deleted file mode 100644 index 6f19dc55..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/Fixtures/GetPathRootQueryFixture.cs +++ /dev/null @@ -1,27 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class GetPathRootQueryFixture -{ - /// - /// Creates a random valid query to check if paths exist. - /// - /// The created query. - public static GetPathRootQuery CreateGetPathRootQuery() - { - return new Faker() - .CustomInstantiator(f => new GetPathRootQuery( - default! - )) - .RuleFor(x => x.Path, f => f.System.FilePath()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/Fixtures/ValidatePathQueryFixure.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/Fixtures/ValidatePathQueryFixure.cs deleted file mode 100644 index 82667104..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/Fixtures/ValidatePathQueryFixure.cs +++ /dev/null @@ -1,27 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class ValidatePathQueryFixure -{ - /// - /// Creates a random valid query to check if paths exist. - /// - /// The created query. - public static ValidatePathQuery CreateValidatePathQuery() - { - return new Faker() - .CustomInstantiator(f => new ValidatePathQuery( - default! - )) - .RuleFor(x => x.Path, f => f.System.FilePath()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandlerTests.cs similarity index 89% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandlerTests.cs index 32a87b9c..0c79b1a6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandHandlerTests.cs @@ -3,7 +3,7 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Commands.CombinePath; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; @@ -13,7 +13,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Commands.CombinePath; /// /// Contains unit tests for the class. @@ -24,6 +24,7 @@ public class CombinePathCommandHandlerTests private readonly IFixture _fixture; private readonly IPathService _mockPathService; private readonly CombinePathCommandHandler _sut; + private readonly CombinePathCommandFixture _combinePathCommandFixture = new(); /// /// Initializes a new instance of the class. @@ -42,7 +43,7 @@ public class CombinePathCommandHandlerTests public async Task HandleAsync_WhenCalledWithValidCommand_ShouldReturnSuccessResult() { // Arrange - CombinePathCommand combinePathCommand = CombinePathCommandFixture.CreateCombinePathCommand(); + CombinePathCommand combinePathCommand = _combinePathCommandFixture.Create(); string combinedPath = System.IO.Path.Combine(combinePathCommand.OriginalPath!, combinePathCommand.NewPath!); _mockPathService.CombinePath(combinePathCommand.OriginalPath!, combinePathCommand.NewPath!) @@ -62,7 +63,7 @@ public class CombinePathCommandHandlerTests public async Task HandleAsync_WhenPathServiceReturnsError_ShouldReturnFailureResult() { // Arrange - CombinePathCommand command = _fixture.Create(); + CombinePathCommand command = _combinePathCommandFixture.Create(); Error error = Error.Failure("PathService.Error", "An error occurred"); _mockPathService.CombinePath(command.OriginalPath!, command.NewPath!) .Returns(error); @@ -80,7 +81,7 @@ public class CombinePathCommandHandlerTests public async Task HandleAsync_WhenPathServiceReturnsEmptyString_ShouldReturnSuccessResultWithEmptyPath() { // Arrange - CombinePathCommand command = _fixture.Create(); + CombinePathCommand command = _combinePathCommandFixture.Create(); _mockPathService.CombinePath(command.OriginalPath!, command.NewPath!) .Returns(Result.From(string.Empty)); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandValidatorTests.cs similarity index 75% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandValidatorTests.cs index 5d120a30..0e47f421 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Commands/CombinePath/CombinePathCommandValidatorTests.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Commands.CombinePath; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Commands.CombinePath; /// /// Contains unit tests for the class. @@ -16,21 +16,14 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.C [ExcludeFromCodeCoverage] public class CombinePathCommandValidatorTests { - private readonly CombinePathCommandValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public CombinePathCommandValidatorTests() - { - _validator = new CombinePathCommandValidator(); - } + private readonly CombinePathCommandValidator _validator = new(); + private readonly CombinePathCommandFixture _combinePathCommandFixture = new(); [Fact] public void Validate_WhenOriginalPathIsNull_ShouldHaveValidationError() { // Arrange - CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand(); + CombinePathCommand command = _combinePathCommandFixture.Create(); command = command with { OriginalPath = null! }; // Act @@ -44,7 +37,7 @@ public class CombinePathCommandValidatorTests public void Validate_WhenOriginalPathIsEmpty_ShouldHaveValidationError() { // Arrange - CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand(); + CombinePathCommand command = _combinePathCommandFixture.Create(); command = command with { OriginalPath = string.Empty }; // Act @@ -58,7 +51,7 @@ public class CombinePathCommandValidatorTests public void Validate_WhenOriginalPathIsWhitespace_ShouldHaveValidationError() { // Arrange - CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand(); + CombinePathCommand command = _combinePathCommandFixture.Create(); command = command with { OriginalPath = " " }; // Act @@ -72,7 +65,7 @@ public class CombinePathCommandValidatorTests public void Validate_WhenNewPathIsNull_ShouldHaveValidationError() { // Arrange - CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand(); + CombinePathCommand command = _combinePathCommandFixture.Create(); command = command with { NewPath = null! }; // Act @@ -86,7 +79,7 @@ public class CombinePathCommandValidatorTests public void Validate_WhenNewPathIsEmpty_ShouldHaveValidationError() { // Arrange - CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand(); + CombinePathCommand command = _combinePathCommandFixture.Create(); command = command with { NewPath = string.Empty }; // Act @@ -100,7 +93,7 @@ public class CombinePathCommandValidatorTests public void Validate_WhenNewPathIsWhitespace_ShouldHaveValidationError() { // Arrange - CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand(); + CombinePathCommand command = _combinePathCommandFixture.Create(); command = command with { NewPath = " " }; // Act @@ -114,7 +107,7 @@ public class CombinePathCommandValidatorTests public void Validate_WhenBothPathsAreValid_ShouldNotHaveValidationError() { // Arrange - CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand(); + CombinePathCommand command = _combinePathCommandFixture.Create(); command = command with { OriginalPath = "/valid/path", NewPath = "new/segment" }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandlerTests.cs similarity index 86% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandlerTests.cs index ea388a71..ec217456 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandHandlerTests.cs @@ -3,12 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Commands.SplitPath; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using NSubstitute; using System; using System.Collections.Generic; @@ -18,7 +18,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Commands.SplitPath; /// /// Contains unit tests for the class. @@ -29,7 +29,8 @@ public class SplitPathCommandHandlerTests private readonly IFixture _fixture; private readonly IPathService _mockPathService; private readonly SplitPathCommandHandler _sut; - private readonly PathSegmentFixture _pathSegmentFixture; + private readonly PathSegmentFixture _pathSegmentFixture = new(); + private readonly SplitPathCommandFixture _splitPathCommandFixture = new(); /// /// Initializes a new instance of the class. @@ -42,14 +43,13 @@ public class SplitPathCommandHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); _sut = new SplitPathCommandHandler(_mockPathService, mockValidator); - _pathSegmentFixture = new PathSegmentFixture(); } [Fact] public async Task HandleAsync_WhenCalledWithValidCommand_ShouldReturnSuccessResult() { // Arrange - SplitPathCommand splitPathCommand = SplitPathCommandFixture.CreateSplitPathCommand(); + SplitPathCommand splitPathCommand = _splitPathCommandFixture.Create(); IEnumerable pathSegments = _pathSegmentFixture.CreateMany(); @@ -76,7 +76,7 @@ public class SplitPathCommandHandlerTests public async Task HandleAsync_WhenPathServiceReturnsError_ShouldReturnFailureResult() { // Arrange - SplitPathCommand command = _fixture.Create(); + SplitPathCommand command = _splitPathCommandFixture.Create(); Error error = Error.Failure("PathService.Error", "An error occurred"); _mockPathService.ParsePath(command.Path!) .Returns(error); @@ -94,7 +94,7 @@ public class SplitPathCommandHandlerTests public async Task HandleAsync_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() { // Arrange - SplitPathCommand command = _fixture.Create(); + SplitPathCommand command = _splitPathCommandFixture.Create(); Result> emptyList = Result.From(Enumerable.Empty()); _mockPathService.ParsePath(command.Path!) .Returns(emptyList); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandValidatorTests.cs similarity index 73% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandValidatorTests.cs index ef65ce42..52cba0fe 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Commands/SplitPath/SplitPathCommandValidatorTests.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Commands.SplitPath; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Commands.SplitPath; /// /// Contains unit tests for the class. @@ -16,21 +16,14 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.S [ExcludeFromCodeCoverage] public class SplitPathCommandValidatorTests { - private readonly SplitPathCommandValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public SplitPathCommandValidatorTests() - { - _validator = new SplitPathCommandValidator(); - } + private readonly SplitPathCommandValidator _validator = new(); + private readonly SplitPathCommandFixture _splitPathCommandFixture = new(); [Fact] public void Validate_WhenPathIsNull_ShouldHaveValidationError() { // Arrange - SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand(); + SplitPathCommand command = _splitPathCommandFixture.Create(); command = command with { Path = null! }; // Act @@ -44,7 +37,7 @@ public class SplitPathCommandValidatorTests public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() { // Arrange - SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand(); + SplitPathCommand command = _splitPathCommandFixture.Create(); command = command with { Path = string.Empty }; // Act @@ -58,7 +51,7 @@ public class SplitPathCommandValidatorTests public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() { // Arrange - SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand(); + SplitPathCommand command = _splitPathCommandFixture.Create(); command = command with { Path = " " }; // Act @@ -72,7 +65,7 @@ public class SplitPathCommandValidatorTests public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() { // Arrange - SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand(); + SplitPathCommand command = _splitPathCommandFixture.Create(); command = command with { Path = "/valid/path" }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs similarity index 87% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs index e2490c47..5c46c28a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.CheckPathExists; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; @@ -11,7 +11,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.CheckPathExists; /// /// Contains unit tests for the class. @@ -21,6 +21,7 @@ public class CheckPathExistsQueryHandlerTests { private readonly IPathService _mockPathService; private readonly CheckPathExistsQueryHandler _sut; + private readonly CheckPathExistsQueryFixture _checkPathExistsQueryFixture = new(); /// /// Initializes a new instance of the class. @@ -38,7 +39,7 @@ public class CheckPathExistsQueryHandlerTests public async Task HandleAsync_WhenPathExistsAndIsNotHidden_ShouldReturnTrueResponse() { // Arrange - CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); + CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(); _mockPathService.Exists(query.Path!).Returns(true); // Act @@ -54,7 +55,7 @@ public class CheckPathExistsQueryHandlerTests public async Task HandleAsync_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsTrue_ShouldReturnTrueResponse() { // Arrange - CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(true); + CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(includeHiddenElements: true); _mockPathService.Exists(query.Path!).Returns(true); // Act @@ -70,7 +71,7 @@ public class CheckPathExistsQueryHandlerTests public async Task HandleAsync_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsFalse_ShouldReturnFalseResponse() { // Arrange - CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(false); + CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(includeHiddenElements: false); _mockPathService.Exists(query.Path!, false).Returns(false); // Act @@ -86,7 +87,7 @@ public class CheckPathExistsQueryHandlerTests public async Task HandleAsync_WhenPathDoesNotExist_ShouldReturnFalseResponse() { // Arrange - CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); + CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(); _mockPathService.Exists(query.Path!).Returns(false); // Act @@ -118,7 +119,7 @@ public class CheckPathExistsQueryHandlerTests public async Task HandleAsync_WhenCancellationRequested_ShouldStillCompleteOperation() { // Arrange - CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); + CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(); _mockPathService.Exists(query.Path!).Returns(true); CancellationToken cancellationToken = new(true); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs similarity index 71% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs index c523476a..8bc17a58 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.CheckPathExists; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.CheckPathExists; /// /// Contains unit tests for the class. @@ -16,21 +16,14 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.Ch [ExcludeFromCodeCoverage] public class CheckPathExistsQueryValidatorTests { - private readonly CheckPathExistsQueryValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public CheckPathExistsQueryValidatorTests() - { - _validator = new CheckPathExistsQueryValidator(); - } + private readonly CheckPathExistsQueryValidator _validator = new(); + private readonly CheckPathExistsQueryFixture _checkPathExistsQueryFixture = new(); [Fact] public void Validate_WhenPathIsNull_ShouldHaveValidationError() { // Arrange - CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); + CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(); query = query with { Path = null! }; // Act @@ -44,7 +37,7 @@ public class CheckPathExistsQueryValidatorTests public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() { // Arrange - CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); + CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(); query = query with { Path = string.Empty }; // Act @@ -58,7 +51,7 @@ public class CheckPathExistsQueryValidatorTests public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() { // Arrange - CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); + CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(); query = query with { Path = " " }; // Act @@ -72,7 +65,7 @@ public class CheckPathExistsQueryValidatorTests public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() { // Arrange - CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); + CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(); query = query with { Path = "/valid/path" }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs similarity index 86% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs index 96f20b34..1089192a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs @@ -3,12 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent.Fixtures; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.GetPathParent; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -17,7 +17,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.GetPathParent; /// /// Contains unit tests for the class. @@ -28,7 +28,8 @@ public class GetPathParentQueryHandlerTests private readonly IFixture _fixture; private readonly IPathService _mockPathService; private readonly GetPathParentQueryHandler _sut; - private readonly PathSegmentFixture _pathSegmentFixture; + private readonly PathSegmentFixture _pathSegmentFixture = new(); + private readonly GetPathParentQueryFixture _getPathParentQueryFixture = new(); public GetPathParentQueryHandlerTests() { @@ -38,14 +39,13 @@ public class GetPathParentQueryHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); _sut = new GetPathParentQueryHandler(_mockPathService, mockValidator); - _pathSegmentFixture = new PathSegmentFixture(); } [Fact] public async Task HandleAsync_WhenCalledWithValidQuery_ShouldReturnSuccessResult() { // Arrange - GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery(); + GetPathParentQuery query = _getPathParentQueryFixture.Create(); IEnumerable pathSegments = _pathSegmentFixture.CreateMany(); @@ -69,7 +69,7 @@ public class GetPathParentQueryHandlerTests public async Task HandleAsync_WhenPathServiceReturnsError_ShouldReturnFailureResult() { // Arrange - GetPathParentQuery query = _fixture.Create(); + GetPathParentQuery query = _getPathParentQueryFixture.Create(); Error error = Error.Failure("PathService.Error", "An error occurred"); _mockPathService.GoUpOneLevel(query.Path!) .Returns(error); @@ -87,7 +87,7 @@ public class GetPathParentQueryHandlerTests public async Task HandleAsync_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() { // Arrange - GetPathParentQuery query = _fixture.Create(); + GetPathParentQuery query = _getPathParentQueryFixture.Create(); Result> emptyList = Result.From(Enumerable.Empty()); _mockPathService.GoUpOneLevel(query.Path!) .Returns(emptyList); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs similarity index 72% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs index bc4959ea..a4db12ae 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.GetPathParent; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent.Fixtures; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.GetPathParent; /// /// Contains unit tests for the class. @@ -16,21 +16,14 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.Ge [ExcludeFromCodeCoverage] public class GetPathParentQueryValidatorTests { - private readonly GetPathParentQueryValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public GetPathParentQueryValidatorTests() - { - _validator = new GetPathParentQueryValidator(); - } + private readonly GetPathParentQueryValidator _validator = new(); + private readonly GetPathParentQueryFixture _getPathParentQueryFixture = new(); [Fact] public void Validate_WhenPathIsNull_ShouldHaveValidationError() { // Arrange - GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery(); + GetPathParentQuery query = _getPathParentQueryFixture.Create(); query = query with { Path = null! }; // Act @@ -44,7 +37,7 @@ public class GetPathParentQueryValidatorTests public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() { // Arrange - GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery(); + GetPathParentQuery query = _getPathParentQueryFixture.Create(); query = query with { Path = string.Empty }; // Act @@ -58,7 +51,7 @@ public class GetPathParentQueryValidatorTests public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() { // Arrange - GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery(); + GetPathParentQuery query = _getPathParentQueryFixture.Create(); query = query with { Path = " " }; // Act @@ -72,7 +65,7 @@ public class GetPathParentQueryValidatorTests public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() { // Arrange - GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery(); + GetPathParentQuery query = _getPathParentQueryFixture.Create(); query = query with { Path = "/valid/path" }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs similarity index 82% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs index b9748e7e..a1936c62 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs @@ -1,19 +1,19 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot.Fixtures; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.GetPathRoot; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.GetPathRoot; /// /// Contains unit tests for the class. @@ -23,7 +23,8 @@ public class GetPathRootQueryHandlerTests { private readonly IPathService _mockPathService; private readonly GetPathRootQueryHandler _sut; - private readonly PathSegmentFixture _pathSegmentFixture; + private readonly PathSegmentFixture _pathSegmentFixture = new(); + private readonly GetPathRootQueryFixture _getPathRootQueryFixture = new(); /// /// Initializes a new instance of the class. @@ -35,15 +36,14 @@ public class GetPathRootQueryHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); _sut = new GetPathRootQueryHandler(_mockPathService, mockValidator); - _pathSegmentFixture = new PathSegmentFixture(); } [Fact] public async Task HandleAsync_WhenCalledWithValidQuery_ShouldReturnSuccessResult() { // Arrange - GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); - PathSegment pathSegment = _pathSegmentFixture.CreatePathSegment(isDrive: true); + GetPathRootQuery query = _getPathRootQueryFixture.Create(); + PathSegment pathSegment = _pathSegmentFixture.Create(isDrive: true); _mockPathService.GetPathRoot(query.Path!) .Returns(Result.From(pathSegment)); @@ -62,7 +62,7 @@ public class GetPathRootQueryHandlerTests public async Task HandleAsync_WhenPathServiceReturnsError_ShouldReturnFailureResult() { // Arrange - GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); + GetPathRootQuery query = _getPathRootQueryFixture.Create(); Error error = Error.Failure("PathService.Error", "An error occurred"); _mockPathService.GetPathRoot(query.Path!) .Returns(error); @@ -80,8 +80,8 @@ public class GetPathRootQueryHandlerTests public async Task HandleAsync_WhenPathServiceReturnsRootPathSegment_ShouldReturnRootSuccessResult() { // Arrange - GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); - PathSegment rootPathSegment = _pathSegmentFixture.CreatePathSegment(name: "/", isDirectory: true, isDrive: true); + GetPathRootQuery query = _getPathRootQueryFixture.Create(); + PathSegment rootPathSegment = _pathSegmentFixture.Create(name: "/", isDirectory: true, isDrive: true); _mockPathService.GetPathRoot(query.Path!) .Returns(Result.From(rootPathSegment)); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs similarity index 73% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs index 8ba380ed..c484b9aa 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.GetPathRoot; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot.Fixtures; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.GetPathRoot; /// /// Contains unit tests for the class. @@ -16,21 +16,14 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.Ge [ExcludeFromCodeCoverage] public class GetPathRootQueryValidatorTests { - private readonly GetPathRootQueryValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public GetPathRootQueryValidatorTests() - { - _validator = new GetPathRootQueryValidator(); - } + private readonly GetPathRootQueryValidator _validator = new(); + private readonly GetPathRootQueryFixture _getPathRootQueryFixture = new(); [Fact] public void Validate_WhenPathIsNull_ShouldHaveValidationError() { // Arrange - GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); + GetPathRootQuery query = _getPathRootQueryFixture.Create(); query = query with { Path = null! }; // Act @@ -44,7 +37,7 @@ public class GetPathRootQueryValidatorTests public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() { // Arrange - GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); + GetPathRootQuery query = _getPathRootQueryFixture.Create(); query = query with { Path = string.Empty }; // Act @@ -58,7 +51,7 @@ public class GetPathRootQueryValidatorTests public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() { // Arrange - GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); + GetPathRootQuery query = _getPathRootQueryFixture.Create(); query = query with { Path = " " }; // Act @@ -72,7 +65,7 @@ public class GetPathRootQueryValidatorTests public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() { // Arrange - GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); + GetPathRootQuery query = _getPathRootQueryFixture.Create(); query = query with { Path = "/valid/path" }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs similarity index 99% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs index e7cfaf36..f79ad5c2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs @@ -9,7 +9,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathSeparator; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.GetPathSeparator; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs similarity index 91% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs index 86f705b0..08138c98 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.ValidatePath; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -12,7 +12,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.ValidatePath; /// /// Contains unit tests for the class. @@ -23,6 +23,7 @@ public class ValidatePathQueryHandlerTests private readonly IPathService _mockPathService; private readonly IValidator _mockValidator; private readonly ValidatePathQueryHandler _sut; + private readonly ValidatePathQueryFixture _validatePathQueryFixture = new(); /// /// Initializes a new instance of the class. @@ -40,7 +41,7 @@ public class ValidatePathQueryHandlerTests public async Task HandleAsync_WhenCalledWithValidPath_ShouldReturnTrueResponse() { // Arrange - ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); + ValidatePathQuery query = _validatePathQueryFixture.Create(); _mockPathService.IsValidPath(query.Path!).Returns(true); // Act @@ -56,7 +57,7 @@ public class ValidatePathQueryHandlerTests public async Task HandleAsync_WhenCalledWithInvalidPath_ShouldReturnFalseResponse() { // Arrange - ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); + ValidatePathQuery query = _validatePathQueryFixture.Create(); _mockPathService.IsValidPath(query.Path!).Returns(false); // Act @@ -104,7 +105,7 @@ public class ValidatePathQueryHandlerTests public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnValidationErrorsWithoutCallingPathService() { // Arrange - ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); + ValidatePathQuery query = _validatePathQueryFixture.Create(); _mockValidator.Validate(query) .Returns([Errors.FileSystemManagement.PathCannotBeEmpty]); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs similarity index 73% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs index d9a2e01a..3794d70b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.ValidatePath; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath; +namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.ValidatePath; /// /// Contains unit tests for the class. @@ -16,21 +16,14 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.Va [ExcludeFromCodeCoverage] public class ValidatePathQueryValidatorTests { - private readonly ValidatePathQueryValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public ValidatePathQueryValidatorTests() - { - _validator = new ValidatePathQueryValidator(); - } + private readonly ValidatePathQueryValidator _validator = new(); + private readonly ValidatePathQueryFixture _validatePathQueryFixture = new(); [Fact] public void Validate_WhenPathIsNull_ShouldHaveValidationError() { // Arrange - ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); + ValidatePathQuery query = _validatePathQueryFixture.Create(); query = query with { Path = null! }; // Act @@ -44,7 +37,7 @@ public class ValidatePathQueryValidatorTests public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() { // Arrange - ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); + ValidatePathQuery query = _validatePathQueryFixture.Create(); query = query with { Path = string.Empty }; // Act @@ -58,7 +51,7 @@ public class ValidatePathQueryValidatorTests public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() { // Arrange - ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); + ValidatePathQuery query = _validatePathQueryFixture.Create(); query = query with { Path = " " }; // Act @@ -72,7 +65,7 @@ public class ValidatePathQueryValidatorTests public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() { // Arrange - ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); + ValidatePathQuery query = _validatePathQueryFixture.Create(); query = query with { Path = "/valid/path" }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Fixtures/ThumbnailResponseFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Fixtures/ThumbnailResponseFixture.cs deleted file mode 100644 index 79753e43..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Fixtures/ThumbnailResponseFixture.cs +++ /dev/null @@ -1,30 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; -using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class ThumbnailResponseFixture -{ - /// - /// Creates a random valid query to get a thumbnail. - /// - /// The created query. - public static ThumbnailResponse CreateThumbnailResponse() - { - return new Faker() - .CustomInstantiator(f => new ThumbnailResponse( - default, - default! - )) - .RuleFor(x => x.Type, f => f.PickRandom()) - .RuleFor(x => x.Bytes, f => f.Random.Bytes(20)); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/Fixtures/GetThumbnailQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/Fixtures/GetThumbnailQueryFixture.cs deleted file mode 100644 index 3481ddcb..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/Fixtures/GetThumbnailQueryFixture.cs +++ /dev/null @@ -1,29 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class GetThumbnailQueryFixture -{ - /// - /// Creates a random valid query to get a thumbnail. - /// - /// The created query. - public static GetThumbnailQuery CreateGetThumbnailQuery() - { - return new Faker() - .CustomInstantiator(f => new GetThumbnailQuery( - default!, - default - )) - .RuleFor(x => x.Path, f => f.System.FilePath()) - .RuleFor(x => x.Quality, f => f.Random.Int()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs index 493a3090..8a45fef0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs @@ -3,10 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; +using Lumina.Application.Fixtures.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Threading; @@ -24,6 +26,8 @@ public class GetThumbnailQueryHandlerTests private readonly IFixture _fixture; private readonly IThumbnailService _mockThumbnailService; private readonly GetThumbnailQueryHandler _sut; + private readonly GetThumbnailQueryFixture _getThumbnailQueryFixture = new(); + private readonly ThumbnailFixture _thumbnailFixture = new(); public GetThumbnailQueryHandlerTests() { @@ -39,8 +43,8 @@ public class GetThumbnailQueryHandlerTests public async Task HandleAsync_WhenCalledWithValidQuery_ShouldReturnSuccessResult() { // Arrange - GetThumbnailQuery query = _fixture.Create(); - Thumbnail thumbnail = _fixture.Create(); + GetThumbnailQuery query = _getThumbnailQueryFixture.Create(); + Thumbnail thumbnail = _thumbnailFixture.Create(); _mockThumbnailService.GetThumbnailAsync(query.Path!, query.Quality, Arg.Any()) .Returns(Result.From(thumbnail)); @@ -60,7 +64,7 @@ public class GetThumbnailQueryHandlerTests public async Task HandleAsync_WhenThumbnailServiceReturnsError_ShouldReturnFailureResult() { // Arrange - GetThumbnailQuery query = _fixture.Create(); + GetThumbnailQuery query = _getThumbnailQueryFixture.Create(); Error error = Error.Failure("ThumbnailService.Error", "An error occurred"); _mockThumbnailService.GetThumbnailAsync(query.Path!, query.Quality, Arg.Any()) .Returns(error); @@ -78,7 +82,7 @@ public class GetThumbnailQueryHandlerTests public async Task HandleAsync_WhenCancellationRequested_ShouldCancelOperation() { // Arrange - GetThumbnailQuery query = _fixture.Create(); + GetThumbnailQuery query = _getThumbnailQueryFixture.Create(); CancellationTokenSource cts = new(); cts.Cancel(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs index 3af9c041..1f15f1df 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryValidatorTests.cs @@ -15,15 +15,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Quer [ExcludeFromCodeCoverage] public class GetThumbnailQueryValidatorTests { - private readonly GetThumbnailQueryValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public GetThumbnailQueryValidatorTests() - { - _validator = new GetThumbnailQueryValidator(); - } + private readonly GetThumbnailQueryValidator _validator = new(); [Fact] public void Validate_WhenPathIsNull_ShouldHaveValidationError() diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/Fixtures/SetupApplicationCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/Fixtures/SetupApplicationCommandFixture.cs deleted file mode 100644 index c4449632..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/Fixtures/SetupApplicationCommandFixture.cs +++ /dev/null @@ -1,35 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class SetupApplicationCommandFixture -{ - /// - /// Creates a random valid command for the application setup. - /// - /// The created command. - public SetupApplicationCommand CreateSetupApplicationCommand() - { - string password = "Abcd123$"; - return new Faker() - .CustomInstantiator(f => new SetupApplicationCommand( - default!, - default!, - default!, - true - )) - .RuleFor(x => x.Username, f => f.Internet.UserName()) - .RuleFor(x => x.Password, password) - .RuleFor(x => x.PasswordConfirm, password) - .RuleFor(x => x.Use2fa, f => f.Random.Bool()) - .Generate(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs index d1a9270b..ef38a48c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs @@ -9,8 +9,8 @@ using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; -using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; -using Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -38,7 +38,8 @@ public class SetupApplicationCommandHandlerTests private readonly IDateTimeProvider _mockDateTimeProvider; private readonly IDataSeedService _mockDataSeedService; private readonly SetupApplicationCommandHandler _sut; - private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture = new(); /// /// Initializes a new instance of the class. @@ -53,7 +54,6 @@ public class SetupApplicationCommandHandlerTests _mockUserRepository = Substitute.For(); _mockDateTimeProvider = Substitute.For(); _mockDataSeedService = Substitute.For(); - _setupApplicationCommandFixture = new SetupApplicationCommandFixture(); IValidator mockValidator = Substitute.For>(); mockValidator.Validate(Arg.Any()) .Returns([]); @@ -76,7 +76,7 @@ public class SetupApplicationCommandHandlerTests public async Task HandleAsync_WhenNoExistingUsers_ShouldCreateAdminUserWithout2FA() { // Arrange - SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand() with { Use2fa = false }; + SetupApplicationCommand command = _setupApplicationCommandFixture.Create() with { Use2fa = false }; string hashedPassword = Uri.EscapeDataString("hashedPassword"); _mockUserRepository.GetAllAsync(Arg.Any()) @@ -112,7 +112,7 @@ public class SetupApplicationCommandHandlerTests public async Task HandleAsync_WhenNoExistingUsersAndWith2FA_ShouldCreateAdminUserWithTOTP() { // Arrange - SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand() with { Use2fa = true }; + SetupApplicationCommand command = _setupApplicationCommandFixture.Create() with { Use2fa = true }; string hashedPassword = Uri.EscapeDataString("hashedPassword"); byte[] totpSecret = [1, 2, 3]; string qrCodeUri = "data:image/png;base64,test"; @@ -157,8 +157,8 @@ public class SetupApplicationCommandHandlerTests public async Task HandleAsync_WhenUserAlreadyExists_ShouldReturnError() { // Arrange - SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); - UserEntity existingUser = UserEntityFixture.CreateUserEntity(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); + UserEntity existingUser = _userEntityFixture.Create(); _mockUserRepository.GetAllAsync(Arg.Any()) .Returns(new[] { existingUser }); @@ -179,7 +179,7 @@ public class SetupApplicationCommandHandlerTests public async Task HandleAsync_WhenGetAllUsersReturnsError_ShouldReturnError() { // Arrange - SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to retrieve users"); _mockUserRepository.GetAllAsync(Arg.Any()) @@ -201,7 +201,7 @@ public class SetupApplicationCommandHandlerTests public async Task HandleAsync_WhenInsertUserReturnsError_ShouldReturnError() { // Arrange - SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to insert user"); _mockUserRepository.GetAllAsync(Arg.Any()) @@ -225,7 +225,7 @@ public class SetupApplicationCommandHandlerTests public async Task HandleAsync_WhenSetDefaultAuthorizationPermissionsFails_ShouldReturnError() { // Arrange - SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to set default permissions"); _mockUserRepository.GetAllAsync(Arg.Any()) @@ -250,7 +250,7 @@ public class SetupApplicationCommandHandlerTests public async Task HandleAsync_WhenSetDefaultAuthorizationRolesFails_ShouldReturnError() { // Arrange - SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to set default roles"); _mockUserRepository.GetAllAsync(Arg.Any()) @@ -278,7 +278,7 @@ public class SetupApplicationCommandHandlerTests public async Task HandleAsync_WhenSetAdminRolePermissionsFails_ShouldReturnError() { // Arrange - SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to set admin role permissions"); _mockUserRepository.GetAllAsync(Arg.Any()) @@ -309,7 +309,7 @@ public class SetupApplicationCommandHandlerTests public async Task HandleAsync_WhenSetAdminRoleToAdministratorAccountFails_ShouldReturnError() { // Arrange - SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to set admin role to administrator account"); _mockUserRepository.GetAllAsync(Arg.Any()) @@ -342,7 +342,7 @@ public class SetupApplicationCommandHandlerTests public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccessResponse() { // Arrange - SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); _mockUserRepository.GetAllAsync(Arg.Any()) .Returns(Result.From(Enumerable.Empty())); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs index 8a2a6400..81ef3d81 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Errors; using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using Lumina.Application.Fixtures.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -16,23 +16,14 @@ namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Command [ExcludeFromCodeCoverage] public class SetupApplicationCommandValidatorTests { - private readonly SetupApplicationCommandValidator _validator; - private readonly SetupApplicationCommandFixture _commandFixture; - - /// - /// Initializes a new instance of the class. - /// - public SetupApplicationCommandValidatorTests() - { - _validator = new SetupApplicationCommandValidator(); - _commandFixture = new SetupApplicationCommandFixture(); - } + private readonly SetupApplicationCommandValidator _validator = new(); + private readonly SetupApplicationCommandFixture _commandFixture = new(); [Fact] public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.Create(); command = command with { Username = null }; // Act @@ -46,7 +37,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.Create(); command = command with { Username = string.Empty }; // Act @@ -60,7 +51,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.Create(); command = command with { Username = " " }; // Act @@ -74,7 +65,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordIsNull_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.Create(); command = command with { Password = null! }; // Act @@ -88,7 +79,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.Create(); command = command with { Password = string.Empty }; // Act @@ -102,7 +93,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.Create(); command = command with { Password = " " }; // Act @@ -116,7 +107,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordConfirmIsNull_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.Create(); command = command with { PasswordConfirm = null! }; // Act @@ -130,7 +121,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordConfirmIsEmpty_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.Create(); command = command with { PasswordConfirm = string.Empty }; // Act @@ -144,7 +135,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordConfirmIsWhiteSpace_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.Create(); command = command with { PasswordConfirm = " " }; // Act @@ -158,7 +149,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordAndPasswordConfirmDontMatch_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.Create(); command = command with { PasswordConfirm = "$321Bcda" }; // Act @@ -178,7 +169,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) { // Arrange - SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.Create(); command = command with { Password = password, PasswordConfirm = password }; // Act @@ -196,7 +187,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password) { // Arrange - SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.Create(); command = command with { Password = password, PasswordConfirm = password }; // Act @@ -210,7 +201,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { // Arrange - SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.Create(); command = command with { Password = "$321Bcda", PasswordConfirm = "$321Bcda" }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandlerTests.cs similarity index 92% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandlerTests.cs index 83e84a03..1432c22e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandlerTests.cs @@ -3,7 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; -using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Responses.UsersManagement; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -14,7 +14,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Queries.CheckInitiliazation; +namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; /// /// Contains unit tests for the class. @@ -25,6 +25,7 @@ public class CheckInitializationQueryHandlerTests private readonly IUnitOfWork _mockUnitOfWork; private readonly IUserRepository _mockUserRepository; private readonly CheckInitializationQueryHandler _sut; + private readonly UserEntityFixture _userEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -43,7 +44,7 @@ public class CheckInitializationQueryHandlerTests public async Task HandleAsync_WhenUsersExist_ShouldReturnInitialized() { // Arrange - List users = UserEntityFixture.CreateMany(); + List users = _userEntityFixture.CreateMany(); _mockUserRepository.GetAllAsync(Arg.Any()) .Returns(Result.From(users.AsEnumerable())); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs deleted file mode 100644 index a49b1e28..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs +++ /dev/null @@ -1,110 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Fixtures; - -/// -/// Fixture class for the . -/// -[ExcludeFromCodeCoverage] -public class DomainLibraryFixture -{ - private readonly Faker _faker; - private readonly Random _random = new(); - - /// - /// Initializes a new instance of the class. - /// - public DomainLibraryFixture() - { - _faker = new Faker(); - } - - /// - /// Creates a media library domain entity. - /// - /// The created media library entity. - public Library CreateLibrary() - { - List validPaths = - [ - "C:/Media", - "D:/Books", - "E:/Digital Library", - "F:/Content" - ]; - - Result library = Library.Create( - UserId.CreateUnique(), - _faker.Random.String2(_faker.Random.Number(1, 50)), - _faker.PickRandom(), - validPaths.Take(_random.Next(1, validPaths.Count)), - _faker.System.FilePath(), - _faker.Random.Bool(), - _faker.Random.Bool(), - _faker.Random.Bool(), - _faker.Random.Bool(), - _faker.Random.Bool(), - [ScanId.CreateUnique(), ScanId.CreateUnique()] - ); - - return library.Value; - } - - public Library CreateLibraryWithSpecificValues( - Guid? id = null, - Guid? userId = null, - string? title = null, - LibraryType? libraryType = null, - IEnumerable? contentLocations = null, - string? coverImage = null, - bool isEnabled = true, - bool isLocked = false, - bool downloadMetadataFromWeb = true, - bool shouldSaveMetadataInMediaDirectories = false, - bool shouldSkipUnchangedDirectoriesDuringScan = false, - IEnumerable? scanIds = null) - { - Result library = id is null ? - Library.Create( - userId is not null ? UserId.Create(userId.Value) : UserId.CreateUnique(), - title ?? _faker.Random.String2(_faker.Random.Number(1, 50)), - libraryType ?? LibraryType.Book, - contentLocations ?? ["C:/Media"], - coverImage, - isEnabled, - isLocked, - downloadMetadataFromWeb, - shouldSaveMetadataInMediaDirectories, - shouldSkipUnchangedDirectoriesDuringScan, - scanIds?.Select(scanId => ScanId.Create(scanId)).ToList() ?? [ScanId.CreateUnique(), ScanId.CreateUnique()] - ) : - Library.Create( - LibraryId.Create(id.Value), - userId is not null ? UserId.Create(userId.Value) : UserId.CreateUnique(), - title ?? _faker.Random.String2(_faker.Random.Number(1, 50)), - libraryType ?? LibraryType.Book, - contentLocations ?? ["C:/Media"], - coverImage, - isEnabled, - isLocked, - downloadMetadataFromWeb, - shouldSaveMetadataInMediaDirectories, - shouldSkipUnchangedDirectoriesDuringScan, - scanIds?.Select(scanId => ScanId.Create(scanId)).ToList() ?? [ScanId.CreateUnique(), ScanId.CreateUnique()] - ); - - return library.Value; - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs index 6850e325..fbe1d2f8 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs @@ -6,8 +6,8 @@ using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; -using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +using Lumina.Application.Fixtures.Common.Setup; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -33,7 +33,7 @@ public class AddBookCommandHandlerTests private readonly IUnitOfWork _mockUnitOfWork; private readonly IBookRepository _mockBookRepository; private readonly AddBookCommandHandler _sut; - private readonly AddBookCommandFixture _commandBookFixture; + private readonly AddBookCommandFixture _commandBookFixture = new(); /// /// Initializes a new instance of the class. @@ -53,14 +53,13 @@ public class AddBookCommandHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); _sut = new AddBookCommandHandler(_mockUnitOfWork, mockValidator); - _commandBookFixture = new AddBookCommandFixture(); } [Fact] public async Task HandleAsync_WhenCalledWithValidCommand_ShouldReturnSuccessResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); @@ -79,7 +78,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenRepositoryInsertFails_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Errors.WrittenContent.BookAlreadyExists); @@ -98,7 +97,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenCalledWithInvalidISBN_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { ISBNs = [new IsbnDto("invalid", IsbnFormat.Isbn13)] }; // Act @@ -115,7 +114,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenCalledWithInvalidRating_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Ratings = [new BookRatingDto(-1, 5, null, null)] }; // Act @@ -132,7 +131,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenGenreCreationFails_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with @@ -155,7 +154,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenTagCreationFails_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with @@ -178,7 +177,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenReleaseInfoCreationFails_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with @@ -208,7 +207,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenLanguageInfoCreationFails_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with @@ -231,7 +230,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenOriginalLanguageInfoCreationFails_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs index 44ab26e7..731697a1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; @@ -20,23 +20,14 @@ namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.B [ExcludeFromCodeCoverage] public class AddBookCommandValidatorTests { - private readonly AddBookCommandFixture _commandBookFixture; - private readonly AddBookCommandValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public AddBookCommandValidatorTests() - { - _validator = new AddBookCommandValidator(); - _commandBookFixture = new AddBookCommandFixture(); - } + private readonly AddBookCommandFixture _commandBookFixture = new(); + private readonly AddBookCommandValidator _validator = new(); [Fact] public void Validate_WhenTitleIsNull_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Title = null! } }; // Act @@ -50,7 +41,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Title = new Faker().Random.String2(300) } }; // Act @@ -64,7 +55,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Title = new Faker().Random.String2(200) } }; // Act @@ -78,7 +69,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalTitleExceeds255Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalTitle = new Faker().Random.String2(300) } }; // Act @@ -92,7 +83,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalTitleIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalTitle = new Faker().Random.String2(200) } }; // Act @@ -106,7 +97,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalTitleIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalTitle = null! } }; // Act @@ -120,7 +111,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionExceeds2000Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = new Faker().Random.String2(2001) } }; // Act @@ -134,7 +125,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = new Faker().Random.String2(1500) } }; // Act @@ -148,7 +139,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = null! } }; // Act @@ -162,7 +153,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenDescriptionIsEmpty_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Description = string.Empty } }; // Act @@ -176,7 +167,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = null! } }; // Act @@ -190,7 +181,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseDate = null!, OriginalReleaseYear = new Faker().Random.Int(2000, 2005), ReReleaseYear = new Faker().Random.Int(2005, 2010), ReReleaseDate = null! } } }; // Act @@ -204,7 +195,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 0 } } }; // Act @@ -218,7 +209,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 10000 } } }; // Act @@ -232,7 +223,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with @@ -254,7 +245,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReReleaseYear = 0 } } }; // Act @@ -268,7 +259,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReReleaseYear = 10000 } } }; // Act @@ -282,7 +273,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseCountryIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseCountry = new Faker().Random.String2(2).ToUpper() } } }; // Act @@ -296,7 +287,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseCountryIsInvalid_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseCountry = new Faker().Random.String2(3) } } }; // Act @@ -310,7 +301,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseVersionIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseVersion = new Faker().Random.String2(50) } } }; // Act @@ -324,7 +315,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReleaseVersionExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { ReleaseVersion = new Faker().Random.String2(51) } } }; // Act @@ -338,7 +329,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 2000, ReReleaseYear = 2001, ReReleaseDate = null! } } }; // Act @@ -352,7 +343,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseYear = 2001, ReReleaseYear = 2000, ReReleaseDate = null! } } }; // Act @@ -366,7 +357,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseDate = new DateOnly(2000, 1, 1), ReReleaseDate = new DateOnly(2001, 1, 1) } } }; // Act @@ -380,7 +371,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { ReleaseInfo = bookCommand.Metadata.ReleaseInfo! with { OriginalReleaseDate = new DateOnly(2001, 1, 1), ReReleaseDate = new DateOnly(2000, 1, 1) } } }; // Act @@ -394,7 +385,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenresIsNull_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = null! } }; // Act @@ -408,7 +399,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenreNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = [.. bookCommand.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = string.Empty } : genre)] } }; // Act @@ -422,7 +413,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenreNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Genres = [.. bookCommand.Metadata.Genres!.Select((genre, index) => index == 0 ? genre with { Name = new Faker().Random.String2(51) } : genre)] } }; // Act @@ -436,7 +427,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGenresAreValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with @@ -456,7 +447,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagsIsNull_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = null! } }; // Act @@ -470,7 +461,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = [.. bookCommand.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = string.Empty } : tag)] } }; // Act @@ -484,7 +475,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Tags = [.. bookCommand.Metadata.Tags!.Select((tag, index) => index == 0 ? tag with { Name = new Faker().Random.String2(51) } : tag)] } }; // Act @@ -498,7 +489,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenTagsAreValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with @@ -518,7 +509,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = null! } }; // Act @@ -532,7 +523,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageCode = string.Empty } } }; // Act @@ -546,7 +537,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageCodeExceeds2Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageCode = new Faker().Random.String2(3) } } }; // Act @@ -560,7 +551,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageName = string.Empty } } }; // Act @@ -574,7 +565,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { LanguageName = new Faker().Random.String2(51) } } }; // Act @@ -588,7 +579,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { NativeName = null! } } }; // Act @@ -602,7 +593,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Language = bookCommand.Metadata.Language! with { NativeName = new Faker().Random.String2(51) } } }; // Act @@ -616,7 +607,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = null! } }; // Act @@ -630,7 +621,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageCode = string.Empty } } }; // Act @@ -644,7 +635,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageCodeExceeds2Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageCode = new Faker().Random.String2(3) } } }; // Act @@ -658,7 +649,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNameIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageName = string.Empty } } }; // Act @@ -672,7 +663,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { LanguageName = new Faker().Random.String2(51) } } }; // Act @@ -686,7 +677,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { NativeName = null! } } }; // Act @@ -700,7 +691,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { OriginalLanguage = bookCommand.Metadata.OriginalLanguage! with { NativeName = new Faker().Random.String2(51) } } }; // Act @@ -714,7 +705,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyPublisher_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Publisher = null! } }; // Act @@ -728,7 +719,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidPublisher_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Publisher = new Faker().Random.String2(100) } }; // Act @@ -742,7 +733,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthPublisher_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { Publisher = new Faker().Random.String2(101) } }; // Act @@ -756,7 +747,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = null } }; // Act @@ -770,7 +761,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsZero_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = 0 } }; // Act @@ -784,7 +775,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsNegative_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = -1 } }; // Act @@ -798,7 +789,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenPageCountIsPositive_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Metadata = bookCommand.Metadata! with { PageCount = 100 } }; // Act @@ -812,7 +803,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenFormatIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Format = null }; // Act @@ -826,7 +817,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenFormatIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Format = BookFormat.Hardcover }; // Act @@ -840,7 +831,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenFormatIsInvalid_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Format = (BookFormat)99 }; // Act @@ -854,7 +845,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenEditionIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Edition = null }; // Act @@ -868,7 +859,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenEditionIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Edition = new Faker().Random.String2(50) }; // Act @@ -882,7 +873,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenEditionExceeds50Characters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Edition = new Faker().Random.String2(51) }; // Act @@ -896,7 +887,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { VolumeNumber = null }; // Act @@ -910,7 +901,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsZero_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { VolumeNumber = 0 }; // Act @@ -924,7 +915,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsNegative_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { VolumeNumber = -1 }; // Act @@ -938,7 +929,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsPositive_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { VolumeNumber = 1 }; // Act @@ -952,7 +943,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenSeriesIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Series = null }; // Act @@ -966,7 +957,7 @@ public class AddBookCommandValidatorTests //public void Validate_WhenSeriesTitleIsEmpty_ShouldHaveValidationError() //{ // // Arrange - // var bookCommand = _commandBookFixture.CreateCommandBook(); + // var bookCommand = _commandBookFixture.Create(); // bookCommand = bookCommand with { Series = bookCommand.Series! with { Title = string.Empty } }; // // Act @@ -980,7 +971,7 @@ public class AddBookCommandValidatorTests //public void Validate_WhenSeriesTitleExceeds255Characters_ShouldHaveValidationError() //{ // // Arrange - // var bookCommand = _commandBookFixture.CreateCommandBook(); + // var bookCommand = _commandBookFixture.Create(); // bookCommand = bookCommand with { Series = bookCommand.Series! with { Title = new Faker().Random.String2(256) } }; // // Act @@ -994,7 +985,7 @@ public class AddBookCommandValidatorTests //public void Validate_WhenSeriesTitleIsValid_ShouldNotHaveValidationError() //{ // // Arrange - // var bookCommand = _commandBookFixture.CreateCommandBook(); + // var bookCommand = _commandBookFixture.Create(); // bookCommand = bookCommand with { Series = bookCommand.Series! with { Title = new Faker().Random.String2(200) } }; // // Act @@ -1008,7 +999,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenAsinIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { ASIN = new Faker().Random.String2(10) }; // Act @@ -1022,7 +1013,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenAsinIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { ASIN = null }; // Act @@ -1036,7 +1027,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenAsinIsNotTenCharacters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { ASIN = new Faker().Random.String2(9) }; // Act @@ -1050,7 +1041,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { GoodreadsId = null }; // Act @@ -1064,7 +1055,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { GoodreadsId = "123456789" }; // Act @@ -1078,7 +1069,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsNonNumeric_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { GoodreadsId = "abc123" }; // Act @@ -1092,7 +1083,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdContainsSpaces_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { GoodreadsId = "123 456" }; // Act @@ -1106,7 +1097,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdContainsSpecialCharacters_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { GoodreadsId = "123-456" }; // Act @@ -1120,7 +1111,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { LCCN = null }; // Act @@ -1134,7 +1125,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { LCCN = "n78890351" }; // Act @@ -1148,7 +1139,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnHasInvalidFormat_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { LCCN = "invalid123" }; // Act @@ -1162,7 +1153,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsTooLong_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { LCCN = new Faker().Random.String2(15) }; // Act @@ -1176,7 +1167,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsTooShort_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { LCCN = "n12" }; // Act @@ -1190,7 +1181,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyOclcNumber_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { OCLCNumber = null }; // Act @@ -1204,7 +1195,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat1_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { OCLCNumber = "ocm12345678" }; // Act @@ -1218,7 +1209,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat2_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { OCLCNumber = "ocn123456789" }; // Act @@ -1232,7 +1223,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat3_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { OCLCNumber = "on1234567890" }; // Act @@ -1246,7 +1237,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat4_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { OCLCNumber = "(OCoLC)1234567890" }; // Act @@ -1260,7 +1251,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidOclcNumberFormat5_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { OCLCNumber = "12345678" }; // Act @@ -1274,7 +1265,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidOclcNumber_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { OCLCNumber = "invalid_oclc_number" }; // Act @@ -1288,7 +1279,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { OpenLibraryId = null! }; // Act @@ -1302,7 +1293,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { OpenLibraryId = "OL123456M" }; // Act @@ -1316,7 +1307,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsInvalid_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { OpenLibraryId = "InvalidID" }; // Act @@ -1330,7 +1321,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdStartsWithOLButIsInvalidFormat_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { OpenLibraryId = "OL123ABC" }; // Act @@ -1344,7 +1335,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdHasValidFormatButInvalidSuffix_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { OpenLibraryId = "OL123456X" }; // Act @@ -1358,7 +1349,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyLibraryThingId_ShouldAddBook() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { LibraryThingId = null }; // Act @@ -1372,7 +1363,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidLibraryThingId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { LibraryThingId = new Faker().Random.String2(50) }; // Act @@ -1386,7 +1377,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthLibraryThingId_ShouldReturnBadRequest() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { LibraryThingId = new Faker().Random.String2(51) }; // Act @@ -1400,7 +1391,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyGoogleBooksId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { GoogleBooksId = null! }; // Act @@ -1414,7 +1405,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthGoogleBooksId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { GoogleBooksId = new Faker().Random.String2(11) }; // Act @@ -1428,7 +1419,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidFormatGoogleBooksId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { GoogleBooksId = new Faker().Random.String2(11) + " " }; // Act @@ -1442,7 +1433,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidGoogleBooksId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { GoogleBooksId = new Faker().Random.String2(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-") }; // Act @@ -1456,7 +1447,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyBarnesAndNobleId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { BarnesAndNobleId = null! }; // Act @@ -1470,7 +1461,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthBarnesAndNobleId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { BarnesAndNobleId = new Faker().Random.String2(11) }; // Act @@ -1484,7 +1475,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNonNumericBarnesAndNobleId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { BarnesAndNobleId = new Faker().Random.AlphaNumeric(10) }; // Act @@ -1498,7 +1489,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidBarnesAndNobleId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { BarnesAndNobleId = new Faker().Random.Number(1000000000, 999999999).ToString() }; // Act @@ -1512,7 +1503,7 @@ public class AddBookCommandValidatorTests public void AddBook_WhenCalledWithEmptyAppleBooksId_ShouldAddBook() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { AppleBooksId = null }; // Act @@ -1526,7 +1517,7 @@ public class AddBookCommandValidatorTests public void AddBook_WhenCalledWithValidAppleBooksId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { AppleBooksId = "id123456" }; // Act @@ -1540,7 +1531,7 @@ public class AddBookCommandValidatorTests public void AddBook_WhenCalledWithInvalidAppleBooksId_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { AppleBooksId = "invalid_id" }; // Act @@ -1554,7 +1545,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullIsbns_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { ISBNs = null! }; // Act @@ -1568,7 +1559,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyIsbnValue_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = null! } : isbn)] }; // Act @@ -1582,7 +1573,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidIsbn10Value_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn10 } : isbn)] }; // Act @@ -1596,7 +1587,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidIsbn13Value_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = new Faker().Random.String2(5), Format = IsbnFormat.Isbn13 } : isbn)] }; // Act @@ -1610,7 +1601,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidIsbnFormat_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Format = (IsbnFormat)99 } : isbn)] }; // Act @@ -1624,7 +1615,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidIsbn10_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = "0-306-40615-2", Format = IsbnFormat.Isbn10 } : isbn)] }; // Act @@ -1638,7 +1629,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidIsbn13_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { ISBNs = [.. bookCommand.ISBNs!.Select((isbn, index) => index == 0 ? isbn with { Value = "978-3-16-148410-0", Format = IsbnFormat.Isbn13 } : isbn)] }; // Act @@ -1652,7 +1643,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullContributors_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Contributors = null! }; // Act @@ -1666,7 +1657,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullContributorName_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = null! } : contributor)] }; // Act @@ -1680,7 +1671,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthContributorDisplayName_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = new Faker().Random.String2(101) } } : contributor)] }; // Act @@ -1694,7 +1685,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyContributorDisplayName_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { DisplayName = null! } } : contributor)] }; // Act @@ -1708,7 +1699,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthContributorLegalName_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Name = contributor.Name! with { LegalName = new Faker().Random.String2(101) } } : contributor)] }; // Act @@ -1722,7 +1713,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullContributorRole_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = null! } : contributor)] }; // Act @@ -1736,7 +1727,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyContributorRoleName_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Name = null! } } : contributor)] }; // Act @@ -1750,7 +1741,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthContributorRoleName_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Name = new Faker().Random.String2(51) } } : contributor)] }; // Act @@ -1764,7 +1755,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyContributorRoleCategory_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Category = null! } } : contributor)] }; // Act @@ -1778,7 +1769,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithInvalidLengthContributorRoleCategory_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Category = new Faker().Random.String2(51) } } : contributor)] }; // Act @@ -1792,7 +1783,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullRatings_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Ratings = null! }; // Act @@ -1806,7 +1797,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNegativeRatingValue_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = -1 } : rating)] }; // Act @@ -1820,7 +1811,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithRatingValueGreaterThanMaxValue_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { Value = 6, MaxValue = 5 } : rating)] }; // Act @@ -1834,7 +1825,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNegativeMaxRatingValue_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { MaxValue = -1 } : rating)] }; // Act @@ -1848,7 +1839,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNegativeVoteCount_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = -1 } : rating)] }; // Act @@ -1862,7 +1853,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithValidRatings_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating @@ -1881,7 +1872,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullVoteCount_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook(); + AddBookCommand bookCommand = _commandBookFixture.Create(); bookCommand = bookCommand with { Ratings = [.. bookCommand.Ratings!.Select((rating, index) => index == 0 ? rating with { VoteCount = null } : rating)] }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookEntityFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookEntityFixture.cs deleted file mode 100644 index f9eb4c47..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/Fixtures/BookEntityFixture.cs +++ /dev/null @@ -1,149 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using Bogus; -using Lumina.Application.Common.DataAccess.Entities.Common; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class BookEntityFixture -{ - private readonly Fixture _fixture; - private readonly Random _random = new(); - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public BookEntityFixture() - { - _fixture = new Fixture(); - _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); - _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); - _faker = new Faker(); - } - - /// - /// Creates a random valid book entity. - /// - /// The created book entity. - public BookEntity CreateBook() - { - int releaseYear = _random.Next(2000, 2010); - int reReleaseYear = _random.Next(2010, 2020); - - Faker genre = new Faker() - .CustomInstantiator(f => new GenreEntity( - default! - )) - .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); - - Faker tag = new Faker() - .CustomInstantiator(f => new TagEntity( - default! - )) - .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))); - - Faker rating = new Faker() - .CustomInstantiator(f => new BookRatingEntity( - default, - default, - default, - default - )) - .RuleFor(e => e.Value, _random.Next(1, 5)) - .RuleFor(e => e.MaxValue, 5) - .RuleFor(e => e.Source, _fixture.Create()) - .RuleFor(e => e.VoteCount, _random.Next(1, 1000)); - - Faker isbn = new Faker() - .CustomInstantiator(f => new IsbnEntity( - default!, - default - )) - .RuleFor(i => i.Value, f => - { - bool isIsbn13 = f.Random.Bool(); - if (isIsbn13) - { - string prefix = f.Random.Bool() ? "978" : "979"; - string group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0'); - string publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0'); - string title = f.Random.Number(0, 99).ToString().PadLeft(2, '0'); - string isbn = $"{prefix}{group[..1]}{publisher}{title}"; - int sum = 0; - for (int i = 0; i < 12; i++) - sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString()); - int checkDigit = (10 - sum % 10) % 10; - return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}"; - } - else - { - int[] digits = new int[9]; - for (int i = 0; i < 9; i++) - digits[i] = f.Random.Number(0, 9); - int sum = 0; - for (int i = 0; i < 9; i++) - sum += (10 - i) * digits[i]; - int checkDigit = (11 - sum % 11) % 11; - string checkChar = checkDigit == 10 ? "X" : checkDigit.ToString(); - return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}"; - } - }) - .RuleFor(i => i.Format, (f, i) => i.Value!.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10); - - return new BookEntity - { - Id = Guid.NewGuid(), - LibraryId = Guid.NewGuid(), - Path = _faker.System.FilePath(), - Title = _faker.Random.String2(_faker.Random.Number(1, 255)), - OriginalTitle = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 255)) : null, - Description = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 2000)) : null, - OriginalReleaseDate = _faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)), - OriginalReleaseYear = releaseYear, - ReReleaseDate = _faker.DateOnlyBetween(new DateOnly(reReleaseYear, 1, 1), new DateOnly(reReleaseYear, 12, 31)), - ReReleaseYear = reReleaseYear, - ReleaseCountry = _faker.Random.String2(2), - ReleaseVersion = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null, - LanguageCode = _faker.Random.String2(2), - LanguageName = _faker.Random.String2(_faker.Random.Number(1, 50)), - LanguageNativeName = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null, - OriginalLanguageCode = _faker.Random.String2(2), - OriginalLanguageName = _faker.Random.String2(_faker.Random.Number(1, 50)), - OriginalLanguageNativeName = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null, - Tags = new HashSet(tag.Generate(_faker.Random.Number(1, 5))), - Genres = new HashSet(genre.Generate(_faker.Random.Number(1, 5))), - Publisher = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 100)) : null, - PageCount = _random.Next(100, 1000), - Format = _faker.PickRandom(), - Edition = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null, - VolumeNumber = _faker.Random.Bool() ? _random.Next(1, 20) : null, - ASIN = _faker.Random.String2(10), - GoodreadsId = _random.Next(100000, 500000).ToString(), - LCCN = _faker.Random.String2(_faker.Random.Number(8, 12)), - OCLCNumber = _faker.Random.String2(_faker.Random.Number(8, 12)), - OpenLibraryId = $"OL{_random.Next(1000000, 9999999)}M", - LibraryThingId = _faker.Random.String2(_faker.Random.Number(1, 50)), - GoogleBooksId = _faker.Random.String2(12), - BarnesAndNobleId = _faker.Random.String2(10), - AppleBooksId = $"id{_random.Next(1, 999999)}", - ISBNs = isbn.Generate(_faker.Random.Number(1, 5)), - Ratings = rating.Generate(_faker.Random.Number(1, 5)), - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedOnUtc = _faker.Random.Bool() ? DateTime.UtcNow.AddDays(-_random.Next(1, 100)) : null, - UpdatedBy = Guid.NewGuid() - }; - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingDtoFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingDtoFixture.cs deleted file mode 100644 index d22caac3..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingDtoFixture.cs +++ /dev/null @@ -1,69 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; - -/// -/// Fixture class for the . -/// -[ExcludeFromCodeCoverage] -public class BookRatingDtoFixture -{ - private readonly Fixture _fixture; - private readonly Random _random = new(); - - /// - /// Initializes a new instance of the class. - /// - public BookRatingDtoFixture() - { - _fixture = new Fixture(); - } - - /// - /// Creates a complete book rating DTO with all properties. - /// - /// The created book rating DTO. - public BookRatingDto CreateComplete() - { - return new BookRatingDto( - _random.Next(1, 5), - 5, - _fixture.Create(), - _random.Next(1, 1000) - ); - } - - /// - /// Creates a minimal book rating DTO with only required properties. - /// - /// The created book rating DTO. - public BookRatingDto CreateMinimal() - { - return new BookRatingDto( - _random.Next(1, 5), - 5, - null, - null - ); - } - - /// - /// Creates an invalid book rating DTO. - /// - /// The created invalid book rating DTO. - public BookRatingDto CreateInvalid() - { - return new BookRatingDto( - 10, // invalid: value > maxValue - 5, - _fixture.Create(), - _random.Next(1, 1000) - ); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingEntityFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingEntityFixture.cs deleted file mode 100644 index 469a7b9e..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingEntityFixture.cs +++ /dev/null @@ -1,55 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; - -/// -/// Fixture class for the . -/// -[ExcludeFromCodeCoverage] -public class BookRatingEntityFixture -{ - private readonly Random _random = new(); - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public BookRatingEntityFixture() - { - _faker = new Faker(); - } - - /// - /// Creates a book rating entity. - /// - /// The created book rating entity. - public BookRatingEntity CreateBookRating() - { - return new BookRatingEntity( - _random.Next(1, 5), - 5, - _faker.PickRandom(), - _random.Next(1, 1000) - ); - } - - /// - /// Creates an invalid book rating entity. - /// - /// The created invalid book rating entity. - public BookRatingEntity CreateInvalidBookRating() - { - return new BookRatingEntity( - null, - null, - null, - null - ); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingFixture.cs deleted file mode 100644 index 4246b557..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Common/Fixtures/BookRatingFixture.cs +++ /dev/null @@ -1,85 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures; - -/// -/// Fixture class for the domain entity. -/// -[ExcludeFromCodeCoverage] -public class BookRatingFixture -{ - private readonly Fixture _fixture; - private readonly Random _random = new(); - - /// - /// Initializes a new instance of the class. - /// - public BookRatingFixture() - { - _fixture = new Fixture(); - } - - /// - /// Creates a random valid book rating. - /// - /// The created book rating. - public BookRating CreateBookRating() - { - decimal maxValue = _random.Next(5, 10); - decimal value = _random.Next(1, (int)maxValue); - Optional source = Optional.Some(_fixture.Create()); - Optional voteCount = Optional.Some(_random.Next(1, 1000)); - - return BookRating.Create(value, maxValue, source, voteCount).Value; - } - - /// - /// Creates a random valid book rating with specific parameters. - /// - /// The rating value. - /// The maximum possible rating value. - /// The rating source. - /// The number of votes. - /// The created book rating. - public BookRating CreateBookRating( - decimal value, - decimal maxValue, - Optional source, - Optional voteCount) - { - return BookRating.Create(value, maxValue, source, voteCount).Value; - } - - /// - /// Creates a random valid book rating without a source. - /// - /// The created book rating. - public BookRating CreateBookRatingWithoutSource() - { - decimal maxValue = _random.Next(5, 10); - decimal value = _random.Next(1, (int)maxValue); - Optional voteCount = Optional.Some(_random.Next(1, 1000)); - - return BookRating.Create(value, maxValue, Optional.None(), voteCount).Value; - } - - /// - /// Creates a random valid book rating without vote count. - /// - /// The created book rating. - public BookRating CreateBookRatingWithoutVoteCount() - { - decimal maxValue = _random.Next(5, 10); - decimal value = _random.Next(1, (int)maxValue); - Optional source = Optional.Some(_fixture.Create()); - - return BookRating.Create(value, maxValue, source, Optional.None()).Value; - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs index c7e3ed50..8698100d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs @@ -4,13 +4,14 @@ using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.DataAccess.UnitTests.Core.Repositories.Plugins.Fixtures; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryMetadataProviders; @@ -18,6 +19,7 @@ namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryMetad /// /// Contains unit tests for the class. /// +[ExcludeFromCodeCoverage] public class ReorderLibraryMetadataProvidersCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; @@ -44,8 +46,8 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests // Arrange Guid libraryId = Guid.NewGuid(); LibraryMetadataProviderConfigurationEntityFixture configurationFixture = new(); - LibraryMetadataProviderConfigurationEntity firstProvider = configurationFixture.CreateConfiguration(libraryId, Guid.NewGuid(), 2); - LibraryMetadataProviderConfigurationEntity secondProvider = configurationFixture.CreateConfiguration(libraryId, Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity firstProvider = configurationFixture.Create(libraryId, Guid.NewGuid(), 2); + LibraryMetadataProviderConfigurationEntity secondProvider = configurationFixture.Create(libraryId, Guid.NewGuid(), 1); _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(new List { firstProvider, secondProvider }); _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs index ad8f489c..85a16954 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs @@ -10,6 +10,7 @@ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; @@ -17,6 +18,7 @@ namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryMetadataP /// /// Contains unit tests for the class. /// +[ExcludeFromCodeCoverage] public class SetLibraryMetadataProviderEnabledCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs index aeec76ed..563a4584 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs @@ -9,6 +9,7 @@ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Application.UnitTests.Core.Plugins.Commands.UpdatePluginSettings; @@ -16,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.Plugins.Commands.UpdatePluginSetting /// /// Contains unit tests for the class. /// +[ExcludeFromCodeCoverage] public class UpdatePluginSettingsCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs index c9540616..42feab39 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs @@ -3,13 +3,14 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Core.Plugins.Queries.GetPlugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Contracts.Responses.Plugins; -using Lumina.DataAccess.UnitTests.Core.Repositories.Plugins.Fixtures; using Lumina.Domain.Common.Primitives; using NSubstitute; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetPlugins; @@ -17,6 +18,7 @@ namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetPlugins; /// /// Contains unit tests for the class. /// +[ExcludeFromCodeCoverage] public class GetPluginsQueryHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; @@ -39,7 +41,7 @@ public class GetPluginsQueryHandlerTests { // Arrange PluginEntityFixture pluginFixture = new(); - List plugins = [pluginFixture.CreatePluginEntity(), pluginFixture.CreatePluginEntity()]; + List plugins = [pluginFixture.Create(), pluginFixture.Create()]; _mockPluginRepository.GetAllAsync(Arg.Any()).Returns(plugins); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs index 8b4646c5..e38e7cc4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs @@ -6,7 +6,7 @@ using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; -using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -28,6 +28,7 @@ public class ChangePasswordCommandHandlerTests private readonly IPasswordHashService _mockHashService; private readonly IUserRepository _mockUserRepository; private readonly ChangePasswordCommandHandler _sut; + private readonly UserEntityFixture _userEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -58,7 +59,7 @@ public class ChangePasswordCommandHandlerTests string hashedNewPassword = "hashedNewPassword"; string escapedHashedCurrentPassword = Uri.EscapeDataString("hashedCurrentPassword"); - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.Password = escapedHashedCurrentPassword; ChangePasswordCommand command = new( @@ -115,7 +116,7 @@ public class ChangePasswordCommandHandlerTests public async Task HandleAsync_WhenCurrentPasswordIsIncorrect_ShouldReturnError() { // Arrange - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); string incorrectPassword = "wrongPassword"; ChangePasswordCommand command = new( @@ -151,7 +152,7 @@ public class ChangePasswordCommandHandlerTests string escapedHashedCurrentPassword = Uri.EscapeDataString("hashedCurrentPassword"); Error error = Error.Failure("Database.Error", "Failed to update user"); - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.Password = escapedHashedCurrentPassword; ChangePasswordCommand command = new( @@ -186,7 +187,7 @@ public class ChangePasswordCommandHandlerTests // Arrange string currentPassword = "currentPassword"; string newPassword = "newPassword"; - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); ChangePasswordCommand command = new( user.Username, currentPassword, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs index 091fd87e..c38a7a64 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Errors; using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.ChangePassword; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -16,21 +16,14 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Comma [ExcludeFromCodeCoverage] public class ChangePasswordCommandValidatorTests { - private readonly ChangePasswordCommandValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public ChangePasswordCommandValidatorTests() - { - _validator = new ChangePasswordCommandValidator(); - } + private readonly ChangePasswordCommandValidator _validator = new(); + private readonly ChangePasswordCommandFixture _changePasswordCommandFixture = new(); [Fact] public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { Username = null! }; // Act @@ -44,7 +37,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { Username = string.Empty }; // Act @@ -58,7 +51,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { Username = " " }; // Act @@ -72,7 +65,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenCurrentPasswordIsNull_ShouldHaveValidationError() { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { CurrentPassword = null! }; // Act @@ -86,7 +79,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenCurrentPasswordIsEmpty_ShouldHaveValidationError() { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { CurrentPassword = string.Empty }; // Act @@ -100,7 +93,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenCurrentPasswordIsWhiteSpace_ShouldHaveValidationError() { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { CurrentPassword = " " }; // Act @@ -114,7 +107,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenNewPasswordIsNull_ShouldHaveValidationError() { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { NewPassword = null! }; // Act @@ -128,7 +121,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenNewPasswordIsEmpty_ShouldHaveValidationError() { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { NewPassword = string.Empty }; // Act @@ -142,7 +135,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenNewPasswordIsWhiteSpace_ShouldHaveValidationError() { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { NewPassword = " " }; // Act @@ -156,7 +149,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenNewPasswordConfirmIsNull_ShouldHaveValidationError() { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { NewPasswordConfirm = null! }; // Act @@ -170,7 +163,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenNewPasswordConfirmIsEmpty_ShouldHaveValidationError() { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { NewPasswordConfirm = string.Empty }; // Act @@ -184,7 +177,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenNewPasswordConfirmIsWhiteSpace_ShouldHaveValidationError() { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { NewPasswordConfirm = " " }; // Act @@ -198,7 +191,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenNewPasswordAndNewPasswordConfirmDontMatch_ShouldHaveValidationError() { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { NewPasswordConfirm = "$321Bcda" }; // Act @@ -218,7 +211,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenCurrentPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { CurrentPassword = password }; // Act @@ -238,7 +231,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenNewPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { NewPassword = password, NewPasswordConfirm = password }; // Act @@ -256,7 +249,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenPasswordsMatchPattern_ShouldNotHaveValidationError(string password) { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); command = command with { CurrentPassword = password, @@ -276,7 +269,7 @@ public class ChangePasswordCommandValidatorTests public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { // Arrange - ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + ChangePasswordCommand command = _changePasswordCommandFixture.Create(); // Act List result = _validator.TestValidate(command); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordCommandFixture.cs deleted file mode 100644 index 49ca6c5b..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordCommandFixture.cs +++ /dev/null @@ -1,35 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class ChangePasswordCommandFixture -{ - /// - /// Creates a random valid command for changing a password. - /// - /// The created command. - public static ChangePasswordCommand CreateChangePasswordCommand() - { - string currentPassword = "Abcd123$"; - string newPassword = "Wxyz789#"; - return new Faker() - .CustomInstantiator(f => new ChangePasswordCommand( - default!, - default!, - default!, - default! - )) - .RuleFor(x => x.Username, f => f.Person.UserName) - .RuleFor(x => x.CurrentPassword, currentPassword) - .RuleFor(x => x.NewPassword, newPassword) - .RuleFor(x => x.NewPasswordConfirm, newPassword); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordCommandFixture.cs deleted file mode 100644 index ec608ab4..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordCommandFixture.cs +++ /dev/null @@ -1,29 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class RecoverPasswordCommandFixture -{ - /// - /// Creates a random valid command for password recovery. - /// - /// The created command. - public static RecoverPasswordCommand CreateRecoverPasswordCommand() - { - return new Faker() - .CustomInstantiator(f => new RecoverPasswordCommand( - default!, - default! - )) - .RuleFor(x => x.Username, f => f.Person.UserName) - .RuleFor(x => x.TotpCode, f => f.Random.Replace("######")); // generates 6 random digits - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs index 7a9923fb..e542116a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs @@ -7,7 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; -using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -31,6 +31,7 @@ public class RecoverPasswordCommandHandlerTests private readonly ICryptographyService _mockCryptographyService; private readonly IUserRepository _mockUserRepository; private readonly RecoverPasswordCommandHandler _sut; + private readonly UserEntityFixture _userEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -65,7 +66,7 @@ public class RecoverPasswordCommandHandlerTests string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 }); string hashedTempPassword = "hashedTempPassword"; - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.TotpSecret = encryptedTotpSecret; user.TempPassword = null; @@ -121,7 +122,7 @@ public class RecoverPasswordCommandHandlerTests public async Task HandleAsync_WhenTempPasswordExists_ShouldReturnError() { // Arrange - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.TempPassword = "existingTempPassword"; user.TempPasswordCreated = DateTime.UtcNow; @@ -146,7 +147,7 @@ public class RecoverPasswordCommandHandlerTests public async Task HandleAsync_WhenUserDoesNotUseTOTP_ShouldReturnError() { // Arrange - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.TotpSecret = null; RecoverPasswordCommand command = new(user.Username, "123456"); @@ -174,7 +175,7 @@ public class RecoverPasswordCommandHandlerTests string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 }); - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.TotpSecret = encryptedTotpSecret; RecoverPasswordCommand command = new(user.Username, totpCode); @@ -208,7 +209,7 @@ public class RecoverPasswordCommandHandlerTests string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 }); Error error = Error.Failure("Database.Error", "Failed to update user"); - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.TotpSecret = encryptedTotpSecret; RecoverPasswordCommand command = new(user.Username, totpCode); @@ -242,7 +243,7 @@ public class RecoverPasswordCommandHandlerTests string totpCode = "123456"; string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.TotpSecret = encryptedTotpSecret; RecoverPasswordCommand command = new(user.Username, totpCode); @@ -269,7 +270,7 @@ public class RecoverPasswordCommandHandlerTests // Arrange string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.TotpSecret = encryptedTotpSecret; RecoverPasswordCommand command = new(user.Username, null); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs index 28aaaa3a..408a7781 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Errors; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.RecoverPassword; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -16,21 +16,14 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Comma [ExcludeFromCodeCoverage] public class RecoverPasswordCommandValidatorTests { - private readonly RecoverPasswordCommandValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public RecoverPasswordCommandValidatorTests() - { - _validator = new RecoverPasswordCommandValidator(); - } + private readonly RecoverPasswordCommandValidator _validator = new(); + private readonly RecoverPasswordCommandFixture _recoverPasswordCommandFixture = new(); [Fact] public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() { // Arrange - RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(); command = command with { Username = null! }; // Act @@ -44,7 +37,7 @@ public class RecoverPasswordCommandValidatorTests public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() { // Arrange - RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(); command = command with { Username = string.Empty }; // Act @@ -58,7 +51,7 @@ public class RecoverPasswordCommandValidatorTests public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() { // Arrange - RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(); command = command with { Username = " " }; // Act @@ -72,7 +65,7 @@ public class RecoverPasswordCommandValidatorTests public void Validate_WhenTotpCodeIsNull_ShouldHaveValidationError() { // Arrange - RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(); command = command with { TotpCode = null! }; // Act @@ -86,7 +79,7 @@ public class RecoverPasswordCommandValidatorTests public void Validate_WhenTotpCodeIsEmpty_ShouldHaveValidationError() { // Arrange - RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(); command = command with { TotpCode = string.Empty }; // Act @@ -100,7 +93,7 @@ public class RecoverPasswordCommandValidatorTests public void Validate_WhenTotpCodeIsWhiteSpace_ShouldHaveValidationError() { // Arrange - RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(); command = command with { TotpCode = " " }; // Act @@ -120,7 +113,7 @@ public class RecoverPasswordCommandValidatorTests public void Validate_WhenTotpCodeIsInvalid_ShouldHaveValidationError(string totpCode) { // Arrange - RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(); command = command with { TotpCode = totpCode }; // Act @@ -137,7 +130,7 @@ public class RecoverPasswordCommandValidatorTests public void Validate_WhenTotpCodeIsValid_ShouldNotHaveValidationError(string totpCode) { // Arrange - RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(); command = command with { TotpCode = totpCode }; // Act @@ -151,7 +144,7 @@ public class RecoverPasswordCommandValidatorTests public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { // Arrange - RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create(); // Act List result = _validator.TestValidate(command); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegisterUserCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegisterUserCommandFixture.cs deleted file mode 100644 index 8f8f7aba..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegisterUserCommandFixture.cs +++ /dev/null @@ -1,33 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class RegisterUserCommandFixture -{ - /// - /// Creates a random valid command for a new account registration. - /// - /// The created command. - public static RegisterUserCommand CreateRegisterCommand() - { - string password = "Abcd123$"; - return new Faker() - .CustomInstantiator(f => new RegisterUserCommand( - default!, - default!, - default!, - true - )) - .RuleFor(x => x.Username, f => f.Person.UserName) - .RuleFor(x => x.Password, password) - .RuleFor(x => x.PasswordConfirm, password); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs index 1c95f5b0..7818ddbb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs @@ -8,8 +8,8 @@ using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; -using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; -using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.RegisterUser; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -35,6 +35,8 @@ public class RegisterUserCommandHandlerTests private readonly IUserRepository _mockUserRepository; private readonly IDateTimeProvider _mockDateTimeProvider; private readonly RegisterUserCommandHandler _sut; + private readonly RegisterUserCommandFixture _registerUserCommandFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -69,7 +71,7 @@ public class RegisterUserCommandHandlerTests public async Task HandleAsync_WhenUserDoesNotExistAndWith2FA_ShouldRegisterUser() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); byte[] totpSecret = [1, 2, 3]; string qrCodeUri = "data:image/png;base64,test"; string encryptedSecret = "encryptedSecret"; @@ -109,7 +111,7 @@ public class RegisterUserCommandHandlerTests public async Task HandleAsync_WhenUserDoesNotExistAndWithout2FA_ShouldRegisterUser() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand() with { Use2fa = false }; + RegisterUserCommand command = _registerUserCommandFixture.Create() with { Use2fa = false }; string hashedPassword = "hashedPassword"; _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) @@ -140,8 +142,8 @@ public class RegisterUserCommandHandlerTests public async Task HandleAsync_WhenUserAlreadyExists_ShouldReturnError() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); - UserEntity existingUser = UserEntityFixture.CreateUserEntity(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); + UserEntity existingUser = _userEntityFixture.Create(); _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) .Returns(Result.From(existingUser)); @@ -162,7 +164,7 @@ public class RegisterUserCommandHandlerTests public async Task HandleAsync_WhenInsertFails_ShouldReturnError() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to insert user"); _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) @@ -186,7 +188,7 @@ public class RegisterUserCommandHandlerTests public async Task HandleAsync_WhenGetByUsernameReturnsError_ShouldReturnError() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to check username"); _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs index e289cfe5..659b8e55 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Errors; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; +using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Commands.RegisterUser; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -16,21 +16,14 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Comma [ExcludeFromCodeCoverage] public class RegisterUserCommandValidatorTests { - private readonly RegisterUserCommandValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public RegisterUserCommandValidatorTests() - { - _validator = new RegisterUserCommandValidator(); - } + private readonly RegisterUserCommandValidator _validator = new(); + private readonly RegisterUserCommandFixture _registerUserCommandFixture = new(); [Fact] public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { Username = null! }; // Act @@ -44,7 +37,7 @@ public class RegisterUserCommandValidatorTests public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { Username = string.Empty }; // Act @@ -58,7 +51,7 @@ public class RegisterUserCommandValidatorTests public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { Username = " " }; // Act @@ -72,7 +65,7 @@ public class RegisterUserCommandValidatorTests public void Validate_WhenPasswordIsNull_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { Password = null! }; // Act @@ -86,7 +79,7 @@ public class RegisterUserCommandValidatorTests public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { Password = string.Empty }; // Act @@ -100,7 +93,7 @@ public class RegisterUserCommandValidatorTests public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { Password = " " }; // Act @@ -114,7 +107,7 @@ public class RegisterUserCommandValidatorTests public void Validate_WhenPasswordConfirmIsNull_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { PasswordConfirm = null! }; // Act @@ -128,7 +121,7 @@ public class RegisterUserCommandValidatorTests public void Validate_WhenPasswordConfirmIsEmpty_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { PasswordConfirm = string.Empty }; // Act @@ -142,7 +135,7 @@ public class RegisterUserCommandValidatorTests public void Validate_WhenPasswordConfirmIsWhiteSpace_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { PasswordConfirm = " " }; // Act @@ -156,7 +149,7 @@ public class RegisterUserCommandValidatorTests public void Validate_WhenPasswordAndPasswordConfirmDontMatch_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { PasswordConfirm = "$321Bcda" }; // Act @@ -176,7 +169,7 @@ public class RegisterUserCommandValidatorTests public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { Password = password, PasswordConfirm = password }; // Act @@ -194,7 +187,7 @@ public class RegisterUserCommandValidatorTests public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password) { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { Password = password, PasswordConfirm = password }; // Act @@ -208,7 +201,7 @@ public class RegisterUserCommandValidatorTests public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { Username = "valid.user123", @@ -232,7 +225,7 @@ public class RegisterUserCommandValidatorTests public void Validate_WhenUsernameHasInvalidLength_ShouldHaveValidationError(string username) { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { Username = username }; // Act @@ -256,7 +249,7 @@ public class RegisterUserCommandValidatorTests public void Validate_WhenUsernameHasInvalidFormat_ShouldHaveValidationError(string username) { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { Username = username }; // Act @@ -277,7 +270,7 @@ public class RegisterUserCommandValidatorTests public void Validate_WhenUsernameHasValidFormat_ShouldNotHaveValidationError(string username) { // Arrange - RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = _registerUserCommandFixture.Create(); command = command with { Username = username }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs index be1e390a..c2329892 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs @@ -6,8 +6,8 @@ using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUsers; -using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; -using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.GetUsers.Fixtures; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Queries.GetUsers; using Lumina.Contracts.Responses.UsersManagement.Users; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -32,7 +32,8 @@ public class GetUsersQueryHandlerTests private readonly ICurrentUserService _mockCurrentUserService; private readonly IUserRepository _mockUserRepository; private readonly GetUsersQueryHandler _sut; - private readonly GetUsersQueryFixture _getUsersQueryFixture; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly GetUsersQueryFixture _getUsersQueryFixture = new(); private readonly Guid _userId; /// @@ -44,7 +45,6 @@ public class GetUsersQueryHandlerTests _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockUserRepository = Substitute.For(); - _getUsersQueryFixture = new GetUsersQueryFixture(); _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); @@ -60,7 +60,7 @@ public class GetUsersQueryHandlerTests public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange - GetUsersQuery query = _getUsersQueryFixture.CreateQuery(); + GetUsersQuery query = _getUsersQueryFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(false); @@ -77,7 +77,7 @@ public class GetUsersQueryHandlerTests public async Task HandleAsync_WhenGetUsersFails_ShouldReturnError() { // Arrange - GetUsersQuery query = _getUsersQueryFixture.CreateQuery(); + GetUsersQuery query = _getUsersQueryFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get users"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -97,8 +97,8 @@ public class GetUsersQueryHandlerTests public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnUsers() { // Arrange - GetUsersQuery query = _getUsersQueryFixture.CreateQuery(); - IEnumerable users = UserEntityFixture.CreateMany(2); + GetUsersQuery query = _getUsersQueryFixture.Create(); + IEnumerable users = _userEntityFixture.CreateMany(2); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs index e2646382..2d372046 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs @@ -8,7 +8,7 @@ using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; -using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -34,6 +34,7 @@ public class LoginUserQueryHandlerTests private readonly IUserRepository _mockUserRepository; private readonly IDateTimeProvider _mockDateTimeProvider; private readonly LoginUserQueryHandler _sut; + private readonly UserEntityFixture _userEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -72,7 +73,7 @@ public class LoginUserQueryHandlerTests string hashedPassword = "hashedPassword"; string jwtToken = "jwtToken"; - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.Password = Uri.EscapeDataString(hashedPassword); user.TotpSecret = null; @@ -107,7 +108,7 @@ public class LoginUserQueryHandlerTests string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 }); - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.Password = Uri.EscapeDataString(hashedPassword); user.TotpSecret = encryptedTotpSecret; @@ -159,7 +160,7 @@ public class LoginUserQueryHandlerTests string password = "wrongPassword"; string hashedPassword = "hashedPassword"; - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.Password = Uri.EscapeDataString(hashedPassword); user.TempPassword = null; @@ -186,7 +187,7 @@ public class LoginUserQueryHandlerTests string hashedPassword = "hashedPassword"; string hashedTempPassword = "hashedTempPassword"; - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.Password = Uri.EscapeDataString(hashedPassword); user.TempPassword = Uri.EscapeDataString(hashedTempPassword); user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16); // Expired (more than 15 minutes old) @@ -222,7 +223,7 @@ public class LoginUserQueryHandlerTests string hashedTempPassword = "hashedTempPassword"; string jwtToken = "jwtToken"; - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.Password = Uri.EscapeDataString(hashedPassword); user.TempPassword = Uri.EscapeDataString(hashedTempPassword); // Set temp password created time to 10 minutes ago (still valid) @@ -259,7 +260,7 @@ public class LoginUserQueryHandlerTests string hashedPassword = "hashedPassword"; string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.Password = Uri.EscapeDataString(hashedPassword); user.TotpSecret = encryptedTotpSecret; @@ -288,7 +289,7 @@ public class LoginUserQueryHandlerTests string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 }); - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.Password = Uri.EscapeDataString(hashedPassword); user.TotpSecret = encryptedTotpSecret; @@ -337,7 +338,7 @@ public class LoginUserQueryHandlerTests string hashedPassword = "hashedPassword"; string hashedTempPassword = "hashedTempPassword"; - UserEntity user = UserEntityFixture.CreateUserEntity(); + UserEntity user = _userEntityFixture.Create(); user.Password = Uri.EscapeDataString(hashedPassword); user.TempPassword = Uri.EscapeDataString(hashedTempPassword); user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-10); // Valid timeframe diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs index b1273e49..5597ea95 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Errors; using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; +using Lumina.Application.Fixtures.Core.UsersManagement.Authentication.Queries.LoginUser; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -16,21 +16,14 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queri [ExcludeFromCodeCoverage] public class LoginUserQueryValidatorTests { - private readonly LoginUserQueryValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public LoginUserQueryValidatorTests() - { - _validator = new LoginUserQueryValidator(); - } + private readonly LoginUserQueryValidator _validator = new(); + private readonly LoginUserQueryFixture _loginUserQueryFixture = new(); [Fact] public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() { // Arrange - LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + LoginUserQuery query = _loginUserQueryFixture.Create(); query = query with { Username = null! }; // Act @@ -44,7 +37,7 @@ public class LoginUserQueryValidatorTests public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() { // Arrange - LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + LoginUserQuery query = _loginUserQueryFixture.Create(); query = query with { Username = string.Empty }; // Act @@ -58,7 +51,7 @@ public class LoginUserQueryValidatorTests public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() { // Arrange - LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + LoginUserQuery query = _loginUserQueryFixture.Create(); query = query with { Username = " " }; // Act @@ -72,7 +65,7 @@ public class LoginUserQueryValidatorTests public void Validate_WhenPasswordIsNull_ShouldHaveValidationError() { // Arrange - LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + LoginUserQuery query = _loginUserQueryFixture.Create(); query = query with { Password = null! }; // Act @@ -86,7 +79,7 @@ public class LoginUserQueryValidatorTests public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError() { // Arrange - LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + LoginUserQuery query = _loginUserQueryFixture.Create(); query = query with { Password = string.Empty }; // Act @@ -100,7 +93,7 @@ public class LoginUserQueryValidatorTests public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError() { // Arrange - LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + LoginUserQuery query = _loginUserQueryFixture.Create(); query = query with { Password = " " }; // Act @@ -120,7 +113,7 @@ public class LoginUserQueryValidatorTests public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) { // Arrange - LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + LoginUserQuery query = _loginUserQueryFixture.Create(); query = query with { Password = password }; // Act @@ -138,7 +131,7 @@ public class LoginUserQueryValidatorTests public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password) { // Arrange - LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + LoginUserQuery query = _loginUserQueryFixture.Create(); query = query with { Password = password }; // Act @@ -158,7 +151,7 @@ public class LoginUserQueryValidatorTests public void Validate_WhenTotpCodeIsInvalid_ShouldHaveValidationError(string totpCode) { // Arrange - LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + LoginUserQuery query = _loginUserQueryFixture.Create(); query = query with { TotpCode = totpCode }; // Act @@ -175,7 +168,7 @@ public class LoginUserQueryValidatorTests public void Validate_WhenTotpCodeIsValid_ShouldNotHaveValidationError(string totpCode) { // Arrange - LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + LoginUserQuery query = _loginUserQueryFixture.Create(); query = query with { TotpCode = totpCode }; // Act @@ -189,7 +182,7 @@ public class LoginUserQueryValidatorTests public void Validate_WhenTotpCodeIsNull_ShouldNotHaveValidationError() { // Arrange - LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + LoginUserQuery query = _loginUserQueryFixture.Create(); query = query with { TotpCode = null }; // Act @@ -203,7 +196,7 @@ public class LoginUserQueryValidatorTests public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError() { // Arrange - LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(true); + LoginUserQuery query = _loginUserQueryFixture.Create(includeTotpCode: true); // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/Fixtures/UpdateUserRoleAndPermissionsCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/Fixtures/UpdateUserRoleAndPermissionsCommandFixture.cs deleted file mode 100644 index a5e41ac0..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/Fixtures/UpdateUserRoleAndPermissionsCommandFixture.cs +++ /dev/null @@ -1,36 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class UpdateUserRoleAndPermissionsCommandFixture -{ - /// - /// Creates a random valid command to update user role and permissions. - /// - /// Optional role ID to assign. If null, no role will be assigned. - /// The number of permissions to generate. - /// The created command. - public UpdateUserRoleAndPermissionsCommand CreateCommand(Guid? roleId = null, int permissionCount = 3) - { - return new Faker() - .CustomInstantiator(f => new UpdateUserRoleAndPermissionsCommand( - Guid.NewGuid(), - roleId, - default!)) - .RuleFor(x => x.Permissions, f => Enumerable.Range(0, permissionCount) - .Select(_ => Guid.NewGuid()) - .ToList()) - .Generate(); - } -} - diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs index 1a4743ce..3766c137 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs @@ -8,8 +8,8 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; -using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; -using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions.Fixtures; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; @@ -39,7 +39,8 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests private readonly IRoleRepository _mockRoleRepository; private readonly IPermissionRepository _mockPermissionRepository; private readonly UpdateUserRoleAndPermissionsCommandHandler _sut; - private readonly UpdateUserRoleAndPermissionsCommandFixture _updateUserRoleAndPermissionsCommandFixture; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly UpdateUserRoleAndPermissionsCommandFixture _updateUserRoleAndPermissionsCommandFixture = new(); private readonly Guid _userId; /// @@ -53,7 +54,6 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockUserRepository = Substitute.For(); _mockRoleRepository = Substitute.For(); _mockPermissionRepository = Substitute.For(); - _updateUserRoleAndPermissionsCommandFixture = new UpdateUserRoleAndPermissionsCommandFixture(); _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); @@ -75,7 +75,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange - UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(); + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(false); @@ -92,7 +92,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnUserDoesNotExistError() { // Arrange - UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(); + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) @@ -110,8 +110,8 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests public async Task HandleAsync_WhenRoleDoesNotExist_ShouldReturnRoleNotFoundError() { // Arrange - UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid()); - UserEntity user = UserEntityFixture.CreateUserEntity(); + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid()); + UserEntity user = _userEntityFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); @@ -132,7 +132,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests public async Task HandleAsync_WhenRemovingLastAdmin_ShouldReturnCannotRemoveLastAdminError() { // Arrange - UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid()); + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid()); RoleEntity adminRole = new() { RoleName = "Admin" }; Guid userId = Guid.NewGuid(); @@ -178,8 +178,8 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests public async Task HandleAsync_WhenUpdateFails_ShouldReturnError() { // Arrange - UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid()); - UserEntity user = UserEntityFixture.CreateUserEntity(); + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid()); + UserEntity user = _userEntityFixture.Create(); RoleEntity role = new() { RoleName = "TestRole" }; IEnumerable permissions = command.Permissions.Select(p => new PermissionEntity { Id = p, PermissionName = AuthorizationPermission.CanViewUsers }); @@ -209,7 +209,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccessResponse() { // Arrange - UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid()); + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid()); UserEntity user = new() { Id = command.UserId, @@ -261,7 +261,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests public async Task HandleAsync_WhenGetAllUsersFails_ShouldReturnError() { // Arrange - UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid()); + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid()); UserEntity user = new() { Id = command.UserId, @@ -302,7 +302,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests public async Task HandleAsync_WhenGetPermissionsFails_ShouldReturnError() { // Arrange - UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.CreateCommand(roleId: Guid.NewGuid()); + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid()); UserEntity user = new() { Id = command.UserId, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs index 90f2cfb4..c8c98f9d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandValidatorTests.cs @@ -17,15 +17,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Comman [ExcludeFromCodeCoverage] public class UpdateUserRoleAndPermissionsCommandValidatorTests { - private readonly UpdateUserRoleAndPermissionsCommandValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public UpdateUserRoleAndPermissionsCommandValidatorTests() - { - _validator = new UpdateUserRoleAndPermissionsCommandValidator(); - } + private readonly UpdateUserRoleAndPermissionsCommandValidator _validator = new(); [Fact] public void Validate_WhenUserIdIsEmpty_ShouldHaveValidationError() diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs index 757a8c49..49ac51ec 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryHandlerTests.cs @@ -5,7 +5,8 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; -using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization.Fixtures; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Queries.GetAuthorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -26,6 +27,8 @@ public class GetAuthorizationQueryHandlerTests private readonly IAuthorizationService _mockAuthorizationService; private readonly ICurrentUserService _mockCurrentUserService; private readonly GetAuthorizationQueryHandler _sut; + private readonly GetAuthorizationQueryFixture _getAuthorizationQueryFixture = new(); + private readonly UserAuthorizationEntityFixture _userAuthorizationEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -45,8 +48,8 @@ public class GetAuthorizationQueryHandlerTests { // Arrange Guid userId = Guid.NewGuid(); - GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(userId); - UserAuthorizationEntity authEntity = GetAuthorizationQueryFixture.CreateUserAuthorizationEntity(userId); + GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create(userId); + UserAuthorizationEntity authEntity = _userAuthorizationEntityFixture.Create(userId); _mockCurrentUserService.UserId.Returns(userId); _mockAuthorizationService.GetUserAuthorizationAsync(userId, Arg.Any()) @@ -68,9 +71,9 @@ public class GetAuthorizationQueryHandlerTests // Arrange Guid adminUserId = Guid.NewGuid(); Guid targetUserId = Guid.NewGuid(); - GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(targetUserId); - UserAuthorizationEntity adminAuthEntity = GetAuthorizationQueryFixture.CreateUserAuthorizationEntity(adminUserId, true); - UserAuthorizationEntity targetAuthEntity = GetAuthorizationQueryFixture.CreateUserAuthorizationEntity(targetUserId); + GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create(targetUserId); + UserAuthorizationEntity adminAuthEntity = _userAuthorizationEntityFixture.Create(adminUserId, true); + UserAuthorizationEntity targetAuthEntity = _userAuthorizationEntityFixture.Create(targetUserId); _mockCurrentUserService.UserId.Returns(adminUserId); _mockAuthorizationService.GetUserAuthorizationAsync(adminUserId, Arg.Any()) @@ -94,8 +97,8 @@ public class GetAuthorizationQueryHandlerTests // Arrange Guid currentUserId = Guid.NewGuid(); Guid targetUserId = Guid.NewGuid(); - GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(targetUserId); - UserAuthorizationEntity currentUserAuth = GetAuthorizationQueryFixture.CreateUserAuthorizationEntity(currentUserId, false); + GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create(targetUserId); + UserAuthorizationEntity currentUserAuth = _userAuthorizationEntityFixture.Create(currentUserId, false); _mockCurrentUserService.UserId.Returns(currentUserId); _mockAuthorizationService.GetUserAuthorizationAsync(currentUserId, Arg.Any()) @@ -115,7 +118,7 @@ public class GetAuthorizationQueryHandlerTests // Arrange Guid currentUserId = Guid.NewGuid(); Guid targetUserId = Guid.NewGuid(); - GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(targetUserId); + GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create(targetUserId); Error error = Error.Failure("Database.Error", "Failed to get user authorization"); _mockCurrentUserService.UserId.Returns(currentUserId); @@ -136,8 +139,8 @@ public class GetAuthorizationQueryHandlerTests // Arrange Guid adminUserId = Guid.NewGuid(); Guid targetUserId = Guid.NewGuid(); - GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(targetUserId); - UserAuthorizationEntity adminAuthEntity = GetAuthorizationQueryFixture.CreateUserAuthorizationEntity(adminUserId, true); + GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create(targetUserId); + UserAuthorizationEntity adminAuthEntity = _userAuthorizationEntityFixture.Create(adminUserId, true); Error error = Error.Failure("Database.Error", "Failed to get target user authorization"); _mockCurrentUserService.UserId.Returns(adminUserId); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidatorTests.cs index 77e0cee1..4831a89b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetAuthorization/GetAuthorizationQueryValidatorTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; +using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Queries.GetAuthorization; using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization.Fixtures; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using System; @@ -17,21 +17,14 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Querie [ExcludeFromCodeCoverage] public class GetAuthorizationQueryValidatorTests { - private readonly GetAuthorizationQueryValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public GetAuthorizationQueryValidatorTests() - { - _validator = new GetAuthorizationQueryValidator(); - } + private readonly GetAuthorizationQueryValidator _validator = new(); + private readonly GetAuthorizationQueryFixture _getAuthorizationQueryFixture = new(); [Fact] public void Validate_WhenUserIdIsNull_ShouldHaveValidationError() { // Arrange - GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(); + GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create(); query = query with { UserId = null }; // Act @@ -45,7 +38,7 @@ public class GetAuthorizationQueryValidatorTests public void Validate_WhenUserIdIsEmpty_ShouldHaveValidationError() { // Arrange - GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(); + GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create(); query = query with { UserId = Guid.Empty }; // Act @@ -59,7 +52,7 @@ public class GetAuthorizationQueryValidatorTests public void Validate_WhenUserIdIsValid_ShouldNotHaveValidationError() { // Arrange - GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery(); + GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create(); // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs index 4477dbeb..7a249c4d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs @@ -7,7 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; -using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetUserPermissions.Fixtures; +using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Queries.GetUserPermissions; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; @@ -33,7 +33,7 @@ public class GetUserPermissionsQueryHandlerTests private readonly ICurrentUserService _mockCurrentUserService; private readonly IUserRepository _mockUserRepository; private readonly GetUserPermissionsQueryHandler _sut; - private readonly GetUserPermissionsQueryFixture _getUserPermissionsQueryFixture; + private readonly GetUserPermissionsQueryFixture _getUserPermissionsQueryFixture = new(); private readonly Guid _userId; /// @@ -45,7 +45,6 @@ public class GetUserPermissionsQueryHandlerTests _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockUserRepository = Substitute.For(); - _getUserPermissionsQueryFixture = new GetUserPermissionsQueryFixture(); _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); @@ -65,7 +64,7 @@ public class GetUserPermissionsQueryHandlerTests public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange - GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.CreateQuery(); + GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(false); @@ -82,7 +81,7 @@ public class GetUserPermissionsQueryHandlerTests public async Task HandleAsync_WhenGetUserByIdFails_ShouldReturnError() { // Arrange - GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.CreateQuery(); + GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get user"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -102,7 +101,7 @@ public class GetUserPermissionsQueryHandlerTests public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnUsernameDoesNotExistError() { // Arrange - GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.CreateQuery(); + GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); @@ -121,7 +120,7 @@ public class GetUserPermissionsQueryHandlerTests public async Task HandleAsync_WhenUserHasPermissions_ShouldReturnPermissions() { // Arrange - GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.CreateQuery(); + GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.Create(); UserEntity user = new() { Id = query.UserId!.Value, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs index 74faf8e4..9b8f07e5 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryValidatorTests.cs @@ -16,15 +16,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Querie [ExcludeFromCodeCoverage] public class GetUserPermissionsQueryValidatorTests { - private readonly GetUserPermissionsQueryValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public GetUserPermissionsQueryValidatorTests() - { - _validator = new GetUserPermissionsQueryValidator(); - } + private readonly GetUserPermissionsQueryValidator _validator = new(); [Fact] public void Validate_WhenUserIdIsNull_ShouldHaveValidationError() diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs index 1d14308d..8b79af52 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs @@ -7,8 +7,8 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; -using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; -using Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetUserRole.Fixtures; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Queries.GetUserRole; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -31,7 +31,8 @@ public class GetUserRoleQueryHandlerTests private readonly ICurrentUserService _mockCurrentUserService; private readonly IUserRepository _mockUserRepository; private readonly GetUserRoleQueryHandler _sut; - private readonly GetUserRoleQueryFixture _getUserRoleQueryFixture; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly GetUserRoleQueryFixture _getUserRoleQueryFixture = new(); private readonly Guid _userId; /// @@ -43,7 +44,6 @@ public class GetUserRoleQueryHandlerTests _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockUserRepository = Substitute.For(); - _getUserRoleQueryFixture = new GetUserRoleQueryFixture(); _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); @@ -63,7 +63,7 @@ public class GetUserRoleQueryHandlerTests public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange - GetUserRoleQuery query = _getUserRoleQueryFixture.CreateQuery(); + GetUserRoleQuery query = _getUserRoleQueryFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(false); @@ -80,7 +80,7 @@ public class GetUserRoleQueryHandlerTests public async Task HandleAsync_WhenGetUserByIdFails_ShouldReturnError() { // Arrange - GetUserRoleQuery query = _getUserRoleQueryFixture.CreateQuery(); + GetUserRoleQuery query = _getUserRoleQueryFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get user"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -100,7 +100,7 @@ public class GetUserRoleQueryHandlerTests public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnUsernameDoesNotExistError() { // Arrange - GetUserRoleQuery query = _getUserRoleQueryFixture.CreateQuery(); + GetUserRoleQuery query = _getUserRoleQueryFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); @@ -119,8 +119,8 @@ public class GetUserRoleQueryHandlerTests public async Task HandleAsync_WhenUserHasNoRole_ShouldReturnNull() { // Arrange - GetUserRoleQuery query = _getUserRoleQueryFixture.CreateQuery(); - UserEntity user = UserEntityFixture.CreateUserEntity(); + GetUserRoleQuery query = _getUserRoleQueryFixture.Create(); + UserEntity user = _userEntityFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); @@ -139,7 +139,7 @@ public class GetUserRoleQueryHandlerTests public async Task HandleAsync_WhenUserHasRole_ShouldReturnRole() { // Arrange - GetUserRoleQuery query = _getUserRoleQueryFixture.CreateQuery(); + GetUserRoleQuery query = _getUserRoleQueryFixture.Create(); UserEntity user = new() { Id = query.UserId!.Value, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs index ecad2004..3212ed10 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryValidatorTests.cs @@ -16,15 +16,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Querie [ExcludeFromCodeCoverage] public class GetUserRoleQueryValidatorTests { - private readonly GetUserRoleQueryValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public GetUserRoleQueryValidatorTests() - { - _validator = new GetUserRoleQueryValidator(); - } + private readonly GetUserRoleQueryValidator _validator = new(); [Fact] public void Validate_WhenUserIdIsNull_ShouldHaveValidationError() diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj b/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj index 6c0665dc..cd947fb9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj @@ -40,6 +40,8 @@ - + + + diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/PermissionRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/PermissionRepositoryTests.cs index 3046e72b..16fdd5a1 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/PermissionRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/PermissionRepositoryTests.cs @@ -2,9 +2,9 @@ using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.Errors; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.DataAccess.Core.Repositories.Authorization; using Lumina.DataAccess.Core.UoW; -using Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; @@ -26,7 +26,7 @@ public class PermissionRepositoryTests { private readonly LuminaDbContext _mockContext; private readonly PermissionRepository _sut; - private readonly PermissionEntityFixture _permissionEntityFixture; + private readonly PermissionEntityFixture _permissionEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -35,14 +35,13 @@ public class PermissionRepositoryTests { _mockContext = Create.MockedDbContextFor(); _sut = new PermissionRepository(_mockContext); - _permissionEntityFixture = new PermissionEntityFixture(); } [Fact] public async Task InsertAsync_WhenPermissionDoesNotExist_ShouldAddPermissionToContextAndReturnCreated() { // Arrange - PermissionEntity permissionModel = _permissionEntityFixture.CreatePermissionModel(); + PermissionEntity permissionModel = _permissionEntityFixture.Create(); // Act Result result = await _sut.InsertAsync(permissionModel, CancellationToken.None); @@ -61,7 +60,7 @@ public class PermissionRepositoryTests public async Task InsertAsync_WhenPermissionAlreadyExists_ShouldReturnError() { // Arrange - PermissionEntity permissionModel = _permissionEntityFixture.CreatePermissionModel(); + PermissionEntity permissionModel = _permissionEntityFixture.Create(); _mockContext.Permissions.Add(permissionModel); await _mockContext.SaveChangesAsync(); @@ -79,12 +78,7 @@ public class PermissionRepositoryTests public async Task GetAllAsync_WhenPermissionsExist_ShouldReturnAllPermissions() { // Arrange - List permissions = - [ - _permissionEntityFixture.CreatePermissionModel(), - _permissionEntityFixture.CreatePermissionModel(), - _permissionEntityFixture.CreatePermissionModel() - ]; + List permissions = _permissionEntityFixture.CreateMany(3); _mockContext.Permissions.AddRange(permissions); await _mockContext.SaveChangesAsync(); @@ -114,12 +108,7 @@ public class PermissionRepositoryTests public async Task GetByIdsAsync_WhenPermissionsExist_ShouldReturnMatchingPermissions() { // Arrange - List permissions = - [ - _permissionEntityFixture.CreatePermissionModel(), - _permissionEntityFixture.CreatePermissionModel(), - _permissionEntityFixture.CreatePermissionModel() - ]; + List permissions = _permissionEntityFixture.CreateMany(3); _mockContext.Permissions.AddRange(permissions); await _mockContext.SaveChangesAsync(); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RolePermissionRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RolePermissionRepositoryTests.cs index 8051d0c4..76186782 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RolePermissionRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RolePermissionRepositoryTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.DataAccess.Core.Repositories.Authorization; using Lumina.DataAccess.Core.UoW; -using Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; @@ -23,7 +23,7 @@ public class RolePermissionRepositoryTests { private readonly LuminaDbContext _mockContext; private readonly RolePermissionRepository _sut; - private readonly RolePermissionEntityFixture _rolePermissionEntityFixture; + private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -32,14 +32,13 @@ public class RolePermissionRepositoryTests { _mockContext = Create.MockedDbContextFor(); _sut = new RolePermissionRepository(_mockContext); - _rolePermissionEntityFixture = new RolePermissionEntityFixture(); } [Fact] public async Task InsertAsync_WhenCalled_ShouldAddRolePermissionToContextAndReturnCreated() { // Arrange - RolePermissionEntity rolePermissionModel = _rolePermissionEntityFixture.CreateRolePermissionModel(); + RolePermissionEntity rolePermissionModel = _rolePermissionEntityFixture.Create(); // Act Result result = await _sut.InsertAsync(rolePermissionModel, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs index a2c55da3..61989f15 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs @@ -2,9 +2,9 @@ using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.Errors; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.DataAccess.Core.Repositories.Authorization; using Lumina.DataAccess.Core.UoW; -using Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; @@ -212,7 +212,7 @@ public class RoleRepositoryTests { // Arrange RolePermissionEntityFixture rolePermissionFixture = new(); - RolePermissionEntity rolePermission = rolePermissionFixture.CreateRolePermissionModel(); + RolePermissionEntity rolePermission = rolePermissionFixture.Create(); RoleEntity role = rolePermission.Role; _mockContext.Roles.Add(role); @@ -307,14 +307,14 @@ public class RoleRepositoryTests { // Arrange RolePermissionEntityFixture rolePermissionFixture = new(); - RolePermissionEntity rolePermission = rolePermissionFixture.CreateRolePermissionModel(); + RolePermissionEntity rolePermission = rolePermissionFixture.Create(); RoleEntity existingRole = rolePermission.Role; existingRole.RolePermissions = [rolePermission]; _mockContext.Roles.Add(existingRole); await _mockContext.SaveChangesAsync(); - RolePermissionEntity newRolePermission = rolePermissionFixture.CreateRolePermissionModel(); + RolePermissionEntity newRolePermission = rolePermissionFixture.Create(); RoleEntity updatedRole = new() { Id = existingRole.Id, @@ -387,7 +387,7 @@ public class RoleRepositoryTests { // Arrange RolePermissionEntityFixture rolePermissionFixture = new(); - RolePermissionEntity rolePermission = rolePermissionFixture.CreateRolePermissionModel(); + RolePermissionEntity rolePermission = rolePermissionFixture.Create(); RoleEntity existingRole = rolePermission.Role; existingRole.RolePermissions = [rolePermission]; diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/UserRoleRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/UserRoleRepositoryTests.cs index 825634f9..55ca950d 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/UserRoleRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/UserRoleRepositoryTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.DataAccess.Core.Repositories.Authorization; using Lumina.DataAccess.Core.UoW; -using Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; @@ -23,7 +23,7 @@ public class UserRoleRepositoryTests { private readonly LuminaDbContext _mockContext; private readonly UserRoleRepository _sut; - private readonly UserRoleEntityFixture _userRoleEntityFixture; + private readonly UserRoleEntityFixture _userRoleEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -32,14 +32,13 @@ public class UserRoleRepositoryTests { _mockContext = Create.MockedDbContextFor(); _sut = new UserRoleRepository(_mockContext); - _userRoleEntityFixture = new UserRoleEntityFixture(); } [Fact] public async Task InsertAsync_WhenUserRoleIsValid_ShouldAddToContextAndReturnCreated() { // Arrange - UserRoleEntity userRole = _userRoleEntityFixture.CreateUserRoleModel(); + UserRoleEntity userRole = _userRoleEntityFixture.Create(); // Act Result result = await _sut.InsertAsync(userRole, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs index d38f4cdc..a5d2b1ab 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -2,9 +2,9 @@ using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.DataAccess.Core.Repositories.Books; using Lumina.DataAccess.Core.UoW; -using Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; @@ -28,7 +28,7 @@ public class BookRepositoryTests { private readonly LuminaDbContext _mockContext; private readonly BookRepository _sut; - private readonly BookEntityFixture _bookEntityFixture; + private readonly BookEntityFixture _bookEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -37,14 +37,13 @@ public class BookRepositoryTests { _mockContext = Create.MockedDbContextFor(); _sut = new BookRepository(_mockContext); - _bookEntityFixture = new BookEntityFixture(); } [Fact] public async Task InsertAsync_WhenBookDoesNotExist_ShouldAddBookToContextAndReturnCreated() { // Arrange - BookEntity bookModel = _bookEntityFixture.CreateBookModel(); + BookEntity bookModel = _bookEntityFixture.Create(); // Act Result result = await _sut.InsertAsync(bookModel, CancellationToken.None); @@ -63,7 +62,7 @@ public class BookRepositoryTests public async Task InsertAsync_WhenBookAlreadyExists_ShouldReturnError() { // Arrange - BookEntity bookModel = _bookEntityFixture.CreateBookModel(); + BookEntity bookModel = _bookEntityFixture.Create(); _mockContext.Books.Add(bookModel); await _mockContext.SaveChangesAsync(); @@ -85,7 +84,7 @@ public class BookRepositoryTests _mockContext.Set().Add(existingTag); await _mockContext.SaveChangesAsync(); - BookEntity bookModel = _bookEntityFixture.CreateBookModel(); + BookEntity bookModel = _bookEntityFixture.Create(); bookModel.Tags = [new("Existing"), new("New")]; // Act @@ -112,7 +111,7 @@ public class BookRepositoryTests _mockContext.Set().Add(existingGenre); await _mockContext.SaveChangesAsync(); - BookEntity bookModel = _bookEntityFixture.CreateBookModel(); + BookEntity bookModel = _bookEntityFixture.Create(); bookModel.Genres = [new("Existing"), new("New")]; // Act @@ -135,12 +134,7 @@ public class BookRepositoryTests public async Task GetAllAsync_WhenCalled_ShouldReturnAllBooks() { // Arrange - List books = - [ - _bookEntityFixture.CreateBookModel(), - _bookEntityFixture.CreateBookModel(), - _bookEntityFixture.CreateBookModel() - ]; + List books = _bookEntityFixture.CreateMany(3); _mockContext.Books.AddRange(books); await _mockContext.SaveChangesAsync(); @@ -170,7 +164,7 @@ public class BookRepositoryTests public async Task GetAllAsync_WhenCalled_ShouldIncludeRelatedEntities() { // Arrange - BookEntity book = _bookEntityFixture.CreateBookModel(); + BookEntity book = _bookEntityFixture.Create(); book.Tags = [new TagEntity("Tag1"), new TagEntity("Tag2")]; book.Genres = [new GenreEntity("Genre1"), new GenreEntity("Genre2")]; book.ISBNs = [new IsbnEntity("1234567890", IsbnFormat.Isbn10), new IsbnEntity("1234567890123", IsbnFormat.Isbn13)]; @@ -195,9 +189,9 @@ public class BookRepositoryTests { // Arrange Guid libraryId = Guid.NewGuid(); - BookEntity bookOfLibrary = _bookEntityFixture.CreateBookModel(); + BookEntity bookOfLibrary = _bookEntityFixture.Create(); bookOfLibrary.LibraryId = libraryId; - BookEntity bookOfAnotherLibrary = _bookEntityFixture.CreateBookModel(); + BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); _mockContext.Books.AddRange(bookOfLibrary, bookOfAnotherLibrary); await _mockContext.SaveChangesAsync(); @@ -215,7 +209,7 @@ public class BookRepositoryTests public async Task GetByPathAsync_WhenBookExists_ShouldReturnTheBook() { // Arrange - BookEntity book = _bookEntityFixture.CreateBookModel(); + BookEntity book = _bookEntityFixture.Create(); _mockContext.Books.Add(book); await _mockContext.SaveChangesAsync(); @@ -231,7 +225,7 @@ public class BookRepositoryTests public async Task GetByPathAsync_WhenBookDoesNotExist_ShouldReturnNull() { // Arrange - BookEntity book = _bookEntityFixture.CreateBookModel(); + BookEntity book = _bookEntityFixture.Create(); _mockContext.Books.Add(book); await _mockContext.SaveChangesAsync(); @@ -248,19 +242,19 @@ public class BookRepositoryTests { // Arrange Guid libraryId = Guid.NewGuid(); - BookEntity pendingBook = _bookEntityFixture.CreateBookModel(); + BookEntity pendingBook = _bookEntityFixture.Create(); pendingBook.LibraryId = libraryId; pendingBook.Path = "/books/a.epub"; pendingBook.MetadataStatus = MetadataStatus.Pending; - BookEntity enrichedBook = _bookEntityFixture.CreateBookModel(); + BookEntity enrichedBook = _bookEntityFixture.Create(); enrichedBook.LibraryId = libraryId; enrichedBook.Path = "/books/b.epub"; enrichedBook.MetadataStatus = MetadataStatus.Enriched; - BookEntity failedBook = _bookEntityFixture.CreateBookModel(); + BookEntity failedBook = _bookEntityFixture.Create(); failedBook.LibraryId = libraryId; failedBook.Path = "/books/c.epub"; failedBook.MetadataStatus = MetadataStatus.Failed; - BookEntity bookOfAnotherLibrary = _bookEntityFixture.CreateBookModel(); + BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Pending; _mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary); @@ -281,10 +275,10 @@ public class BookRepositoryTests { // Arrange Guid libraryId = Guid.NewGuid(); - BookEntity firstBook = _bookEntityFixture.CreateBookModel(); + BookEntity firstBook = _bookEntityFixture.Create(); firstBook.LibraryId = libraryId; firstBook.Path = "/books/a.epub"; - BookEntity secondBook = _bookEntityFixture.CreateBookModel(); + BookEntity secondBook = _bookEntityFixture.Create(); secondBook.LibraryId = libraryId; secondBook.Path = "/books/b.epub"; _mockContext.Books.AddRange(firstBook, secondBook); @@ -303,7 +297,7 @@ public class BookRepositoryTests public async Task UpdateAsync_WhenBookExists_ShouldUpdateItsScalarProperties() { // Arrange - BookEntity book = _bookEntityFixture.CreateBookModel(); + BookEntity book = _bookEntityFixture.Create(); _mockContext.Books.Add(book); await _mockContext.SaveChangesAsync(); @@ -323,7 +317,7 @@ public class BookRepositoryTests public async Task UpdateAsync_WhenBookDoesNotExist_ShouldReturnError() { // Arrange - BookEntity book = _bookEntityFixture.CreateBookModel(); + BookEntity book = _bookEntityFixture.Create(); // Act Result result = await _sut.UpdateAsync(book, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs index 5acb3fee..9821f0f5 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.DataAccess.Core.Repositories.Plugins; using Lumina.DataAccess.Core.UoW; -using Lumina.DataAccess.UnitTests.Core.Repositories.Plugins.Fixtures; using Lumina.Domain.Common.Primitives; using System; using System.Linq; @@ -20,7 +20,7 @@ public class LibraryMetadataProviderConfigurationRepositoryTests { private readonly LuminaDbContext _mockContext; private readonly LibraryMetadataProviderConfigurationRepository _sut; - private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationFixture; + private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationFixture = new(); /// /// Initializes a new instance of the class. @@ -29,7 +29,6 @@ public class LibraryMetadataProviderConfigurationRepositoryTests { _mockContext = Create.MockedDbContextFor(); _sut = new LibraryMetadataProviderConfigurationRepository(_mockContext); - _configurationFixture = new LibraryMetadataProviderConfigurationEntityFixture(); } [Fact] @@ -37,8 +36,8 @@ public class LibraryMetadataProviderConfigurationRepositoryTests { // Arrange Guid libraryId = Guid.NewGuid(); - LibraryMetadataProviderConfigurationEntity configurationOfLibrary = _configurationFixture.CreateConfiguration(libraryId, Guid.NewGuid(), 1); - LibraryMetadataProviderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.CreateConfiguration(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity configurationOfLibrary = _configurationFixture.Create(libraryId, Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); _mockContext.LibraryMetadataProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary); await _mockContext.SaveChangesAsync(); @@ -55,7 +54,7 @@ public class LibraryMetadataProviderConfigurationRepositoryTests public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationExists_ShouldReturnIt() { // Arrange - LibraryMetadataProviderConfigurationEntity configuration = _configurationFixture.CreateConfiguration(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); _mockContext.LibraryMetadataProviderConfigurations.Add(configuration); await _mockContext.SaveChangesAsync(); @@ -71,7 +70,7 @@ public class LibraryMetadataProviderConfigurationRepositoryTests public async Task UpsertAsync_WhenConfigurationDoesNotExist_ShouldInsertIt() { // Arrange - LibraryMetadataProviderConfigurationEntity configuration = _configurationFixture.CreateConfiguration(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); // Act Result result = await _sut.UpsertAsync(configuration, CancellationToken.None); @@ -86,11 +85,11 @@ public class LibraryMetadataProviderConfigurationRepositoryTests public async Task UpsertAsync_WhenConfigurationExists_ShouldUpdateIt() { // Arrange - LibraryMetadataProviderConfigurationEntity configuration = _configurationFixture.CreateConfiguration(Guid.NewGuid(), Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); _mockContext.LibraryMetadataProviderConfigurations.Add(configuration); await _mockContext.SaveChangesAsync(); - LibraryMetadataProviderConfigurationEntity updatedConfiguration = _configurationFixture.CreateConfiguration(configuration.LibraryId, configuration.PluginId, 5); + LibraryMetadataProviderConfigurationEntity updatedConfiguration = _configurationFixture.Create(configuration.LibraryId, configuration.PluginId, 5); updatedConfiguration.IsEnabled = true; // Act diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs index 4f110480..0730c42e 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.DataAccess.Core.Repositories.Plugins; using Lumina.DataAccess.Core.UoW; -using Lumina.DataAccess.UnitTests.Core.Repositories.Plugins.Fixtures; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using System; @@ -21,7 +21,7 @@ public class PluginRepositoryTests { private readonly LuminaDbContext _mockContext; private readonly PluginRepository _sut; - private readonly PluginEntityFixture _pluginFixture; + private readonly PluginEntityFixture _pluginFixture = new(); /// /// Initializes a new instance of the class. @@ -30,14 +30,13 @@ public class PluginRepositoryTests { _mockContext = Create.MockedDbContextFor(); _sut = new PluginRepository(_mockContext); - _pluginFixture = new PluginEntityFixture(); } [Fact] public async Task GetByIdAsync_WhenPluginExists_ShouldReturnIt() { // Arrange - PluginEntity plugin = _pluginFixture.CreatePluginEntity(); + PluginEntity plugin = _pluginFixture.Create(); _mockContext.Plugins.Add(plugin); await _mockContext.SaveChangesAsync(); @@ -53,7 +52,7 @@ public class PluginRepositoryTests public async Task UpsertAsync_WhenPluginDoesNotExist_ShouldInsertIt() { // Arrange - PluginEntity plugin = _pluginFixture.CreatePluginEntity(); + PluginEntity plugin = _pluginFixture.Create(); // Act Result result = await _sut.UpsertAsync(plugin, CancellationToken.None); @@ -68,12 +67,12 @@ public class PluginRepositoryTests public async Task UpsertAsync_WhenPluginExists_ShouldUpdateDetectionFieldsAndPreserveSettings() { // Arrange - PluginEntity plugin = _pluginFixture.CreatePluginEntity(); + PluginEntity plugin = _pluginFixture.Create(); plugin.SettingsJson = """{"preferredLanguage":"en"}"""; _mockContext.Plugins.Add(plugin); await _mockContext.SaveChangesAsync(); - PluginEntity updatedPlugin = _pluginFixture.CreatePluginEntity(plugin.Id); + PluginEntity updatedPlugin = _pluginFixture.Create(plugin.Id); updatedPlugin.Name = "Updated Name"; updatedPlugin.SettingsJson = null; // the stored settings must be preserved @@ -92,7 +91,7 @@ public class PluginRepositoryTests public async Task UpdateSettingsAsync_WhenPluginExists_ShouldUpdateItsSettings() { // Arrange - PluginEntity plugin = _pluginFixture.CreatePluginEntity(); + PluginEntity plugin = _pluginFixture.Create(); _mockContext.Plugins.Add(plugin); await _mockContext.SaveChangesAsync(); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/Fixtures/UserEntityFixture.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/Fixtures/UserEntityFixture.cs deleted file mode 100644 index c591c735..00000000 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/Fixtures/UserEntityFixture.cs +++ /dev/null @@ -1,118 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using Bogus; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Users.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class UserEntityFixture -{ - private readonly Fixture _fixture; - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public UserEntityFixture() - { - _fixture = new Fixture(); - _faker = new Faker(); - ConfigureCustomTypes(); - } - - /// - /// Creates a random valid . - /// - /// The created . - public UserEntity CreateUserModel() - { - Guid userId = _faker.Random.Guid(); - - return new Faker() - .RuleFor(x => x.Id, _ => userId) - .RuleFor(x => x.Username, f => f.Internet.UserName()) - .RuleFor(x => x.Password, f => f.Internet.Password(12)) - .RuleFor(x => x.TempPassword, f => f.Random.Bool() ? f.Internet.Password(8) : null) - .RuleFor(x => x.TotpSecret, f => f.Random.Bool() ? f.Random.String2(32, "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567") : null) - .RuleFor(x => x.TempPasswordCreated, (f, u) => u.TempPassword != null ? f.Date.Past() : null) - .RuleFor(x => x.Libraries, _ => CreateLibraries(_faker.Random.Number(1, 3), userId)) - .RuleFor(x => x.CreatedOnUtc, f => f.Date.Past()) - .RuleFor(x => x.CreatedBy, _ => userId) - .RuleFor(x => x.UpdatedOnUtc, f => f.Random.Bool() ? f.Date.Recent() : null) - .RuleFor(x => x.UpdatedBy, _ => userId) - .Generate(); - } - - /// - /// Creates a valid collection of user libraries. - /// - /// The number of user libraries to create. - /// The unique identifier of the user for whom to create the libraries. - /// A collection of . - private static List CreateLibraries(int count, Guid userId) - { - return new Faker() - .CustomInstantiator(f => new LibraryEntity - { - Id = f.Random.Guid(), - UserId = userId, - Title = f.Random.String2(f.Random.Number(1, 50)), - LibraryType = f.PickRandom(), - ContentLocations = CreateContentLocations(f.Random.Number(1, 3)), - CreatedOnUtc = f.Date.Past(), - CreatedBy = userId, - UpdatedOnUtc = f.Random.Bool() ? f.Date.Recent() : null, - UpdatedBy = f.Random.Bool() ? userId : null, - }) - .Generate(count); - } - - /// - /// Creates a valid collection of media paths for a library. - /// - /// The number of media library contents to create. - /// A collection of . - private static List CreateContentLocations(int count) - { - return new Faker() - .CustomInstantiator(f => new LibraryContentLocationEntity - { - Path = f.System.FilePath() - }) - .Generate(count); - } - - /// - /// Configures custom type generation rules for the AutoFixture instance. - /// - private void ConfigureCustomTypes() - { - _fixture.Register(() => new LibraryEntity - { - Id = _fixture.Create(), - UserId = _fixture.Create(), - Title = _fixture.Create(), - LibraryType = _fixture.Create(), - ContentLocations = [], - CreatedOnUtc = _fixture.Create(), - CreatedBy = _fixture.Create(), - UpdatedOnUtc = _fixture.Create(), - UpdatedBy = _fixture.Create() - }); - - _fixture.Register(() => new LibraryContentLocationEntity - { - Path = _fixture.Create() - }); - } -} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs index 0553791d..2595091e 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs @@ -2,10 +2,10 @@ using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.DataAccess.Core.Repositories.Users; using Lumina.DataAccess.Core.UoW; -using Lumina.DataAccess.UnitTests.Core.Repositories.Authorization.Fixtures; -using Lumina.DataAccess.UnitTests.Core.Repositories.Users.Fixtures; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; @@ -28,8 +28,8 @@ public class UserRepositoryTests { private readonly LuminaDbContext _mockContext; private readonly UserRepository _sut; - private readonly UserEntityFixture _userEntityFixture; - private readonly PermissionEntityFixture _permissionEntityFixture; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -38,15 +38,13 @@ public class UserRepositoryTests { _mockContext = Create.MockedDbContextFor(); _sut = new UserRepository(_mockContext); - _userEntityFixture = new UserEntityFixture(); - _permissionEntityFixture = new PermissionEntityFixture(); } [Fact] public async Task InsertAsync_WhenUserDoesNotExist_ShouldAddUserToContextAndReturnCreated() { // Arrange - UserEntity userModel = _userEntityFixture.CreateUserModel(); + UserEntity userModel = _userEntityFixture.Create(); // Act Result result = await _sut.InsertAsync(userModel, CancellationToken.None); @@ -64,7 +62,7 @@ public class UserRepositoryTests public async Task InsertAsync_WhenUserAlreadyExists_ShouldReturnError() { // Arrange - UserEntity userModel = _userEntityFixture.CreateUserModel(); + UserEntity userModel = _userEntityFixture.Create(); _mockContext.Users.Add(userModel); await _mockContext.SaveChangesAsync(); @@ -82,12 +80,7 @@ public class UserRepositoryTests public async Task GetAllAsync_WhenCalled_ShouldReturnAllUsers() { // Arrange - List users = - [ - _userEntityFixture.CreateUserModel(), - _userEntityFixture.CreateUserModel(), - _userEntityFixture.CreateUserModel() - ]; + List users = _userEntityFixture.CreateMany(); _mockContext.Users.AddRange(users); await _mockContext.SaveChangesAsync(); @@ -117,7 +110,7 @@ public class UserRepositoryTests public async Task GetByUsernameAsync_WhenUserExists_ShouldReturnUser() { // Arrange - UserEntity userModel = _userEntityFixture.CreateUserModel(); + UserEntity userModel = _userEntityFixture.Create(); _mockContext.Users.Add(userModel); await _mockContext.SaveChangesAsync(); @@ -145,7 +138,7 @@ public class UserRepositoryTests public async Task UpdateAsync_WhenUserExists_ShouldUpdateUserAndReturnUpdated() { // Arrange - UserEntity existingUser = _userEntityFixture.CreateUserModel(); + UserEntity existingUser = _userEntityFixture.Create(); _mockContext.Users.Add(existingUser); await _mockContext.SaveChangesAsync(); @@ -183,7 +176,7 @@ public class UserRepositoryTests public async Task UpdateAsync_WhenUserDoesNotExist_ShouldReturnError() { // Arrange - UserEntity userModel = _userEntityFixture.CreateUserModel(); + UserEntity userModel = _userEntityFixture.Create(); // Act Result result = await _sut.UpdateAsync(userModel, CancellationToken.None); @@ -197,7 +190,7 @@ public class UserRepositoryTests public async Task GetByIdAsync_WhenUserExists_ShouldReturnUserWithAllRelations() { // Arrange - UserEntity userModel = _userEntityFixture.CreateUserModel(); + UserEntity userModel = _userEntityFixture.Create(); _mockContext.Users.Add(userModel); await _mockContext.SaveChangesAsync(); @@ -233,9 +226,9 @@ public class UserRepositoryTests public async Task UpdateAsync_WhenUserExistsWithPermissions_ShouldUpdatePermissionsAndReturnUpdated() { // Arrange - UserEntity existingUser = _userEntityFixture.CreateUserModel(); - PermissionEntity oldPermission = _permissionEntityFixture.CreatePermissionModel(); - PermissionEntity newPermission = _permissionEntityFixture.CreatePermissionModel(); + UserEntity existingUser = _userEntityFixture.Create(); + PermissionEntity oldPermission = _permissionEntityFixture.Create(); + PermissionEntity newPermission = _permissionEntityFixture.Create(); _mockContext.Users.Add(existingUser); _mockContext.Permissions.Add(oldPermission); @@ -291,9 +284,9 @@ public class UserRepositoryTests PermissionEntityFixture permissionFixture = new(); UserPermissionEntityFixture userPermissionFixture = new(); - UserEntity existingUser = userFixture.CreateUserModel(); - PermissionEntity oldPermission = permissionFixture.CreatePermissionModel(); - PermissionEntity newPermission = permissionFixture.CreatePermissionModel(); + UserEntity existingUser = userFixture.Create(); + PermissionEntity oldPermission = permissionFixture.Create(); + PermissionEntity newPermission = permissionFixture.Create(); UserEntity userWithPermissions = new() { @@ -304,7 +297,7 @@ public class UserRepositoryTests UserRole = null, UserPermissions = [ - userPermissionFixture.CreateUserPermissionModel(existingUser, oldPermission) + userPermissionFixture.Create(existingUser, oldPermission) ], CreatedOnUtc = existingUser.CreatedOnUtc, CreatedBy = existingUser.CreatedBy, @@ -324,7 +317,7 @@ public class UserRepositoryTests UserRole = null, UserPermissions = [ - userPermissionFixture.CreateUserPermissionModel(existingUser, newPermission) + userPermissionFixture.Create(existingUser, newPermission) ], CreatedBy = existingUser.CreatedBy, CreatedOnUtc = existingUser.CreatedOnUtc, @@ -464,7 +457,7 @@ public class UserRepositoryTests UserEntityFixture userFixture = new(); UserRoleEntityFixture userRoleFixture = new(); - UserRoleEntity oldUserRole = userRoleFixture.CreateUserRoleModel(); + UserRoleEntity oldUserRole = userRoleFixture.Create(); UserEntity existingUser = new() { diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs index 18d4053b..6c96edc1 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs @@ -6,8 +6,8 @@ using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.DataAccess.Core.Seed; -using Lumina.DataAccess.UnitTests.Core.Repositories.Users.Fixtures; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using NSubstitute; @@ -375,7 +375,7 @@ public class DataSeedServiceTests Guid userId = Guid.NewGuid(); RoleEntity adminRole = new() { Id = Guid.NewGuid(), RoleName = "Admin" }; UserEntityFixture userFixture = new(); - UserEntity adminUser = userFixture.CreateUserModel(); + UserEntity adminUser = userFixture.Create(); // Use the adminUser.Id instead of the randomly generated userId userId = adminUser.Id; @@ -464,7 +464,7 @@ public class DataSeedServiceTests // Arrange Guid userId = Guid.NewGuid(); RoleEntity adminRole = new() { Id = Guid.NewGuid(), RoleName = "Admin" }; - UserEntity adminUser = new UserEntityFixture().CreateUserModel(); + UserEntity adminUser = new UserEntityFixture().Create(); Error expectedError = Error.Failure("UserRole.InsertFailed", "Failed to insert user role"); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj b/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj index 252d8a1e..e8f0da90 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj @@ -42,5 +42,6 @@ + diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/BookLibraryAggregate/Fixtures/BookFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/BookLibraryAggregate/Fixtures/BookFixture.cs deleted file mode 100644 index 32d90ce8..00000000 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/BookLibraryAggregate/Fixtures/BookFixture.cs +++ /dev/null @@ -1,70 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Common.ValueObjects.Metadata; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Domain.UnitTests.Core.Aggregates.BookLibraryAggregate.Fixtures; - -/// -/// Fixture class for the domain entity. -/// -[ExcludeFromCodeCoverage] -public static class BookFixture -{ - /// - /// Creates a valid book domain entity with random data. - /// - /// The created domain entity. - public static Book CreateValidBook() - { - Result bookResult = Book.Create( - LibraryId.Create(Guid.NewGuid()), - "/books/test.epub", - WrittenContentMetadata.Create( - "Test Title", - Optional.None(), - Optional.None(), - ReleaseInfo.Create( - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None() - ).Value, - [], - [], - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None() - ).Value, - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None(), - [], - [], - [] - ); - if (bookResult.IsFailure) - throw new InvalidOperationException("Failed to create a valid book in the test fixture."); - return bookResult.Value; - } -} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/FileFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/FileFixture.cs deleted file mode 100644 index c6ba3b4b..00000000 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/Fixtures/FileFixture.cs +++ /dev/null @@ -1,81 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class FileFixture -{ - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public FileFixture() - { - _faker = new Faker(); - } - - /// - /// Creates a random valid . - /// - /// The created . - public File CreateFile( - string? path = null, - string? name = null, - Optional? dateCreated = null, - Optional? dateModified = null, - long? size = null, - FileSystemItemStatus? status = null) - { - path ??= _faker.System.FilePath(); - name ??= _faker.System.FileName(); - dateCreated ??= Optional.Some(_faker.Date.Past()); - dateModified ??= Optional.Some(_faker.Date.Recent()); - size ??= _faker.Random.Long(); - status ??= _faker.PickRandom(); - - Result fileResult = File.Create(path, name, dateCreated.Value, dateModified.Value, size.Value, status.Value); - - if (fileResult.IsFailure) - throw new InvalidOperationException("Failed to create File: " + string.Join(", ", fileResult.Errors)); - return fileResult.Value; - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => CreateFile())]; - } - - /// - /// Creates a random valid , without creationg and modification dates. - /// - /// - public static File CreateFileWithoutDates() - { - return File.Create( - "/path/to/file_without_dates.txt", - "file_without_dates.txt", - Optional.None(), - Optional.None(), - 2048, - FileSystemItemStatus.Accessible - ).Value; - } -} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs deleted file mode 100644 index 54d2cc01..00000000 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs +++ /dev/null @@ -1,42 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class FileSystemPathIdFixture -{ - private readonly Faker _faker; - - /// - /// Initializes a new instance of the class. - /// - public FileSystemPathIdFixture() - { - _faker = new Faker(); - } - - /// - /// Creates a random valid . - /// - /// The path of the file system path element. - /// The created . - public FileSystemPathId CreateFileSystemPathId(string? path = null) - { - path ??= _faker.System.FilePath(); - - Result fileSystemPathIdResult = FileSystemPathId.Create(path); - - if (fileSystemPathIdResult.IsFailure) - throw new InvalidOperationException("Failed to create FileSystemPathId: " + string.Join(", ", fileSystemPathIdResult.Errors)); - return fileSystemPathIdResult.Value; - } -} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/DirectoryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/DirectoryTests.cs similarity index 95% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/DirectoryTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/DirectoryTests.cs index 5b01e5ca..d7455fcf 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/DirectoryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/DirectoryTests.cs @@ -4,13 +4,13 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Fixtures; using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/FileTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/FileTests.cs similarity index 97% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/FileTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/FileTests.cs index f84c823a..ea5c5af7 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/FileTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/FileTests.cs @@ -8,7 +8,7 @@ using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs similarity index 96% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs index b6e033c7..5a75102c 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs @@ -8,7 +8,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs similarity index 97% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs index b5454ce0..30533f5e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs @@ -9,7 +9,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/FileSystemItemTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/FileSystemItemTests.cs similarity index 88% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/FileSystemItemTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/FileSystemItemTests.cs index e6b09937..ff0b4f5a 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/FileSystemItemTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/FileSystemItemTests.cs @@ -5,13 +5,13 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Fixtures; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; /// /// Contains unit tests for the class. @@ -20,7 +20,7 @@ namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate; public class FileSystemItemTests { private readonly IFixture _fixture; - private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); /// /// Initializes a new instance of the class. @@ -28,14 +28,13 @@ public class FileSystemItemTests public FileSystemItemTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _fileSystemPathIdFixture = new FileSystemPathIdFixture(); } [Fact] public void Constructor_WhenCalled_ShouldSetPropertiesCorrectly() { // Arrange - FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId id = _fileSystemPathIdFixture.Create(); string name = "TestItem"; FileSystemItemType type = FileSystemItemType.File; @@ -101,7 +100,7 @@ public class FileSystemItemTests public void Equals_WithSameId_ShouldReturnTrue() { // Arrange - FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId id = _fileSystemPathIdFixture.Create(); FileSystemItemFixture item1 = CreateFileSystemItemFixture(id); FileSystemItemFixture item2 = CreateFileSystemItemFixture(id); @@ -130,7 +129,7 @@ public class FileSystemItemTests public void GetHashCode_WithSameId_ShouldReturnSameHashCode() { // Arrange - FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId id = _fileSystemPathIdFixture.Create(); FileSystemItemFixture item1 = CreateFileSystemItemFixture(id); FileSystemItemFixture item2 = CreateFileSystemItemFixture(id); @@ -159,7 +158,7 @@ public class FileSystemItemTests private FileSystemItemFixture CreateFileSystemItemFixture(FileSystemPathId? id = null) { - id ??= _fileSystemPathIdFixture.CreateFileSystemPathId(); + id ??= _fileSystemPathIdFixture.Create(); string name = _fixture.Create(); FileSystemItemType type = _fixture.Create(); return new FileSystemItemFixture(id, name, type); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs similarity index 93% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs index 62abd03f..a15c1e44 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs @@ -5,9 +5,9 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.SharedKernel.Common.Enums.Primitives; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using NSubstitute.ExceptionExtensions; using System; @@ -19,7 +19,7 @@ using System.Linq; using System.Runtime.InteropServices; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. @@ -31,7 +31,7 @@ public class DirectoryProviderServiceTests private readonly IFileSystem _mockFileSystem; private readonly IFileSystemPermissionsService _mockFileSystemPermissionsService; private readonly DirectoryProviderService _sut; - private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); private readonly string _pathSource = s_isUnix ? "/Source" : @"C:\Source"; private readonly string _pathSourceSubDir = s_isUnix ? "/Source/SubDir" : @"C:\Source\SubDir"; @@ -65,14 +65,13 @@ public class DirectoryProviderServiceTests _mockFileSystem = Substitute.For(); _mockFileSystemPermissionsService = Substitute.For(); _sut = new DirectoryProviderService(_mockFileSystem, _mockFileSystemPermissionsService); - _fileSystemPathIdFixture = new(); } [Fact] public void GetSubdirectoryPaths_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(false); // Act @@ -87,7 +86,7 @@ public class DirectoryProviderServiceTests public void GetSubdirectoryPaths_WhenUserHasAccess_ShouldReturnSubdirectories() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); string[] subdirectories = [.. _fixture.CreateMany(3)]; _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true); _mockFileSystem.Directory.GetDirectories(path.Path).Returns(subdirectories); @@ -109,7 +108,7 @@ public class DirectoryProviderServiceTests public void GetSubdirectoryPaths_WhenIncludeHiddenElementsIsFalse_ShouldExcludeHiddenDirectories() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); string[] subdirectories = [_pathVisible1, _pathHidden1]; _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true); _mockFileSystem.Directory.GetDirectories(path.Path).Returns(subdirectories); @@ -130,7 +129,7 @@ public class DirectoryProviderServiceTests public void GetSubdirectoryPaths_WhenIncludeHiddenElementsIsTrue_ShouldIncludeHiddenDirectories() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); string[] subdirectories = [_pathVisible1, _pathHidden1]; _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true); _mockFileSystem.Directory.GetDirectories(path.Path).Returns(subdirectories); @@ -154,7 +153,7 @@ public class DirectoryProviderServiceTests public void GetSubdirectoryPaths_WhenGetAttributesThrowsException_ShouldStillAddDirectory() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); string[] subdirectories = [_pathValid1, _pathInvalid1]; _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true); _mockFileSystem.Directory.GetDirectories(path.Path).Returns(subdirectories); @@ -176,7 +175,7 @@ public class DirectoryProviderServiceTests public void GetSubdirectoryPaths_WhenCalled_ShouldOrderDirectoriesAlphabetically() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); string[] subdirectories = s_isUnix ? ["/C", "/A", "/B"] : [@"C:\C", @"C:\A", @"C:\B"]; @@ -200,7 +199,7 @@ public class DirectoryProviderServiceTests public void GetSubdirectoryPaths_WhenDirectoryHasNoSubdirectories_ShouldReturnEmptyList() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true); _mockFileSystem.Directory.GetDirectories(path.Path).Returns([]); @@ -216,7 +215,7 @@ public class DirectoryProviderServiceTests public void DirectoryExists_WhenDirectoryExists_ShouldReturnTrue() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); _mockFileSystem.Directory.Exists(path.Path).Returns(true); // Act @@ -231,7 +230,7 @@ public class DirectoryProviderServiceTests public void DirectoryExists_WhenDirectoryDoesNotExist_ShouldReturnFalse() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); _mockFileSystem.Directory.Exists(path.Path).Returns(false); // Act @@ -249,7 +248,7 @@ public class DirectoryProviderServiceTests string fullPath = s_isUnix ? "/folder/subfolder/file.txt" : @"C:\folder\subfolder\file.txt"; - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(fullPath); + FileSystemPathId path = _fileSystemPathIdFixture.Create(fullPath); _mockFileSystem.Path.GetFileName(fullPath).Returns("file.txt"); // Act @@ -267,7 +266,7 @@ public class DirectoryProviderServiceTests string fullPath = s_isUnix ? "/folder/subfolder/" : @"C:\folder\subfolder\"; - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(fullPath); + FileSystemPathId path = _fileSystemPathIdFixture.Create(fullPath); _mockFileSystem.Path.GetFileName(fullPath[..^1]).Returns("subfolder"); _mockFileSystem.Path.DirectorySeparatorChar.Returns(_dirSeparator); @@ -286,7 +285,7 @@ public class DirectoryProviderServiceTests string fullPath = s_isUnix ? "/C/" : @"/"; - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(fullPath); + FileSystemPathId path = _fileSystemPathIdFixture.Create(fullPath); _mockFileSystem.Path.GetFileName(fullPath[..^1]).Returns(string.Empty); _mockFileSystem.Path.DirectorySeparatorChar.Returns(_dirSeparator); @@ -302,7 +301,7 @@ public class DirectoryProviderServiceTests public void GetLastWriteTime_WhenUserHasAccess_ShouldReturnLastWriteTime() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); DateTime expectedDateTime = DateTime.Now; _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false).Returns(true); _mockFileSystem.Directory.GetLastWriteTime(path.Path).Returns(expectedDateTime); @@ -320,7 +319,7 @@ public class DirectoryProviderServiceTests public void GetLastWriteTime_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false).Returns(false); // Act @@ -335,7 +334,7 @@ public class DirectoryProviderServiceTests public void GetCreationTime_WhenUserHasAccess_ShouldReturnCreationTime() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); DateTime expectedDateTime = DateTime.Now; _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false).Returns(true); _mockFileSystem.Directory.GetCreationTime(path.Path).Returns(expectedDateTime); @@ -353,7 +352,7 @@ public class DirectoryProviderServiceTests public void GetCreationTime_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false).Returns(false); // Act @@ -368,7 +367,7 @@ public class DirectoryProviderServiceTests public void CreateDirectory_WhenUserHasAccess_ShouldCreateDirectoryAndReturnPath() { // Arrange - FileSystemPathId parentPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Parent"); + FileSystemPathId parentPath = _fileSystemPathIdFixture.Create(@"C:\Parent"); string directoryName = "NewDirectory"; string fullPath = s_isUnix ? "/Parent/NewDirectory" @@ -394,7 +393,7 @@ public class DirectoryProviderServiceTests public void CreateDirectory_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId parentPath = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId parentPath = _fileSystemPathIdFixture.Create(); string directoryName = "NewDirectory"; _mockFileSystemPermissionsService.CanAccessPath(parentPath, FileAccessMode.Write, false).Returns(false); @@ -427,7 +426,7 @@ public class DirectoryProviderServiceTests public void CreateDirectory_WhenCreatedDirectoryPathIsInvalid_ShouldReturnError() { // Arrange - FileSystemPathId parentPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Parent"); + FileSystemPathId parentPath = _fileSystemPathIdFixture.Create(@"C:\Parent"); string directoryName = "NewDirectory"; string invalidPath = "Invalid:Path"; @@ -447,8 +446,8 @@ public class DirectoryProviderServiceTests public void CopyDirectory_WhenSourceDirectoryExistsAndUserHasAccess_ShouldCopyDirectoryAndReturnPath() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSource); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSource); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); bool overrideExisting = false; _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); @@ -476,8 +475,8 @@ public class DirectoryProviderServiceTests public void CopyDirectory_WhenSourceDirectoryDoesNotExist_ShouldReturnError() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(); bool overrideExisting = false; _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(false); @@ -494,8 +493,8 @@ public class DirectoryProviderServiceTests public void CopyDirectory_WhenDestinationDirectoryExists_ShouldCreateUniqueDirectoryName() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSource); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSource); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); string expectedNewDirectoryPath = s_isUnix ? "/Destination - Copy (1)" : @"C:\Destination - Copy (1)"; @@ -528,8 +527,8 @@ public class DirectoryProviderServiceTests public void CopyDirectory_WhenCopyingFilesAndSubdirectories_ShouldCopyAllContents() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSource); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSource); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); bool overrideExisting = true; @@ -583,8 +582,8 @@ public class DirectoryProviderServiceTests public void CopyDirectory_WhenExceptionOccurs_ShouldReturnError() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(); bool overrideExisting = false; _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); @@ -602,10 +601,10 @@ public class DirectoryProviderServiceTests public void MoveDirectory_WhenSourceDirectoryDoesNotExist_ShouldReturnDirectoryNotFoundError() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create( s_isUnix ? "/NonExistentSource" : @"C:\NonExistentSource" ); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); bool overrideExisting = false; _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(false); @@ -622,8 +621,8 @@ public class DirectoryProviderServiceTests public void MoveDirectory_WhenDestinationDirectoryDoesNotExist_ShouldPerformSimpleMove() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSource); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSource); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); bool overrideExisting = false; _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); @@ -642,8 +641,8 @@ public class DirectoryProviderServiceTests public void MoveDirectory_WhenDestinationDirectoryExists_ShouldMergeDirectories() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSource); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSource); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); bool overrideExisting = true; _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); @@ -681,8 +680,8 @@ public class DirectoryProviderServiceTests public void MoveDirectory_WhenExceptionOccurs_ShouldReturnDirectoryMoveError() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSource); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSource); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); bool overrideExisting = false; _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); @@ -702,8 +701,8 @@ public class DirectoryProviderServiceTests public void MergeDirectories_WhenSourceContainsFilesAndSubdirectories_ShouldMergeCorrectly() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSource); - FileSystemPathId destPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSource); + FileSystemPathId destPath = _fileSystemPathIdFixture.Create(_pathDestination); bool overwrite = true; _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); @@ -745,8 +744,8 @@ public class DirectoryProviderServiceTests public void MoveDirectory_WhenOverwriteIsFalse_ShouldMoveOnlyNonExistingFiles() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSource); - FileSystemPathId destPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSource); + FileSystemPathId destPath = _fileSystemPathIdFixture.Create(_pathDestination); bool overwrite = false; _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); @@ -803,8 +802,8 @@ public class DirectoryProviderServiceTests public void MergeDirectories_WhenSourceContainsNestedDirectories_ShouldMergeRecursively() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSource); - FileSystemPathId destPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSource); + FileSystemPathId destPath = _fileSystemPathIdFixture.Create(_pathDestination); bool overwrite = true; _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); @@ -850,7 +849,7 @@ public class DirectoryProviderServiceTests public void RenameDirectory_WhenParentDirectoryIsWritable_ShouldRenameSuccessfully() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId path = _fileSystemPathIdFixture.Create( s_isUnix ? "/OldName" : @"C:\OldName" ); string newName = "NewName"; @@ -877,7 +876,7 @@ public class DirectoryProviderServiceTests public void RenameDirectory_WhenParentDirectoryIsNotWritable_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId path = _fileSystemPathIdFixture.Create( s_isUnix ? "/OldName" : @"C:\OldName" ); string newName = "NewName"; @@ -903,7 +902,7 @@ public class DirectoryProviderServiceTests public void RenameDirectory_WhenDirectoryIsNotExecutable_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId path = _fileSystemPathIdFixture.Create( s_isUnix ? "/OldName" : @"C:\OldName" ); string newName = "NewName"; @@ -930,7 +929,7 @@ public class DirectoryProviderServiceTests public void RenameDirectory_WhenParentDirectoryIsNull_ShouldReturnInvalidPathError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId path = _fileSystemPathIdFixture.Create( s_isUnix ? "/OldName" : @"C:\OldName" ); string newName = "NewName"; @@ -950,7 +949,7 @@ public class DirectoryProviderServiceTests public void RenameDirectory_WhenNewPathIsInvalid_ShouldReturnInvalidPathError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId path = _fileSystemPathIdFixture.Create( s_isUnix ? "/OldName" : @"C:\OldName" ); string newName = "NewName"; @@ -974,7 +973,7 @@ public class DirectoryProviderServiceTests public void DeleteDirectory_WhenDirectoryExistsAndHasDeletePermission_ShouldDeleteSuccessfully() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId path = _fileSystemPathIdFixture.Create( s_isUnix ? "/DirectoryToDelete" : @"C:\DirectoryToDelete" ); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete, false).Returns(true); @@ -994,7 +993,7 @@ public class DirectoryProviderServiceTests public void DeleteDirectory_WhenNoDeletePermission_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId path = _fileSystemPathIdFixture.Create( s_isUnix ? "/DirectoryToDelete" : @"C:\DirectoryToDelete" ); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete, false).Returns(false); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs similarity index 93% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs index 9488f961..1ec2e417 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs @@ -6,9 +6,9 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities.Fixtures; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using System; using System.Collections.Generic; @@ -18,7 +18,7 @@ using System.Runtime.InteropServices; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. @@ -30,8 +30,8 @@ public class DirectoryServiceTests private readonly IPlatformContextManager _mockPlatformContextManager; private readonly IPlatformContext _mockPlatformContext; private readonly DirectoryService _sut; - private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; - private readonly DirectoryFixture _directoryFixture; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly DirectoryFixture _directoryFixture = new(); private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); private readonly string _pathDirTest = s_isUnix ? "/TestDir" : @"C:\TestDir"; private readonly string _pathDirTestSubDir1 = s_isUnix ? "/TestDir/Sub1" : @"C:\TestDir\Sub1"; @@ -47,8 +47,6 @@ public class DirectoryServiceTests _mockPlatformContext = Substitute.For(); _mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext); _sut = new DirectoryService(_mockEnvironmentContext, _mockPlatformContextManager); - _fileSystemPathIdFixture = new FileSystemPathIdFixture(); - _directoryFixture = new DirectoryFixture(); } [Fact] @@ -57,11 +55,11 @@ public class DirectoryServiceTests // Arrange string path = _pathDirTest; bool includeHiddenElements = false; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); FileSystemPathId[] subPaths = [ - _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTestSubDir1), - _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTestSubDir2) + _fileSystemPathIdFixture.Create(_pathDirTestSubDir1), + _fileSystemPathIdFixture.Create(_pathDirTestSubDir2) ]; _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) @@ -107,7 +105,7 @@ public class DirectoryServiceTests // Arrange string path = _pathDirTest; bool includeHiddenElements = false; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) .Returns(Errors.Permission.UnauthorizedAccess); @@ -126,8 +124,8 @@ public class DirectoryServiceTests // Arrange string path = _pathDirTest; bool includeHiddenElements = false; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); - FileSystemPathId subPath = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); + FileSystemPathId subPath = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/InaccessibleSub" : @"C:\TestDir\InaccessibleSub" ); @@ -154,12 +152,12 @@ public class DirectoryServiceTests public void GetSubdirectoriesOverload_WithValidDirectory_ShouldReturnListOfDirectories() { // Arrange - Directory parentDirectory = _directoryFixture.CreateDirectory(); + Directory parentDirectory = _directoryFixture.Create(); bool includeHiddenElements = false; FileSystemPathId[] subPaths = [ - _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTestSubDir1), - _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTestSubDir2) + _fileSystemPathIdFixture.Create(_pathDirTestSubDir1), + _fileSystemPathIdFixture.Create(_pathDirTestSubDir2) ]; _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, includeHiddenElements) @@ -188,7 +186,7 @@ public class DirectoryServiceTests public void GetSubdirectoriesOverload_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError() { // Arrange - Directory parentDirectory = _directoryFixture.CreateDirectory(); + Directory parentDirectory = _directoryFixture.Create(); bool includeHiddenElements = false; _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, includeHiddenElements) @@ -206,9 +204,9 @@ public class DirectoryServiceTests public void GetSubdirectoriesOverload_WhenSubdirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory() { // Arrange - Directory parentDirectory = _directoryFixture.CreateDirectory(); + Directory parentDirectory = _directoryFixture.Create(); bool includeHiddenElements = false; - FileSystemPathId subPath = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId subPath = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/InaccessibleSub" : @"C:\TestDir\InaccessibleSub" ); @@ -235,12 +233,12 @@ public class DirectoryServiceTests public void GetSubdirectories_WithValidFileSystemPathId_ShouldReturnListOfDirectories() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathDirTest); bool includeHiddenElements = false; FileSystemPathId[] subPaths = [ - _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTestSubDir1), - _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTestSubDir2) + _fileSystemPathIdFixture.Create(_pathDirTestSubDir1), + _fileSystemPathIdFixture.Create(_pathDirTestSubDir2) ]; _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) @@ -269,7 +267,7 @@ public class DirectoryServiceTests public void GetSubdirectoriesWithFileSystemPathId_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathDirTest); bool includeHiddenElements = false; _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) @@ -287,9 +285,9 @@ public class DirectoryServiceTests public void GetSubdirectoriesWithFileSystemPathId_WhenSubdirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathDirTest); bool includeHiddenElements = false; - FileSystemPathId subPath = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId subPath = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/InaccessibleSub" : @"C:\TestDir\InaccessibleSub" ); @@ -318,8 +316,8 @@ public class DirectoryServiceTests // Arrange string parentPath = _pathDirTest; string newDirName = "NewDirectory"; - FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(parentPath); - FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPath, newDirName)); + FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(parentPath); + FileSystemPathId newDirPathId = _fileSystemPathIdFixture.Create(System.IO.Path.Combine(parentPath, newDirName)); _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId)); _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(Result.From(false)); @@ -360,9 +358,9 @@ public class DirectoryServiceTests public void CreateDirectory_WithFileSystemPathId_ShouldReturnNewDirectory() { // Arrange - FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest); + FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(_pathDirTest); string newDirName = "NewDirectory"; - FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName)); + FileSystemPathId newDirPathId = _fileSystemPathIdFixture.Create(System.IO.Path.Combine(parentPathId.Path, newDirName)); _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId)); _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(Result.From(false)); @@ -388,9 +386,9 @@ public class DirectoryServiceTests public void CreateDirectory_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError() { // Arrange - FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest); + FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(_pathDirTest); string newDirName = "NewDirectory"; - FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName)); + FileSystemPathId newDirPathId = _fileSystemPathIdFixture.Create(System.IO.Path.Combine(parentPathId.Path, newDirName)); _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId)); _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(Result.From(false)); @@ -410,9 +408,9 @@ public class DirectoryServiceTests public void CreateDirectory_WhenDirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory() { // Arrange - FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest); + FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(_pathDirTest); string newDirName = "NewDirectory"; - FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName)); + FileSystemPathId newDirPathId = _fileSystemPathIdFixture.Create(System.IO.Path.Combine(parentPathId.Path, newDirName)); _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId)); _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(Result.From(false)); @@ -442,9 +440,9 @@ public class DirectoryServiceTests public void CreateDirectory_WhenDirectoryExistsReturnsError_ShouldPropagateError() { // Arrange - FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest); + FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(_pathDirTest); string newDirName = "NewDirectory"; - FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName)); + FileSystemPathId newDirPathId = _fileSystemPathIdFixture.Create(System.IO.Path.Combine(parentPathId.Path, newDirName)); _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId)); _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId) @@ -462,9 +460,9 @@ public class DirectoryServiceTests public void CreateDirectory_WhenDirectoryAlreadyExists_ShouldReturnDirectoryAlreadyExistsError() { // Arrange - FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest); + FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(_pathDirTest); string newDirName = "ExistingDirectory"; - FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName)); + FileSystemPathId newDirPathId = _fileSystemPathIdFixture.Create(System.IO.Path.Combine(parentPathId.Path, newDirName)); _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId)); _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(true); @@ -481,7 +479,7 @@ public class DirectoryServiceTests public void CreateDirectory_WhenCombinePathReturnsError_ShouldReturnError() { // Arrange - FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest); + FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(_pathDirTest); string newDirName = "NewDirectory"; _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName) @@ -505,8 +503,8 @@ public class DirectoryServiceTests // Arrange string oldPath = s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName"; string newName = "NewName"; - FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(oldPath); - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId oldPathId = _fileSystemPathIdFixture.Create(oldPath); + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName" ); @@ -550,11 +548,11 @@ public class DirectoryServiceTests public void RenameDirectory_WithFileSystemPathId_ShouldReturnRenamedDirectory() { // Arrange - FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId oldPathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName" ); string newName = "NewName"; - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName" ); @@ -583,11 +581,11 @@ public class DirectoryServiceTests public void RenameDirectory_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError() { // Arrange - FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId oldPathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName" ); string newName = "NewName"; - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName" ); @@ -609,11 +607,11 @@ public class DirectoryServiceTests public void RenameDirectory_WhenDirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory() { // Arrange - FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId oldPathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName" ); string newName = "NewName"; - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName" ); @@ -645,11 +643,11 @@ public class DirectoryServiceTests public void RenameDirectory_WhenDirectoryAlreadyExists_ShouldReturnDirectoryAlreadyExistsError() { // Arrange - FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId oldPathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName" ); string newName = "ExistingDirectory"; - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/ExistingDirectory" : @"C:\TestDir\ExistingDirectory" ); @@ -670,7 +668,7 @@ public class DirectoryServiceTests public void RenameDirectory_WhenCombinePathReturnsError_ShouldReturnError() { // Arrange - FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId oldPathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName" ); string newName = "NewName"; @@ -694,11 +692,11 @@ public class DirectoryServiceTests public void RenameDirectory_WhenDirectoryExistsReturnsError_ShouldPropagateError() { // Arrange - FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId oldPathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName" ); string newName = "NewName"; - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName" ); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) @@ -723,7 +721,7 @@ public class DirectoryServiceTests { // Arrange string path = s_isUnix ? "/TestDir/ToDelete" : @"C:\TestDir\ToDelete"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); _mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId) .Returns(Result.Deleted); @@ -754,7 +752,7 @@ public class DirectoryServiceTests public void DeleteDirectory_WithFileSystemPathId_ShouldReturnDeleted() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId pathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/ToDelete" : @"C:\TestDir\ToDelete" ); @@ -773,7 +771,7 @@ public class DirectoryServiceTests public void DeleteDirectory_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId pathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/ToDelete" : @"C:\TestDir\ToDelete" ); @@ -792,7 +790,7 @@ public class DirectoryServiceTests public void DeleteDirectory_WhenDirectoryDoesNotExist_ShouldReturnDirectoryNotFoundError() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId pathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/NonExistent" : @"C:\TestDir\NonExistent" ); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DriveServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveServiceTests.cs similarity index 96% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DriveServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveServiceTests.cs index b7b8ad35..132aef7f 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/DriveServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DriveServiceTests.cs @@ -12,7 +12,7 @@ using System.IO.Abstractions; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs similarity index 91% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs index 6ad13a46..44056680 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs @@ -5,8 +5,8 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using NSubstitute.ExceptionExtensions; using System; @@ -18,7 +18,7 @@ using System.Linq; using System.Runtime.InteropServices; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. @@ -30,7 +30,7 @@ public class FileProviderServiceTests private readonly IFileSystem _mockFileSystem; private readonly IFileSystemPermissionsService _mockFileSystemPermissionsService; private readonly FileProviderService _sut; - private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); private readonly string _pathVisible1 = s_isUnix ? "/Visible.txt" : @"C:\Visible.txt"; private readonly string _pathHidden1 = s_isUnix ? "/Hidden.txt" : @"C:\Hidden.txt"; @@ -50,14 +50,13 @@ public class FileProviderServiceTests _mockFileSystem = Substitute.For(); _mockFileSystemPermissionsService = Substitute.For(); _sut = new FileProviderService(_mockFileSystem, _mockFileSystemPermissionsService); - _fileSystemPathIdFixture = new(); } [Fact] public void GetFilePaths_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(false); // Act @@ -72,8 +71,8 @@ public class FileProviderServiceTests public void GetFilePaths_WhenUserHasAccess_ShouldReturnFiles() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); - string[] files = _fixture.CreateMany(3).ToArray(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); + string[] files = [.. _fixture.CreateMany(3)]; _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true); _mockFileSystem.Directory.GetFiles(path.Path).Returns(files); @@ -93,7 +92,7 @@ public class FileProviderServiceTests public void GetFilePaths_WhenIncludeHiddenElementsIsFalse_ShouldExcludeHiddenFiles() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); string[] files = [_pathVisible1, _pathHidden1]; _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true); _mockFileSystem.Directory.GetFiles(path.Path).Returns(files); @@ -113,7 +112,7 @@ public class FileProviderServiceTests public void GetFilePaths_WhenIncludeHiddenElementsIsTrue_ShouldIncludeHiddenFiles() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); string[] files = [_pathVisible1, _pathHidden1]; _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true); _mockFileSystem.Directory.GetFiles(path.Path).Returns(files); @@ -136,7 +135,7 @@ public class FileProviderServiceTests public void GetFilePaths_WhenGetAttributesThrowsException_ShouldStillAddFile() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); string[] files = [_pathValid1, _pathInvalid1]; _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true); _mockFileSystem.Directory.GetFiles(path.Path).Returns(files); @@ -156,7 +155,7 @@ public class FileProviderServiceTests public void GetFilePaths_WhenCalled_ShouldOrderFilesAlphabetically() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); string[] files = s_isUnix ? ["/C.txt", "/A.txt", "/B.txt"] : [@"C:\C.txt", @"C:\A.txt", @"C:\B.txt"]; @@ -179,7 +178,7 @@ public class FileProviderServiceTests public void GetFilePaths_WhenDirectoryHasNoFiles_ShouldReturnEmptyList() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true); _mockFileSystem.Directory.GetFiles(path.Path).Returns([]); @@ -195,7 +194,7 @@ public class FileProviderServiceTests public void FileExists_WhenFileExists_ShouldReturnTrue() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); _mockFileSystem.File.Exists(path.Path).Returns(true); // Act @@ -210,7 +209,7 @@ public class FileProviderServiceTests public void FileExists_WhenFileDoesNotExist_ShouldReturnFalse() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); _mockFileSystem.File.Exists(path.Path).Returns(false); // Act @@ -225,7 +224,7 @@ public class FileProviderServiceTests public void GetFileName_WhenPathIsValid_ShouldReturnFileName() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); string expectedFileName = "testfile.txt"; _mockFileSystem.Path.GetFileName(path.Path).Returns(expectedFileName); @@ -241,7 +240,7 @@ public class FileProviderServiceTests public void GetFileName_WhenPathIsEmpty_ShouldReturnEmptyString() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); _mockFileSystem.Path.GetFileName(path.Path).Returns(string.Empty); // Act @@ -286,7 +285,7 @@ public class FileProviderServiceTests public void GetFileAsync_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(false); // Act @@ -353,7 +352,7 @@ public class FileProviderServiceTests public void GetLastWriteTime_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false); // Act @@ -396,7 +395,7 @@ public class FileProviderServiceTests public void GetCreationTime_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false); // Act @@ -440,7 +439,7 @@ public class FileProviderServiceTests public void GetSize_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId path = _fileSystemPathIdFixture.Create(); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false); // Act @@ -473,8 +472,8 @@ public class FileProviderServiceTests public void CopyFile_WhenSourceFileExistsAndUserHasAccess_ShouldCopyFileAndReturnPath() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); bool overrideExisting = false; _mockFileSystem.File.Exists(sourcePath.Path).Returns(true); @@ -496,8 +495,8 @@ public class FileProviderServiceTests public void CopyFile_WhenSourceFileDoesNotExist_ShouldReturnError() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(); bool overrideExisting = false; _mockFileSystem.File.Exists(sourcePath.Path).Returns(false); @@ -514,8 +513,8 @@ public class FileProviderServiceTests public void CopyFile_WhenDestinationFileExistsAndOverrideIsFalse_ShouldReturnFileAlreadyExistsError() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); string expectedDestinationFilePath = _pathDestinationFile; bool overrideExisting = false; @@ -541,8 +540,8 @@ public class FileProviderServiceTests public void CopyFile_WhenOverrideExistingIsTrue_ShouldOverwriteExistingFile() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); bool overrideExisting = true; _mockFileSystem.File.Exists(sourcePath.Path).Returns(true); @@ -564,8 +563,8 @@ public class FileProviderServiceTests public void CopyFile_WhenExceptionOccurs_ShouldReturnError() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(); bool overrideExisting = false; _mockFileSystem.File.Exists(sourcePath.Path).Returns(true); @@ -585,8 +584,8 @@ public class FileProviderServiceTests { // Arrange string sourceDirectory = _pathSource; - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(Path.Combine(sourceDirectory, "file.txt")); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(sourceDirectory); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(Path.Combine(sourceDirectory, "file.txt")); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(sourceDirectory); string expectedNewFilePath = Path.Combine(sourceDirectory, "file - Copy (1).txt"); bool overrideExisting = false; @@ -627,10 +626,10 @@ public class FileProviderServiceTests public void MoveFile_WhenSourceFileDoesNotExist_ShouldReturnFileNotFoundError() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create( s_isUnix ? "/NonExistentSource.txt" : @"C:\NonExistentSource.txt" ); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); bool overrideExisting = false; _mockFileSystem.File.Exists(sourcePath.Path).Returns(false); @@ -647,8 +646,8 @@ public class FileProviderServiceTests public void MoveFile_WhenDestinationFileDoesNotExist_ShouldPerformSimpleMove() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); string destinationFilePath = _pathDestinationFile; bool overrideExisting = false; @@ -670,8 +669,8 @@ public class FileProviderServiceTests public void MoveFile_WhenDestinationFileExistsAndOverrideIsTrue_ShouldOverwriteFile() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); string destinationFilePath = _pathDestinationFile; bool overrideExisting = true; @@ -693,8 +692,8 @@ public class FileProviderServiceTests public void MoveFile_WhenDestinationFileExistsAndOverrideIsFalse_ShouldReturnFileAlreadyExistsError() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); string destinationFilePath = _pathDestinationFile; bool overrideExisting = false; @@ -715,8 +714,8 @@ public class FileProviderServiceTests public void MoveFile_WhenExceptionOccurs_ShouldReturnFileMoveError() { // Arrange - FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile); - FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination); + FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination); string destinationFilePath = _pathDestinationFile; bool overrideExisting = false; @@ -739,7 +738,7 @@ public class FileProviderServiceTests public void RenameFile_WhenParentDirectoryIsWritable_ShouldRenameSuccessfully() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId path = _fileSystemPathIdFixture.Create( s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" ); string newName = "NewName.txt"; @@ -766,7 +765,7 @@ public class FileProviderServiceTests public void RenameFile_WhenParentDirectoryIsNotWritable_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId path = _fileSystemPathIdFixture.Create( s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" ); string newName = "NewName.txt"; @@ -792,7 +791,7 @@ public class FileProviderServiceTests public void RenameFile_WhenFileIsNotExecutable_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId path = _fileSystemPathIdFixture.Create( s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" ); string newName = "NewName.txt"; @@ -819,7 +818,7 @@ public class FileProviderServiceTests public void RenameFile_WhenParentDirectoryIsNull_ShouldReturnInvalidPathError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId path = _fileSystemPathIdFixture.Create( s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" ); string newName = "NewName.txt"; @@ -839,7 +838,7 @@ public class FileProviderServiceTests public void RenameFile_WhenNewPathIsInvalid_ShouldReturnInvalidPathError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId path = _fileSystemPathIdFixture.Create( s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" ); string newName = "NewName.txt"; @@ -863,7 +862,7 @@ public class FileProviderServiceTests public void RenameFile_WhenParentDirectoryExistsButNotWritable_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId path = _fileSystemPathIdFixture.Create( s_isUnix ? "/OldName.txt" : @"C:\OldName.txt" ); string newName = "NewName.txt"; @@ -896,7 +895,7 @@ public class FileProviderServiceTests public void DeleteFile_WhenFileExistsAndHasDeletePermission_ShouldDeleteSuccessfully() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId path = _fileSystemPathIdFixture.Create( s_isUnix ? "/FileToDelete.txt" : @"C:\FileToDelete.txt" ); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(true); @@ -915,7 +914,7 @@ public class FileProviderServiceTests public void DeleteFile_WhenNoDeletePermission_ShouldReturnUnauthorizedAccessError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId path = _fileSystemPathIdFixture.Create( s_isUnix ? "/FileToDelete.txt" : @"C:\FileToDelete.txt" ); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(false); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileServiceTests.cs similarity index 92% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileServiceTests.cs index 4cf46087..1efdd9be 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileServiceTests.cs @@ -6,9 +6,9 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities.Fixtures; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using System; using System.Collections.Generic; @@ -18,7 +18,7 @@ using System.Runtime.InteropServices; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. @@ -30,8 +30,8 @@ public class FileServiceTests private readonly IPlatformContextManager _mockPlatformContextManager; private readonly IPlatformContext _mockPlatformContext; private readonly FileService _sut; - private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; - private readonly FileFixture _fileFixture; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly FileFixture _fileFixture = new(); private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); private readonly string _pathTestDir = s_isUnix ? "/TestDir" : @"C:\TestDir"; private readonly string _pathTestDirFile1 = s_isUnix ? "/TestDir/File1.txt" : @"C:\TestDir\File1.txt"; @@ -57,8 +57,6 @@ public class FileServiceTests _mockPlatformContext = Substitute.For(); _mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext); _sut = new FileService(_mockEnvironmentContext, _mockPlatformContextManager); - _fileSystemPathIdFixture = new FileSystemPathIdFixture(); - _fileFixture = new FileFixture(); } [Fact] @@ -67,11 +65,11 @@ public class FileServiceTests // Arrange string path = _pathTestDir; bool includeHiddenElements = false; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); FileSystemPathId[] filePaths = [ - _fileSystemPathIdFixture.CreateFileSystemPathId(_pathTestDirFile1), - _fileSystemPathIdFixture.CreateFileSystemPathId(_pathTestDirFile2) + _fileSystemPathIdFixture.Create(_pathTestDirFile1), + _fileSystemPathIdFixture.Create(_pathTestDirFile2) ]; _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) @@ -119,7 +117,7 @@ public class FileServiceTests // Arrange string path = _pathTestDir; bool includeHiddenElements = false; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) .Returns(Errors.Permission.UnauthorizedAccess); @@ -138,8 +136,8 @@ public class FileServiceTests // Arrange string path = _pathTestDir; bool includeHiddenElements = false; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); - FileSystemPathId filePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathTestDirInaccessible); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); + FileSystemPathId filePath = _fileSystemPathIdFixture.Create(_pathTestDirInaccessible); _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) .Returns(Result.From(new[] { filePath }.AsEnumerable())); @@ -166,12 +164,12 @@ public class FileServiceTests public void GetFilesOverload_WithValidFile_ShouldReturnListOfFiles() { // Arrange - File parentFile = _fileFixture.CreateFile(); + File parentFile = _fileFixture.Create(); bool includeHiddenElements = false; FileSystemPathId[] filePaths = [ - _fileSystemPathIdFixture.CreateFileSystemPathId(_pathTestDirFile1), - _fileSystemPathIdFixture.CreateFileSystemPathId(_pathTestDirFile2) + _fileSystemPathIdFixture.Create(_pathTestDirFile1), + _fileSystemPathIdFixture.Create(_pathTestDirFile2) ]; _mockEnvironmentContext.FileProviderService.GetFilePaths(parentFile.Id, includeHiddenElements) @@ -202,7 +200,7 @@ public class FileServiceTests public void GetFilesOverload_WhenFileProviderServiceReturnsError_ShouldPropagateError() { // Arrange - File parentFile = _fileFixture.CreateFile(); + File parentFile = _fileFixture.Create(); bool includeHiddenElements = false; _mockEnvironmentContext.FileProviderService.GetFilePaths(parentFile.Id, includeHiddenElements) @@ -220,9 +218,9 @@ public class FileServiceTests public void GetFilesOverload_WhenFileDetailsAreInaccessible_ShouldReturnInaccessibleFile() { // Arrange - File parentFile = _fileFixture.CreateFile(); + File parentFile = _fileFixture.Create(); bool includeHiddenElements = false; - FileSystemPathId filePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathTestDirInaccessible); + FileSystemPathId filePath = _fileSystemPathIdFixture.Create(_pathTestDirInaccessible); _mockEnvironmentContext.FileProviderService.GetFilePaths(parentFile.Id, includeHiddenElements) .Returns(Result.From(new[] { filePath }.AsEnumerable())); @@ -249,12 +247,12 @@ public class FileServiceTests public void GetFiles_WithValidFileSystemPathId_ShouldReturnListOfFiles() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathTestDir); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathTestDir); bool includeHiddenElements = false; FileSystemPathId[] filePaths = [ - _fileSystemPathIdFixture.CreateFileSystemPathId(_pathTestDirFile1), - _fileSystemPathIdFixture.CreateFileSystemPathId(_pathTestDirFile2) + _fileSystemPathIdFixture.Create(_pathTestDirFile1), + _fileSystemPathIdFixture.Create(_pathTestDirFile2) ]; _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) @@ -285,7 +283,7 @@ public class FileServiceTests public void GetFilesWithFileSystemPathId_WhenFileProviderServiceReturnsError_ShouldPropagateError() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathTestDir); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathTestDir); bool includeHiddenElements = false; _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) @@ -303,9 +301,9 @@ public class FileServiceTests public void GetFilesWithFileSystemPathId_WhenFileDetailsAreInaccessible_ShouldReturnInaccessibleFile() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathTestDir); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathTestDir); bool includeHiddenElements = false; - FileSystemPathId filePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathTestDirInaccessible); + FileSystemPathId filePath = _fileSystemPathIdFixture.Create(_pathTestDirInaccessible); _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) .Returns(Result.From(new[] { filePath }.AsEnumerable())); @@ -335,9 +333,9 @@ public class FileServiceTests string sourcePath = _pathSourceFile; string destinationPath = _pathDestination1; bool overrideExisting = true; - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); - FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(destinationPath); - FileSystemPathId copiedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestinationFile); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(sourcePath); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(destinationPath); + FileSystemPathId copiedFilePathId = _fileSystemPathIdFixture.Create(_pathDestinationFile); _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), Arg.Any()) @@ -369,7 +367,7 @@ public class FileServiceTests string sourcePath = _pathSourceNonExistingFile; string destinationPath = _pathDestination1; bool overrideExisting = true; - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(sourcePath); _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(Result.From(false)); @@ -388,8 +386,8 @@ public class FileServiceTests string sourcePath = _pathSourceFile; string destinationPath = _pathDestination1; bool overrideExisting = true; - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); - FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(destinationPath); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(sourcePath); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(destinationPath); _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(Result.From(true)); @@ -411,9 +409,9 @@ public class FileServiceTests string sourcePath = _pathSourceFile; string destinationPath = _pathDestination1; bool overrideExisting = true; - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); - FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(destinationPath); - FileSystemPathId copiedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestinationFile); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(sourcePath); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(destinationPath); + FileSystemPathId copiedFilePathId = _fileSystemPathIdFixture.Create(_pathDestinationFile); _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(Result.From(true)); @@ -471,9 +469,9 @@ public class FileServiceTests public void CopyFile_WithValidFileSystemPathIds_ShouldReturnCopiedFile() { // Arrange - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile); - FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination2); - FileSystemPathId copiedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestinationFile); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(_pathDestination2); + FileSystemPathId copiedFilePathId = _fileSystemPathIdFixture.Create(_pathDestinationFile); bool overrideExisting = true; _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); @@ -500,8 +498,8 @@ public class FileServiceTests public void CopyFileWithFileSystemPathIds_WhenSourceDoesNotExist_ShouldReturnError() { // Arrange - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceNonExistingFile); - FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination2); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(_pathSourceNonExistingFile); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(_pathDestination2); bool overrideExisting = true; _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(false); @@ -518,8 +516,8 @@ public class FileServiceTests public void CopyFileWithFileSystemPathIds_WhenFileProviderServiceReturnsError_ShouldPropagateError() { // Arrange - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile); - FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination2); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(_pathDestination2); bool overrideExisting = true; _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); @@ -538,9 +536,9 @@ public class FileServiceTests public void CopyFileWithFileSystemPathIds_WhenRetrievingFileInfoFails_ShouldReturnInaccessibleFile() { // Arrange - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile); - FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination2); - FileSystemPathId copiedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestinationFile); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(_pathDestination2); + FileSystemPathId copiedFilePathId = _fileSystemPathIdFixture.Create(_pathDestinationFile); bool overrideExisting = true; _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); @@ -568,9 +566,9 @@ public class FileServiceTests string sourcePath = _pathSourceFile; string destinationPath = _pathDestination1; bool overrideExisting = true; - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); - FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(destinationPath); - FileSystemPathId movedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestinationFile); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(sourcePath); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(destinationPath); + FileSystemPathId movedFilePathId = _fileSystemPathIdFixture.Create(_pathDestinationFile); _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), Arg.Any()) @@ -602,7 +600,7 @@ public class FileServiceTests string sourcePath = _pathSourceNonExistingFile; string destinationPath = _pathDestination2; bool overrideExisting = true; - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(sourcePath); _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(false); @@ -622,8 +620,8 @@ public class FileServiceTests string sourcePath = _pathSourceFile; string destinationPath = _pathDestination1; bool overrideExisting = true; - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); - FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(destinationPath); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(sourcePath); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(destinationPath); _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); @@ -645,9 +643,9 @@ public class FileServiceTests string sourcePath = _pathSourceFile; string destinationPath = _pathDestination1; bool overrideExisting = true; - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); - FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(destinationPath); - FileSystemPathId movedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestinationFile); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(sourcePath); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(destinationPath); + FileSystemPathId movedFilePathId = _fileSystemPathIdFixture.Create(_pathDestinationFile); _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), Arg.Any()) @@ -710,9 +708,9 @@ public class FileServiceTests public void MoveFile_WithValidFileSystemPathIds_ShouldReturnMovedFile() { // Arrange - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile); - FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination2); - FileSystemPathId movedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestinationFile); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(_pathDestination2); + FileSystemPathId movedFilePathId = _fileSystemPathIdFixture.Create(_pathDestinationFile); bool overrideExisting = true; _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); @@ -739,10 +737,10 @@ public class FileServiceTests public void MoveFileWithFileSystemPathIds_WhenSourceDoesNotExist_ShouldReturnError() { // Arrange - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId( + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create( s_isUnix ? "/Source/nonexistent.txt" : _pathSourceNonExistingFile ); - FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination2); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(_pathDestination2); bool overrideExisting = true; _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(false); @@ -759,8 +757,8 @@ public class FileServiceTests public void MoveFileWithFileSystemPathIds_WhenFileProviderServiceReturnsError_ShouldPropagateError() { // Arrange - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile); - FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination1); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(_pathDestination1); bool overrideExisting = true; _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); @@ -779,9 +777,9 @@ public class FileServiceTests public void MoveFileWithFileSystemPathIds_WhenRetrievingFileInfoFails_ShouldReturnInaccessibleFile() { // Arrange - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile); - FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination1); - FileSystemPathId movedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestinationFile); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(_pathSourceFile); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.Create(_pathDestination1); + FileSystemPathId movedFilePathId = _fileSystemPathIdFixture.Create(_pathDestinationFile); bool overrideExisting = true; _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); @@ -809,7 +807,7 @@ public class FileServiceTests string sourcePath = _pathSourceFile; string destinationPath = _pathDestination1; bool overrideExisting = true; - FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.Create(sourcePath); _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId) @@ -829,8 +827,8 @@ public class FileServiceTests // Arrange string path = _pathSourceOldFile; string newName = "newfile.txt"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceNewFile); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(_pathSourceNewFile); _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) @@ -861,7 +859,7 @@ public class FileServiceTests // Arrange string path = _pathSourceOldFile; string newName = "existingfile.txt"; - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceExistingFile); + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(_pathSourceExistingFile); _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) @@ -882,8 +880,8 @@ public class FileServiceTests // Arrange string path = _pathSourceOldFile; string newName = "newfile.txt"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceNewFile); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(_pathSourceNewFile); _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) @@ -906,8 +904,8 @@ public class FileServiceTests // Arrange string path = _pathSourceOldFile; string newName = "newfile.txt"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceNewFile); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(_pathSourceNewFile); _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) @@ -951,9 +949,9 @@ public class FileServiceTests public void RenameFileWithValidFileSystemPathIdAndName_ShouldReturnRenamedFile() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceOldFile); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathSourceOldFile); string newName = "newfile.txt"; - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceNewFile); + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(_pathSourceNewFile); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) .Returns(Result.From(newPathId)); @@ -981,9 +979,9 @@ public class FileServiceTests public void RenameFileWithFileSystemPathId_WhenNewNameAlreadyExists_ShouldReturnError() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceOldFile); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathSourceOldFile); string newName = "existingfile.txt"; - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceExistingFile); + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(_pathSourceExistingFile); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) .Returns(Result.From(newPathId)); @@ -1001,9 +999,9 @@ public class FileServiceTests public void RenameFileWithFileSystemPathId_WhenFileProviderServiceReturnsError_ShouldPropagateError() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceOldFile); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathSourceOldFile); string newName = "newfile.txt"; - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceNewFile); + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(_pathSourceNewFile); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) .Returns(Result.From(newPathId)); @@ -1023,9 +1021,9 @@ public class FileServiceTests public void RenameFileWithFileSystemPathId_WhenRetrievingFileInfoFails_ShouldReturnInaccessibleFile() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceOldFile); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathSourceOldFile); string newName = "newfile.txt"; - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceNewFile); + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(_pathSourceNewFile); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) .Returns(Result.From(newPathId)); @@ -1072,7 +1070,7 @@ public class FileServiceTests // Arrange string path = _pathSourceOldFile; string newName = "newfile.txt"; - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceNewFile); + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(_pathSourceNewFile); _mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) @@ -1092,7 +1090,7 @@ public class FileServiceTests public void RenameFileWithFileSystemPathId_WhenCombinePathReturnsError_ShouldPropagateError() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceOldFile); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathSourceOldFile); string newName = "newfile.txt"; _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) @@ -1110,9 +1108,9 @@ public class FileServiceTests public void RenameFileWithFileSystemPathId_WhenFileExistsReturnsError_ShouldPropagateError() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceOldFile); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathSourceOldFile); string newName = "newfile.txt"; - FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceNewFile); + FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(_pathSourceNewFile); _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) .Returns(Result.From(newPathId)); @@ -1132,7 +1130,7 @@ public class FileServiceTests { // Arrange string path = _pathSourceFile; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); _mockEnvironmentContext.FileProviderService.DeleteFile(pathId) .Returns(Result.Deleted); @@ -1164,7 +1162,7 @@ public class FileServiceTests { // Arrange string path = _pathSourceFile; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); _mockEnvironmentContext.FileProviderService.DeleteFile(pathId) .Returns(Errors.Permission.UnauthorizedAccess); @@ -1181,7 +1179,7 @@ public class FileServiceTests public void DeleteFile_WithValidFileSystemPathId_ShouldReturnDeleted() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathSourceFile); _mockEnvironmentContext.FileProviderService.DeleteFile(pathId) .Returns(Result.Deleted); @@ -1198,7 +1196,7 @@ public class FileServiceTests public void DeleteFileWithFileSystemPathId_WhenFileProviderServiceReturnsError_ShouldPropagateError() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathSourceFile); _mockEnvironmentContext.FileProviderService.DeleteFile(pathId) .Returns(Errors.Permission.UnauthorizedAccess); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileTypeServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeServiceTests.cs similarity index 91% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileTypeServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeServiceTests.cs index 13382bc4..dcc32308 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/FileTypeServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeServiceTests.cs @@ -4,10 +4,10 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Entities.Fixtures; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -18,7 +18,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. @@ -29,8 +29,8 @@ public class FileTypeServiceTests private MockFileSystem _mockFileSystem = null!; private readonly IFileSystemPermissionsService _mockFileSystemPermissionsService; private FileTypeService? sut; - private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; - private readonly FileFixture _fileFixture; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly FileFixture _fileFixture = new(); /// /// Initializes a new instance of the class. @@ -38,15 +38,13 @@ public class FileTypeServiceTests public FileTypeServiceTests() { _mockFileSystemPermissionsService = Substitute.For(); - _fileSystemPathIdFixture = new FileSystemPathIdFixture(); - _fileFixture = new FileFixture(); } [Fact] public async Task GetImageTypeAsync_WithValidFile_ShouldReturnCorrectImageType() { // Arrange - File file = _fileFixture.CreateFile(); + File file = _fileFixture.Create(); byte[] pngHeader = [137, 80, 78, 71, 13, 10, 26, 10]; byte[] fileContent = [.. pngHeader, .. Enumerable.Repeat(0, 100)]; @@ -66,7 +64,7 @@ public class FileTypeServiceTests public async Task GetImageTypeAsync_WithUnauthorizedAccess_ShouldReturnError() { // Arrange - File file = _fileFixture.CreateFile(); + File file = _fileFixture.Create(); SetupMockFileSystem(file.Id, []); sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService); @@ -85,7 +83,7 @@ public class FileTypeServiceTests public async Task GetImageTypeAsync_WithSmallFile_ShouldReturnNone() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\test.jpg"); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\test.jpg"); byte[] fileContent = [1, 2, 3]; // Less than BUFFER_SIZE SetupMockFileSystem(pathId, fileContent); @@ -104,7 +102,7 @@ public class FileTypeServiceTests public async Task GetImageTypeAsync_WithSvgFile_ShouldReturnSvgType() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\test.svg"); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\test.svg"); string svgContent = ""; byte[] fileContent = Encoding.UTF8.GetBytes(svgContent); @@ -124,7 +122,7 @@ public class FileTypeServiceTests public async Task GetImageTypeAsync_WithTgaFile_ShouldReturnTgaType() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\test.tga"); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\test.tga"); byte[] tgaHeader = new byte[18]; tgaHeader[2] = 2; // Set image type to 2 (uncompressed true-color image) byte[] fileContent = [.. tgaHeader, .. Enumerable.Repeat(0, 100)]; @@ -146,8 +144,8 @@ public class FileTypeServiceTests public async Task GetImageTypeAsync_WithUnknownImageType_ShouldReturnNone() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\test.unknown"); - byte[] fileContent = Enumerable.Repeat(0, 100).ToArray(); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\test.unknown"); + byte[] fileContent = [.. Enumerable.Repeat(0, 100)]; SetupMockFileSystem(pathId, fileContent); sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService); @@ -175,7 +173,7 @@ public class FileTypeServiceTests public async Task GetImageTypeAsync_WithSvgFileStartingWithXmlDeclaration_ShouldReturnSvgType() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\test.svg"); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\test.svg"); string svgContent = "\n"; byte[] fileContent = Encoding.UTF8.GetBytes(svgContent); @@ -212,7 +210,7 @@ public class FileTypeServiceTests public async Task GetImageTypeAsync_WithVariousImageTypes_ShouldIdentifyCorrectly(byte[] header, ImageType expectedType, string testName) { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId($@"C:\test.{testName.ToLower()}"); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create($@"C:\test.{testName.ToLower()}"); byte[] fileContent = [.. header, .. Enumerable.Repeat(0, 100)]; SetupMockFileSystem(pathId, fileContent); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/PathServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs similarity index 95% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/PathServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs index 24978918..3bebfe31 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/PathServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs @@ -5,14 +5,14 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. @@ -24,8 +24,8 @@ public class PathServiceTests private readonly IPlatformContext _mockPlatformContext; private readonly IPathStrategy _mockPathStrategy; private readonly PathService _sut; - private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; - private readonly PathSegmentFixture _pathSegmentFixture; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly PathSegmentFixture _pathSegmentFixture = new(); /// /// Initializes a new instance of the class. @@ -38,8 +38,6 @@ public class PathServiceTests _mockPlatformContext.PathStrategy.Returns(_mockPathStrategy); _mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext); _sut = new PathService(_mockPlatformContextManager); - _fileSystemPathIdFixture = new FileSystemPathIdFixture(); - _pathSegmentFixture = new PathSegmentFixture(); } [Fact] @@ -47,7 +45,7 @@ public class PathServiceTests { // Arrange string validPath = @"C:\ValidPath"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(validPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(validPath); _mockPathStrategy.IsValidPath(pathId).Returns(true); // Act @@ -63,7 +61,7 @@ public class PathServiceTests { // Arrange string invalidPath = @"C:\Invalid\*Path"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(invalidPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(invalidPath); _mockPathStrategy.IsValidPath(pathId).Returns(false); // Act @@ -107,7 +105,7 @@ public class PathServiceTests { // Arrange string existingPath = @"C:\ExistingPath"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(existingPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(existingPath); _mockPathStrategy.Exists(pathId).Returns(true); // Act @@ -123,7 +121,7 @@ public class PathServiceTests { // Arrange string existingPath = @"C:\ExistingPath"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(existingPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(existingPath); _mockPathStrategy.Exists(pathId, true).Returns(true); // Act @@ -139,7 +137,7 @@ public class PathServiceTests { // Arrange string existingPath = @"C:\ExistingPath"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(existingPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(existingPath); _mockPathStrategy.Exists(pathId, false).Returns(false); // Act @@ -155,7 +153,7 @@ public class PathServiceTests { // Arrange string nonExistingPath = @"C:\NonExistingPath"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(nonExistingPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(nonExistingPath); _mockPathStrategy.Exists(pathId).Returns(false); // Act @@ -200,8 +198,8 @@ public class PathServiceTests // Arrange string path = @"C:\BaseDir"; string name = "SubDir"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); - FileSystemPathId combinedPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\BaseDir\SubDir"); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); + FileSystemPathId combinedPathId = _fileSystemPathIdFixture.Create(@"C:\BaseDir\SubDir"); _mockPathStrategy.CombinePath(pathId, name).Returns(Result.From(combinedPathId)); // Act @@ -235,7 +233,7 @@ public class PathServiceTests // Arrange string path = @"C:\BaseDir"; string name = "Invalid*Name"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); _mockPathStrategy.CombinePath(pathId, name).Returns(Errors.FileSystemManagement.InvalidPath); // Act @@ -268,7 +266,7 @@ public class PathServiceTests { // Arrange string validPath = @"C:\ValidPath\SubDir"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(validPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(validPath); List expectedSegments = _pathSegmentFixture.CreateMany(); _mockPathStrategy.ParsePath(pathId).Returns(Result.From(expectedSegments.AsEnumerable())); @@ -301,7 +299,7 @@ public class PathServiceTests { // Arrange string path = @"C:\InvalidPath\*SubDir"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); _mockPathStrategy.ParsePath(pathId).Returns(Errors.FileSystemManagement.InvalidPath); // Act @@ -333,7 +331,7 @@ public class PathServiceTests { // Arrange string validPath = @"C:\ValidPath\SubDir"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(validPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(validPath); List expectedSegments = _pathSegmentFixture.CreateMany(2); // Assuming parent path has 2 segments _mockPathStrategy.GoUpOneLevel(pathId).Returns(Result.From(expectedSegments.AsEnumerable())); @@ -351,7 +349,7 @@ public class PathServiceTests { // Arrange string rootPath = @"C:\"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(rootPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(rootPath); List emptySegmentList = []; _mockPathStrategy.GoUpOneLevel(pathId).Returns(Result.From(emptySegmentList.AsEnumerable())); @@ -384,7 +382,7 @@ public class PathServiceTests { // Arrange string path = @"C:\InvalidPath\*SubDir"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); _mockPathStrategy.GoUpOneLevel(pathId).Returns(Errors.FileSystemManagement.InvalidPath); // Act @@ -463,8 +461,8 @@ public class PathServiceTests { // Arrange string validPath = @"C:\ValidPath\SubDir"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(validPath); - PathSegment expectedRootSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDirectory: false, isDrive: true); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(validPath); + PathSegment expectedRootSegment = _pathSegmentFixture.Create(name: "C:", isDirectory: false, isDrive: true); _mockPathStrategy.GetPathRoot(pathId).Returns(Result.From(expectedRootSegment)); // Act @@ -496,7 +494,7 @@ public class PathServiceTests { // Arrange string path = @"C:\InvalidPath\*SubDir"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); _mockPathStrategy.GetPathRoot(pathId).Returns(Errors.FileSystemManagement.InvalidPath); // Act diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs similarity index 92% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs index 46eb0c0b..83d75cf0 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailServiceTests.cs @@ -4,9 +4,9 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Fixtures.Common.Enums.PhotoLibrary; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services.Fixtures; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; using NSubstitute; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Jpeg; @@ -17,7 +17,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Services; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; /// /// Contains unit tests for the class. @@ -27,7 +27,7 @@ public class ThumbnailServiceTests { private readonly IEnvironmentContext _mockEnvironmentContext; private readonly ThumbnailService _sut; - private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); /// /// Initializes a new instance of the class. @@ -36,7 +36,6 @@ public class ThumbnailServiceTests { _mockEnvironmentContext = Substitute.For(); _sut = new ThumbnailService(_mockEnvironmentContext); - _fileSystemPathIdFixture = new FileSystemPathIdFixture(); } [Fact] @@ -45,7 +44,7 @@ public class ThumbnailServiceTests // Arrange string path = @"C:\TestImage.jpg"; int quality = 80; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); // Create a small valid JPEG image byte[] imageBytes; @@ -89,7 +88,7 @@ public class ThumbnailServiceTests public async Task GetThumbnailAsync_WhenFileTypeServiceReturnsError_ShouldPropagateError() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestImage.jpg"); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestImage.jpg"); int quality = 80; _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) @@ -107,7 +106,7 @@ public class ThumbnailServiceTests public async Task GetThumbnailAsync_WhenImageTypeIsNone_ShouldReturnNoThumbnailError() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestFile.txt"); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestFile.txt"); int quality = 80; _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) @@ -125,7 +124,7 @@ public class ThumbnailServiceTests public async Task GetThumbnailAsync_WhenFileProviderServiceReturnsError_ShouldPropagateError() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestImage.jpg"); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestImage.jpg"); int quality = 80; _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) @@ -146,7 +145,7 @@ public class ThumbnailServiceTests public async Task GetThumbnailAsync_WithDifferentImageTypes_ShouldReturnThumbnail(ImageType imageType, byte[] imageBytes) { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestImage"); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestImage"); int quality = 80; _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) @@ -173,7 +172,7 @@ public class ThumbnailServiceTests public async Task GetThumbnailAsync_WithCancellation_ShouldThrowTaskCanceledException() { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestImage.jpg"); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestImage.jpg"); int quality = 80; CancellationTokenSource cts = new(); cts.Cancel(); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Environment/EnvironmentContextTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Environment/EnvironmentContextTests.cs similarity index 95% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Environment/EnvironmentContextTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Environment/EnvironmentContextTests.cs index e4f8039d..dfddfe72 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Environment/EnvironmentContextTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Environment/EnvironmentContextTests.cs @@ -5,7 +5,7 @@ using NSubstitute; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Environment; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs similarity index 77% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs index 16070fb1..715a5434 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs @@ -3,7 +3,7 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -11,7 +11,7 @@ using System.IO.Abstractions; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Path; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; /// /// Contains unit tests for the class. @@ -21,8 +21,8 @@ public class UnixPathStrategyTests { private readonly IFileSystem _mockFileSystem; private readonly UnixPathStrategy _sut; - private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; - private readonly PathSegmentFixture _pathSegmentFixture; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly PathSegmentFixture _pathSegmentFixture = new(); /// /// Initializes a new instance of the class. @@ -31,8 +31,6 @@ public class UnixPathStrategyTests { _mockFileSystem = Substitute.For(); _sut = new UnixPathStrategy(_mockFileSystem); - _fileSystemPathIdFixture = new FileSystemPathIdFixture(); - _pathSegmentFixture = new PathSegmentFixture(); } [Theory] @@ -44,7 +42,7 @@ public class UnixPathStrategyTests public void IsValidPath_WithValidUnixPaths_ShouldReturnTrue(string path) { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); // Act bool result = _sut.IsValidPath(pathId); @@ -61,7 +59,7 @@ public class UnixPathStrategyTests public void IsValidPath_WithInvalidUnixPaths_ShouldReturnFalse(string path) { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); // Act bool result = _sut.IsValidPath(pathId); @@ -75,7 +73,7 @@ public class UnixPathStrategyTests { // Arrange string invalidPath = "/home/user/file\0name"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(invalidPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(invalidPath); // Act bool result = _sut.IsValidPath(pathId); @@ -98,7 +96,7 @@ public class UnixPathStrategyTests public void IsValidPath_WithValidSpecialCharacters_ShouldReturnTrue(string path) { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); // Act bool result = _sut.IsValidPath(pathId); @@ -112,7 +110,7 @@ public class UnixPathStrategyTests { // Arrange string longPath = "/" + string.Join("/", Enumerable.Repeat("a", 100)); - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(longPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(longPath); // Act bool result = _sut.IsValidPath(pathId); @@ -126,7 +124,7 @@ public class UnixPathStrategyTests { // Arrange string existingPath = "/home/user/existing_file.txt"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(existingPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(existingPath); _mockFileSystem.Path.Exists(existingPath).Returns(true); _mockFileSystem.File.Exists(existingPath).Returns(true); @@ -144,7 +142,7 @@ public class UnixPathStrategyTests { // Arrange string existingPath = "/home/user/existing_file.txt"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(existingPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(existingPath); _mockFileSystem.Path.Exists(existingPath).Returns(true); _mockFileSystem.File.Exists(existingPath).Returns(true); IFileInfo mockFileInfo = Substitute.For(); @@ -164,7 +162,7 @@ public class UnixPathStrategyTests { // Arrange string nonExistingPath = "/home/user/non_existing_file.txt"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(nonExistingPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(nonExistingPath); _mockFileSystem.Path.Exists(nonExistingPath).Returns(false); // Act @@ -180,7 +178,7 @@ public class UnixPathStrategyTests { // Arrange string rootPath = "/"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(rootPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(rootPath); _mockFileSystem.Path.Exists(rootPath).Returns(true); // Act @@ -196,7 +194,7 @@ public class UnixPathStrategyTests { // Arrange string directoryPath = "/home/user/documents/"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(directoryPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(directoryPath); _mockFileSystem.Path.Exists(directoryPath).Returns(true); _mockFileSystem.Directory.Exists(directoryPath).Returns(true); @@ -213,7 +211,7 @@ public class UnixPathStrategyTests { // Arrange string filePath = "/home/user/documents/file.txt"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(filePath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(filePath); _mockFileSystem.Path.Exists(filePath).Returns(true); _mockFileSystem.File.Exists(filePath).Returns(true); @@ -229,7 +227,7 @@ public class UnixPathStrategyTests public void CombinePath_WithValidPathAndName_ShouldReturnCombinedPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user"); string name = "documents"; // Act @@ -244,7 +242,7 @@ public class UnixPathStrategyTests public void CombinePath_WithTrailingSlashInPath_ShouldReturnCorrectlyCombinedPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user/"); string name = "documents"; // Act @@ -259,7 +257,7 @@ public class UnixPathStrategyTests public void CombinePath_WithLeadingSlashInName_ShouldReturnCorrectlyCombinedPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user"); string name = "/documents"; // Act @@ -274,7 +272,7 @@ public class UnixPathStrategyTests public void CombinePath_WithEmptyName_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user"); string name = ""; // Act @@ -289,7 +287,7 @@ public class UnixPathStrategyTests public void CombinePath_WithNullName_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user"); string name = null!; // Act @@ -304,7 +302,7 @@ public class UnixPathStrategyTests public void CombinePath_WithRootPath_ShouldReturnCorrectlyCombinedPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/"); string name = "home"; // Act @@ -319,7 +317,7 @@ public class UnixPathStrategyTests public void ParsePath_WithValidUnixPath_ShouldReturnCorrectPathSegments() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents/file.txt"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user/documents/file.txt"); // Act Result> result = _sut.ParsePath(path); @@ -327,18 +325,18 @@ public class UnixPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Equal(5, result.Value.Count()); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("/", false, true), result.Value.ElementAt(0)); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("home", true, false), result.Value.ElementAt(1)); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("user", true, false), result.Value.ElementAt(2)); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("documents", true, false), result.Value.ElementAt(3)); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("file.txt", false, false), result.Value.ElementAt(4)); + Assert.Equal(_pathSegmentFixture.Create("/", false, true), result.Value.ElementAt(0)); + Assert.Equal(_pathSegmentFixture.Create("home", true, false), result.Value.ElementAt(1)); + Assert.Equal(_pathSegmentFixture.Create("user", true, false), result.Value.ElementAt(2)); + Assert.Equal(_pathSegmentFixture.Create("documents", true, false), result.Value.ElementAt(3)); + Assert.Equal(_pathSegmentFixture.Create("file.txt", false, false), result.Value.ElementAt(4)); } [Fact] public void ParsePath_WithRootPath_ShouldReturnSingleRootSegment() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/"); // Act Result> result = _sut.ParsePath(path); @@ -346,14 +344,14 @@ public class UnixPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Single(result.Value); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("/", false, true), result.Value.Single()); + Assert.Equal(_pathSegmentFixture.Create("/", false, true), result.Value.Single()); } [Fact] public void ParsePath_WithTrailingSlash_ShouldTreatLastSegmentAsDirectory() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents/"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user/documents/"); // Act Result> result = _sut.ParsePath(path); @@ -361,14 +359,14 @@ public class UnixPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Equal(4, result.Value.Count()); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("documents", true, false), result.Value.Last()); + Assert.Equal(_pathSegmentFixture.Create("documents", true, false), result.Value.Last()); } [Fact] public void ParsePath_WithRelativePath_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("home/user"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("home/user"); // Act Result> result = _sut.ParsePath(path); @@ -382,7 +380,7 @@ public class UnixPathStrategyTests public void ParsePath_WithPathContainingDots_ShouldParseCorrectly() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/file.with.dots.txt"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user/file.with.dots.txt"); // Act Result> result = _sut.ParsePath(path); @@ -390,14 +388,14 @@ public class UnixPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Equal(4, result.Value.Count()); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("file.with.dots.txt", false, false), result.Value.Last()); + Assert.Equal(_pathSegmentFixture.Create("file.with.dots.txt", false, false), result.Value.Last()); } [Fact] public void GoUpOneLevel_WithValidPath_ShouldReturnParentPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user/documents"); // Act Result> result = _sut.GoUpOneLevel(path); @@ -405,16 +403,16 @@ public class UnixPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Equal(3, result.Value.Count()); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("/", false, true), result.Value.ElementAt(0)); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("home", true, false), result.Value.ElementAt(1)); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("user", true, false), result.Value.ElementAt(2)); + Assert.Equal(_pathSegmentFixture.Create("/", false, true), result.Value.ElementAt(0)); + Assert.Equal(_pathSegmentFixture.Create("home", true, false), result.Value.ElementAt(1)); + Assert.Equal(_pathSegmentFixture.Create("user", true, false), result.Value.ElementAt(2)); } [Fact] public void GoUpOneLevel_WithRootPath_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/"); // Act Result> result = _sut.GoUpOneLevel(path); @@ -428,7 +426,7 @@ public class UnixPathStrategyTests public void GoUpOneLevel_WithTrailingSlash_ShouldReturnCorrectParentPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user/"); // Act Result> result = _sut.GoUpOneLevel(path); @@ -436,15 +434,15 @@ public class UnixPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("/", false, true), result.Value.ElementAt(0)); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("home", true, false), result.Value.ElementAt(1)); + Assert.Equal(_pathSegmentFixture.Create("/", false, true), result.Value.ElementAt(0)); + Assert.Equal(_pathSegmentFixture.Create("home", true, false), result.Value.ElementAt(1)); } [Fact] public void GoUpOneLevel_WithInvalidPath_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("invalid/path"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("invalid/path"); // Act Result> result = _sut.GoUpOneLevel(path); @@ -458,7 +456,7 @@ public class UnixPathStrategyTests public void GoUpOneLevel_WithSingleLevelPath_ShouldReturnRootPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/home"); // Act Result> result = _sut.GoUpOneLevel(path); @@ -466,7 +464,7 @@ public class UnixPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Single(result.Value); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("/", false, true), result.Value.Single()); + Assert.Equal(_pathSegmentFixture.Create("/", false, true), result.Value.Single()); } [Fact] @@ -513,35 +511,35 @@ public class UnixPathStrategyTests public void GetPathRoot_WithValidUnixPath_ShouldReturnRootSegment() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user/documents"); // Act Result result = _sut.GetPathRoot(path); // Assert Assert.False(result.IsFailure); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("/", false, true), result.Value); + Assert.Equal(_pathSegmentFixture.Create("/", false, true), result.Value); } [Fact] public void GetPathRoot_WithRootPath_ShouldReturnRootSegment() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("/"); // Act Result result = _sut.GetPathRoot(path); // Assert Assert.False(result.IsFailure); - Assert.Equal(_pathSegmentFixture.CreatePathSegment("/", false, true), result.Value); + Assert.Equal(_pathSegmentFixture.Create("/", false, true), result.Value); } [Fact] public void GetPathRoot_WithInvalidPath_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("home/user"); + FileSystemPathId path = _fileSystemPathIdFixture.Create("home/user"); // Act Result result = _sut.GetPathRoot(path); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs similarity index 72% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs index 4c163e71..48d903a4 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs @@ -3,7 +3,7 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -11,7 +11,7 @@ using System.IO.Abstractions; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Path; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; /// /// Contains unit tests for the class. @@ -21,8 +21,8 @@ public class WindowsPathStrategyTests { private readonly IFileSystem _mockFileSystem; private readonly WindowsPathStrategy _sut; - private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; - private readonly PathSegmentFixture _pathSegmentFixture; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly PathSegmentFixture _pathSegmentFixture = new(); /// /// Initializes a new instance of the class. @@ -31,8 +31,6 @@ public class WindowsPathStrategyTests { _mockFileSystem = Substitute.For(); _sut = new WindowsPathStrategy(_mockFileSystem); - _fileSystemPathIdFixture = new FileSystemPathIdFixture(); - _pathSegmentFixture = new PathSegmentFixture(); } [Theory] @@ -44,7 +42,7 @@ public class WindowsPathStrategyTests public void IsValidPath_WithValidWindowsPaths_ShouldReturnTrue(string path) { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); // Act bool result = _sut.IsValidPath(pathId); @@ -62,7 +60,7 @@ public class WindowsPathStrategyTests public void IsValidPath_WithInvalidWindowsPaths_ShouldReturnFalse(string path) { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); // Act bool result = _sut.IsValidPath(pathId); @@ -76,7 +74,7 @@ public class WindowsPathStrategyTests { // Arrange string invalidPath = @"C:\Users\User\file"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(invalidPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(invalidPath); // Act bool result = _sut.IsValidPath(pathId); @@ -94,7 +92,7 @@ public class WindowsPathStrategyTests public void IsValidPath_WithValidSpecialCharacters_ShouldReturnTrue(string path) { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); // Act bool result = _sut.IsValidPath(pathId); @@ -108,7 +106,7 @@ public class WindowsPathStrategyTests { // Arrange string longPath = @"C:\" + string.Join("\\", Enumerable.Repeat("a", 100)); - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(longPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(longPath); // Act bool result = _sut.IsValidPath(pathId); @@ -124,7 +122,7 @@ public class WindowsPathStrategyTests public void IsValidPath_WithValidUNCPaths_ShouldReturnTrue(string path) { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); // Act bool result = _sut.IsValidPath(pathId); @@ -140,7 +138,7 @@ public class WindowsPathStrategyTests public void IsValidPath_WithInvalidUNCPaths_ShouldReturnFalse(string path) { // Arrange - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); // Act bool result = _sut.IsValidPath(pathId); @@ -154,7 +152,7 @@ public class WindowsPathStrategyTests { // Arrange string existingPath = @"C:\Users\User\existing_file.txt"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(existingPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(existingPath); _mockFileSystem.Path.Exists(existingPath).Returns(true); _mockFileSystem.File.Exists(existingPath).Returns(true); @@ -171,7 +169,7 @@ public class WindowsPathStrategyTests { // Arrange string existingPath = @"C:\Users\User\existing_file.txt"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(existingPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(existingPath); _mockFileSystem.Path.Exists(existingPath).Returns(true); _mockFileSystem.File.Exists(existingPath).Returns(true); IFileInfo mockFileInfo = Substitute.For(); @@ -191,7 +189,7 @@ public class WindowsPathStrategyTests { // Arrange string nonExistingPath = @"C:\Users\User\non_existing_file.txt"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(nonExistingPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(nonExistingPath); _mockFileSystem.Path.Exists(nonExistingPath).Returns(false); // Act @@ -207,7 +205,7 @@ public class WindowsPathStrategyTests { // Arrange string rootPath = @"C:\"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(rootPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(rootPath); _mockFileSystem.Path.Exists(rootPath).Returns(true); // Act @@ -223,7 +221,7 @@ public class WindowsPathStrategyTests { // Arrange string directoryPath = @"C:\Users\User\Documents\"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(directoryPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(directoryPath); _mockFileSystem.Path.Exists(directoryPath).Returns(true); _mockFileSystem.Directory.Exists(directoryPath).Returns(true); @@ -240,7 +238,7 @@ public class WindowsPathStrategyTests { // Arrange string filePath = @"C:\Users\User\Documents\file.txt"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(filePath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(filePath); _mockFileSystem.Path.Exists(filePath).Returns(true); _mockFileSystem.File.Exists(filePath).Returns(true); @@ -257,7 +255,7 @@ public class WindowsPathStrategyTests { // Arrange string uncPath = @"\\server\share\folder\file.txt"; - FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(uncPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(uncPath); _mockFileSystem.Path.Exists(uncPath).Returns(true); // Act @@ -272,7 +270,7 @@ public class WindowsPathStrategyTests public void CombinePath_WithValidPathAndName_ShouldReturnCombinedPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User"); string name = "Documents"; // Act @@ -287,7 +285,7 @@ public class WindowsPathStrategyTests public void CombinePath_WithTrailingBackslashInPath_ShouldReturnCorrectlyCombinedPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User\"); string name = "Documents"; // Act @@ -302,7 +300,7 @@ public class WindowsPathStrategyTests public void CombinePath_WithLeadingBackslashInName_ShouldReturnCorrectlyCombinedPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User"); string name = @"\Documents"; // Act @@ -317,7 +315,7 @@ public class WindowsPathStrategyTests public void CombinePath_WithNullName_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User"); string name = null!; // Act @@ -332,7 +330,7 @@ public class WindowsPathStrategyTests public void CombinePath_WithRootPath_ShouldReturnCorrectlyCombinedPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\"); string name = "Users"; // Act @@ -347,7 +345,7 @@ public class WindowsPathStrategyTests public void CombinePath_WithUNCPath_ShouldReturnCorrectlyCombinedPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server\share"); string name = "folder"; // Act @@ -362,7 +360,7 @@ public class WindowsPathStrategyTests public void ParsePath_WithValidWindowsPath_ShouldReturnCorrectPathSegments() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents\file.txt"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User\Documents\file.txt"); // Act Result> result = _sut.ParsePath(path); @@ -370,18 +368,18 @@ public class WindowsPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Equal(5, result.Value.Count()); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("C:", false, true), result.Value.ElementAt(0)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("Users", true, false), result.Value.ElementAt(1)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("User", true, false), result.Value.ElementAt(2)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("Documents", true, false), result.Value.ElementAt(3)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("file.txt", false, false), result.Value.ElementAt(4)); + Assert.Equivalent(_pathSegmentFixture.Create("C:", false, true), result.Value.ElementAt(0)); + Assert.Equivalent(_pathSegmentFixture.Create("Users", true, false), result.Value.ElementAt(1)); + Assert.Equivalent(_pathSegmentFixture.Create("User", true, false), result.Value.ElementAt(2)); + Assert.Equivalent(_pathSegmentFixture.Create("Documents", true, false), result.Value.ElementAt(3)); + Assert.Equivalent(_pathSegmentFixture.Create("file.txt", false, false), result.Value.ElementAt(4)); } [Fact] public void ParsePath_WithRootPath_ShouldReturnSingleRootSegment() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\"); // Act Result> result = _sut.ParsePath(path); @@ -389,14 +387,14 @@ public class WindowsPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Single(result.Value); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("C:", false, true), result.Value.Single()); + Assert.Equivalent(_pathSegmentFixture.Create("C:", false, true), result.Value.Single()); } [Fact] public void ParsePath_WithTrailingBackslash_ShouldTreatLastSegmentAsDirectory() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents\"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User\Documents\"); // Act Result> result = _sut.ParsePath(path); @@ -404,14 +402,14 @@ public class WindowsPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Equal(4, result.Value.Count()); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("Documents", true, false), result.Value.Last()); + Assert.Equivalent(_pathSegmentFixture.Create("Documents", true, false), result.Value.Last()); } [Fact] public void ParsePath_WithRelativePath_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"Users\User"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"Users\User"); // Act Result> result = _sut.ParsePath(path); @@ -425,7 +423,7 @@ public class WindowsPathStrategyTests public void ParsePath_WithPathContainingDots_ShouldParseCorrectly() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\file.with.dots.txt"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User\file.with.dots.txt"); // Act Result> result = _sut.ParsePath(path); @@ -433,14 +431,14 @@ public class WindowsPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Equal(4, result.Value.Count()); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("file.with.dots.txt", false, false), result.Value.Last()); + Assert.Equivalent(_pathSegmentFixture.Create("file.with.dots.txt", false, false), result.Value.Last()); } [Fact] public void ParsePath_WithUNCPath_ShouldReturnCorrectPathSegments() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder\file.txt"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server\share\folder\file.txt"); // Act Result> result = _sut.ParsePath(path); @@ -448,18 +446,18 @@ public class WindowsPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Equal(5, result.Value.Count()); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment(@"\\", false, true), result.Value.ElementAt(0)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("server", true, false), result.Value.ElementAt(1)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("share", true, false), result.Value.ElementAt(2)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("folder", true, false), result.Value.ElementAt(3)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("file.txt", false, false), result.Value.ElementAt(4)); + Assert.Equivalent(_pathSegmentFixture.Create(@"\\", false, true), result.Value.ElementAt(0)); + Assert.Equivalent(_pathSegmentFixture.Create("server", true, false), result.Value.ElementAt(1)); + Assert.Equivalent(_pathSegmentFixture.Create("share", true, false), result.Value.ElementAt(2)); + Assert.Equivalent(_pathSegmentFixture.Create("folder", true, false), result.Value.ElementAt(3)); + Assert.Equivalent(_pathSegmentFixture.Create("file.txt", false, false), result.Value.ElementAt(4)); } [Fact] public void GoUpOneLevel_WithValidPath_ShouldReturnParentPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User\Documents"); // Act Result> result = _sut.GoUpOneLevel(path); @@ -467,16 +465,16 @@ public class WindowsPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Equal(3, result.Value.Count()); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("C:", false, true), result.Value.ElementAt(0)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("Users", true, false), result.Value.ElementAt(1)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("User", true, false), result.Value.ElementAt(2)); + Assert.Equivalent(_pathSegmentFixture.Create("C:", false, true), result.Value.ElementAt(0)); + Assert.Equivalent(_pathSegmentFixture.Create("Users", true, false), result.Value.ElementAt(1)); + Assert.Equivalent(_pathSegmentFixture.Create("User", true, false), result.Value.ElementAt(2)); } [Fact] public void GoUpOneLevel_WithRootPath_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\"); // Act Result> result = _sut.GoUpOneLevel(path); @@ -490,7 +488,7 @@ public class WindowsPathStrategyTests public void GoUpOneLevel_WithTrailingBackslash_ShouldReturnCorrectParentPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User\"); // Act Result> result = _sut.GoUpOneLevel(path); @@ -498,15 +496,15 @@ public class WindowsPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("C:", false, true), result.Value.ElementAt(0)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("Users", true, false), result.Value.ElementAt(1)); + Assert.Equivalent(_pathSegmentFixture.Create("C:", false, true), result.Value.ElementAt(0)); + Assert.Equivalent(_pathSegmentFixture.Create("Users", true, false), result.Value.ElementAt(1)); } [Fact] public void GoUpOneLevel_WithInvalidPath_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"invalid\path"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"invalid\path"); // Act Result> result = _sut.GoUpOneLevel(path); @@ -520,7 +518,7 @@ public class WindowsPathStrategyTests public void GoUpOneLevel_WithSingleLevelPath_ShouldReturnRootPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users"); // Act Result> result = _sut.GoUpOneLevel(path); @@ -528,14 +526,14 @@ public class WindowsPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Single(result.Value); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("C:", false, true), result.Value.Single()); + Assert.Equivalent(_pathSegmentFixture.Create("C:", false, true), result.Value.Single()); } [Fact] public void GoUpOneLevel_WithUNCPath_ShouldReturnParentPath() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder\subfolder"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server\share\folder\subfolder"); // Act Result> result = _sut.GoUpOneLevel(path); @@ -543,17 +541,17 @@ public class WindowsPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Equal(4, result.Value.Count()); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment(@"\\", false, true), result.Value.ElementAt(0)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("server", true, false), result.Value.ElementAt(1)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("share", true, false), result.Value.ElementAt(2)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("folder", true, false), result.Value.ElementAt(3)); + Assert.Equivalent(_pathSegmentFixture.Create(@"\\", false, true), result.Value.ElementAt(0)); + Assert.Equivalent(_pathSegmentFixture.Create("server", true, false), result.Value.ElementAt(1)); + Assert.Equivalent(_pathSegmentFixture.Create("share", true, false), result.Value.ElementAt(2)); + Assert.Equivalent(_pathSegmentFixture.Create("folder", true, false), result.Value.ElementAt(3)); } [Fact] public void GoUpOneLevel_WithUNCRootPath_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server\share"); // Act Result> result = _sut.GoUpOneLevel(path); @@ -567,7 +565,7 @@ public class WindowsPathStrategyTests public void GoUpOneLevel_WithUNCPathWithOneFolder_ShouldReturnUNCRoot() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server\share\folder"); // Act Result> result = _sut.GoUpOneLevel(path); @@ -575,16 +573,16 @@ public class WindowsPathStrategyTests // Assert Assert.False(result.IsFailure); Assert.Equal(3, result.Value.Count()); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment(@"\\", false, true), result.Value.ElementAt(0)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("server", true, false), result.Value.ElementAt(1)); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("share", true, false), result.Value.ElementAt(2)); + Assert.Equivalent(_pathSegmentFixture.Create(@"\\", false, true), result.Value.ElementAt(0)); + Assert.Equivalent(_pathSegmentFixture.Create("server", true, false), result.Value.ElementAt(1)); + Assert.Equivalent(_pathSegmentFixture.Create("share", true, false), result.Value.ElementAt(2)); } [Fact] public void GoUpOneLevel_WithDriveRootAndBackslash_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\"); // Act Result> result = _sut.GoUpOneLevel(path); @@ -631,35 +629,35 @@ public class WindowsPathStrategyTests public void GetPathRoot_WithValidWindowsPath_ShouldReturnRootSegment() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User\Documents"); // Act Result result = _sut.GetPathRoot(path); // Assert Assert.False(result.IsFailure); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("C:\\", true, true), result.Value); + Assert.Equivalent(_pathSegmentFixture.Create("C:\\", true, true), result.Value); } [Fact] public void GetPathRoot_WithRootPath_ShouldReturnRootSegment() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\"); // Act Result result = _sut.GetPathRoot(path); // Assert Assert.False(result.IsFailure); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment("C:\\", true, true), result.Value); + Assert.Equivalent(_pathSegmentFixture.Create("C:\\", true, true), result.Value); } [Fact] public void GetPathRoot_WithInvalidPath_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"InvalidFolder"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"InvalidFolder"); // Act Result result = _sut.GetPathRoot(path); @@ -673,21 +671,21 @@ public class WindowsPathStrategyTests public void GetPathRoot_WithUNCPath_ShouldReturnUNCRootSegment() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server\share\folder"); // Act Result result = _sut.GetPathRoot(path); // Assert Assert.False(result.IsFailure); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment(@"\\server\share\", true, false), result.Value); + Assert.Equivalent(_pathSegmentFixture.Create(@"\\server\share\", true, false), result.Value); } [Fact] public void GetPathRoot_WithInvalidUNCPath_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\"); // Act Result result = _sut.GetPathRoot(path); @@ -701,7 +699,7 @@ public class WindowsPathStrategyTests public void GetPathRoot_WithUNCPathWithoutShare_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server"); // Act Result result = _sut.GetPathRoot(path); @@ -715,7 +713,7 @@ public class WindowsPathStrategyTests public void GetPathRoot_WithNonDriveNonUNCPath_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"InvalidPath"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"InvalidPath"); // Act Result result = _sut.GetPathRoot(path); @@ -729,7 +727,7 @@ public class WindowsPathStrategyTests public void GetPathRoot_WithUNCPathMissingServerName_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\"); // Act Result result = _sut.GetPathRoot(path); @@ -743,21 +741,21 @@ public class WindowsPathStrategyTests public void GetPathRoot_WithUNCPathWithoutThirdBackslash_ShouldReturnServerAndShare() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server\share"); // Act Result result = _sut.GetPathRoot(path); // Assert Assert.False(result.IsFailure); - Assert.Equivalent(_pathSegmentFixture.CreatePathSegment(@"\\server\share\", true, false), result.Value); + Assert.Equivalent(_pathSegmentFixture.Create(@"\\server\share\", true, false), result.Value); } [Fact] public void GetPathRoot_WithNeitherUNCNorDrivePath_ShouldReturnError() { // Arrange - FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"invalid\path"); + FileSystemPathId path = _fileSystemPathIdFixture.Create(@"invalid\path"); // Act Result result = _sut.GetPathRoot(path); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextFactoryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextFactoryTests.cs similarity index 89% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextFactoryTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextFactoryTests.cs index cddec81b..c5272cd7 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextFactoryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextFactoryTests.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Platform.Fixtures; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; using Microsoft.Extensions.DependencyInjection; using System; using System.Diagnostics.CodeAnalysis; using System.IO.Abstractions; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManagerTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManagerTests.cs similarity index 97% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManagerTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManagerTests.cs index 0003dfb9..be42d503 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManagerTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManagerTests.cs @@ -7,7 +7,7 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; /// /// Contains unit tests for the class. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextTests.cs similarity index 96% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextTests.cs index f1a50b9f..56194f6e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/Strategies/Platform/PlatformContextTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextTests.cs @@ -6,7 +6,7 @@ using NSubstitute; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.Strategies.Platform; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; /// /// Contains unit tests for the and classes. diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdTests.cs similarity index 65% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdTests.cs index d3134664..039fa22f 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/FileSystemPathIdTests.cs @@ -2,11 +2,11 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; /// /// Contains unit tests for the class. @@ -14,15 +14,7 @@ namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate. [ExcludeFromCodeCoverage] public class FileSystemPathIdTests { - private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; - - /// - /// Initializes a new instance of the class. - /// - public FileSystemPathIdTests() - { - _fileSystemPathIdFixture = new FileSystemPathIdFixture(); - } + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); [Fact] public void Create_WithValidPath_ShouldReturnFileSystemPathId() @@ -57,8 +49,8 @@ public class FileSystemPathIdTests { // Arrange string path = @"C:\TestDir\file.txt"; - FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(path); - FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId id1 = _fileSystemPathIdFixture.Create(path); + FileSystemPathId id2 = _fileSystemPathIdFixture.Create(path); // Act bool result = id1.Equals(id2); @@ -71,8 +63,8 @@ public class FileSystemPathIdTests public void Equals_WithDifferentPath_ShouldReturnFalse() { // Arrange - FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file1.txt"); - FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file2.txt"); + FileSystemPathId id1 = _fileSystemPathIdFixture.Create(@"C:\TestDir\file1.txt"); + FileSystemPathId id2 = _fileSystemPathIdFixture.Create(@"C:\TestDir\file2.txt"); // Act bool result = id1.Equals(id2); @@ -86,8 +78,8 @@ public class FileSystemPathIdTests { // Arrange string path = @"C:\TestDir\file.txt"; - FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(path); - FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId id1 = _fileSystemPathIdFixture.Create(path); + FileSystemPathId id2 = _fileSystemPathIdFixture.Create(path); // Act int hashCode1 = id1.GetHashCode(); @@ -101,8 +93,8 @@ public class FileSystemPathIdTests public void GetHashCode_WithDifferentPath_ShouldReturnDifferentHashCode() { // Arrange - FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file1.txt"); - FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file2.txt"); + FileSystemPathId id1 = _fileSystemPathIdFixture.Create(@"C:\TestDir\file1.txt"); + FileSystemPathId id2 = _fileSystemPathIdFixture.Create(@"C:\TestDir\file2.txt"); // Act int hashCode1 = id1.GetHashCode(); @@ -117,8 +109,8 @@ public class FileSystemPathIdTests { // Arrange string path = @"C:\TestDir\file.txt"; - FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(path); - FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId id1 = _fileSystemPathIdFixture.Create(path); + FileSystemPathId id2 = _fileSystemPathIdFixture.Create(path); // Act bool result = id1 == id2; @@ -131,8 +123,8 @@ public class FileSystemPathIdTests public void InequalityOperator_WithDifferentPath_ShouldReturnTrue() { // Arrange - FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file1.txt"); - FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file2.txt"); + FileSystemPathId id1 = _fileSystemPathIdFixture.Create(@"C:\TestDir\file1.txt"); + FileSystemPathId id2 = _fileSystemPathIdFixture.Create(@"C:\TestDir\file2.txt"); // Act bool result = id1 != id2; diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/PathSegmentTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/PathSegmentTests.cs similarity index 65% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/PathSegmentTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/PathSegmentTests.cs index e606e493..22d49bbc 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/PathSegmentTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/PathSegmentTests.cs @@ -2,11 +2,11 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; /// /// Contains unit tests for the class. @@ -14,15 +14,7 @@ namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate. [ExcludeFromCodeCoverage] public class PathSegmentTests { - private readonly PathSegmentFixture _pathSegmentFixture; - - /// - /// Initializes a new instance of the class. - /// - public PathSegmentTests() - { - _pathSegmentFixture = new PathSegmentFixture(); - } + private readonly PathSegmentFixture _pathSegmentFixture = new(); [Fact] public void Create_WithValidInput_ShouldReturnPathSegment() @@ -60,8 +52,8 @@ public class PathSegmentTests public void Equals_WithSameProperties_ShouldReturnTrue() { // Arrange - PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder", true, false); - PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder", true, false); + PathSegment segment1 = _pathSegmentFixture.Create("folder", true, false); + PathSegment segment2 = _pathSegmentFixture.Create("folder", true, false); // Act bool result = segment1.Equals(segment2); @@ -74,8 +66,8 @@ public class PathSegmentTests public void Equals_WithDifferentProperties_ShouldReturnFalse() { // Arrange - PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder1", true, false); - PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder2", true, false); + PathSegment segment1 = _pathSegmentFixture.Create("folder1", true, false); + PathSegment segment2 = _pathSegmentFixture.Create("folder2", true, false); // Act bool result = segment1.Equals(segment2); @@ -88,8 +80,8 @@ public class PathSegmentTests public void GetHashCode_WithSameProperties_ShouldReturnSameHashCode() { // Arrange - PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder", true, false); - PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder", true, false); + PathSegment segment1 = _pathSegmentFixture.Create("folder", true, false); + PathSegment segment2 = _pathSegmentFixture.Create("folder", true, false); // Act int hashCode1 = segment1.GetHashCode(); @@ -103,8 +95,8 @@ public class PathSegmentTests public void GetHashCode_WithDifferentProperties_ShouldReturnDifferentHashCode() { // Arrange - PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder1", true, false); - PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder2", true, false); + PathSegment segment1 = _pathSegmentFixture.Create("folder1", true, false); + PathSegment segment2 = _pathSegmentFixture.Create("folder2", true, false); // Act int hashCode1 = segment1.GetHashCode(); @@ -118,8 +110,8 @@ public class PathSegmentTests public void EqualityOperator_WithSameProperties_ShouldReturnTrue() { // Arrange - PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder", true, false); - PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder", true, false); + PathSegment segment1 = _pathSegmentFixture.Create("folder", true, false); + PathSegment segment2 = _pathSegmentFixture.Create("folder", true, false); // Act bool result = segment1 == segment2; @@ -132,8 +124,8 @@ public class PathSegmentTests public void InequalityOperator_WithDifferentProperties_ShouldReturnTrue() { // Arrange - PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder1", true, false); - PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder2", true, false); + PathSegment segment1 = _pathSegmentFixture.Create("folder1", true, false); + PathSegment segment2 = _pathSegmentFixture.Create("folder2", true, false); // Act bool result = segment1 != segment2; diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/StreamInfoTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/StreamInfoTests.cs similarity index 83% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/StreamInfoTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/StreamInfoTests.cs index a2eba0e0..ec672c6c 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/StreamInfoTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/StreamInfoTests.cs @@ -2,12 +2,12 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; /// /// Contains unit tests for the class. @@ -15,15 +15,7 @@ namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate. [ExcludeFromCodeCoverage] public class StreamInfoTests { - private readonly StreamInfoFixture _streamInfoFixture; - - /// - /// Initializes a new instance of the class. - /// - public StreamInfoTests() - { - _streamInfoFixture = new StreamInfoFixture(); - } + private readonly StreamInfoFixture _streamInfoFixture = new(); [Fact] public void Create_WithValidInput_ShouldReturnStreamInfo() @@ -108,8 +100,8 @@ public class StreamInfoTests public void Equals_WithSameProperties_ShouldReturnTrue() { // Arrange - StreamInfo info1 = _streamInfoFixture.CreateStreamInfo(); - StreamInfo info2 = _streamInfoFixture.CreateStreamInfo( + StreamInfo info1 = _streamInfoFixture.Create(); + StreamInfo info2 = _streamInfoFixture.Create( info1.StreamId, info1.MimeType, info1.Bitrate, info1.Codec, info1.Resolution, info1.FrameRate, info1.SampleRate, info1.Channels); @@ -124,8 +116,8 @@ public class StreamInfoTests public void Equals_WithDifferentProperties_ShouldReturnFalse() { // Arrange - StreamInfo info1 = _streamInfoFixture.CreateStreamInfo(); - StreamInfo info2 = _streamInfoFixture.CreateStreamInfo(); + StreamInfo info1 = _streamInfoFixture.Create(); + StreamInfo info2 = _streamInfoFixture.Create(); // Act bool result = info1.Equals(info2); @@ -138,8 +130,8 @@ public class StreamInfoTests public void GetHashCode_WithSameProperties_ShouldReturnSameHashCode() { // Arrange - StreamInfo info1 = _streamInfoFixture.CreateStreamInfo(); - StreamInfo info2 = _streamInfoFixture.CreateStreamInfo( + StreamInfo info1 = _streamInfoFixture.Create(); + StreamInfo info2 = _streamInfoFixture.Create( info1.StreamId, info1.MimeType, info1.Bitrate, info1.Codec, info1.Resolution, info1.FrameRate, info1.SampleRate, info1.Channels); @@ -155,8 +147,8 @@ public class StreamInfoTests public void GetHashCode_WithDifferentProperties_ShouldReturnDifferentHashCode() { // Arrange - StreamInfo info1 = _streamInfoFixture.CreateStreamInfo(); - StreamInfo info2 = _streamInfoFixture.CreateStreamInfo(); + StreamInfo info1 = _streamInfoFixture.Create(); + StreamInfo info2 = _streamInfoFixture.Create(); // Act int hashCode1 = info1.GetHashCode(); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/ThumbnailTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/ThumbnailTests.cs similarity index 68% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/ThumbnailTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/ThumbnailTests.cs index 41df8389..b5b7cef3 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileSystemManagementAggregate/ValueObjects/ThumbnailTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/ThumbnailTests.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects.Fixtures; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate.ValueObjects; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; /// /// Contains unit tests for the class. @@ -16,15 +16,7 @@ namespace Lumina.Domain.UnitTests.Core.Aggregates.FileSystemManagementAggregate. [ExcludeFromCodeCoverage] public class ThumbnailTests { - private readonly ThumbnailFixture _thumbnailFixture; - - /// - /// Initializes a new instance of the class. - /// - public ThumbnailTests() - { - _thumbnailFixture = new ThumbnailFixture(); - } + private readonly ThumbnailFixture _thumbnailFixture = new(); [Fact] public void Constructor_WhenCalled_ShouldSetPropertiesCorrectly() @@ -45,7 +37,7 @@ public class ThumbnailTests public void Equals_WithSameProperties_ShouldReturnTrue() { // Arrange - Thumbnail thumbnail1 = _thumbnailFixture.CreateThumbnail(); + Thumbnail thumbnail1 = _thumbnailFixture.Create(); Thumbnail thumbnail2 = new(thumbnail1.Type, thumbnail1.Bytes); // Act @@ -59,8 +51,8 @@ public class ThumbnailTests public void Equals_WithDifferentType_ShouldReturnFalse() { // Arrange - Thumbnail thumbnail1 = _thumbnailFixture.CreateThumbnail(ImageType.PNG); - Thumbnail thumbnail2 = _thumbnailFixture.CreateThumbnail(ImageType.JPEG, thumbnail1.Bytes); + Thumbnail thumbnail1 = _thumbnailFixture.Create(ImageType.PNG); + Thumbnail thumbnail2 = _thumbnailFixture.Create(ImageType.JPEG, thumbnail1.Bytes); // Act bool result = thumbnail1.Equals(thumbnail2); @@ -73,8 +65,8 @@ public class ThumbnailTests public void Equals_WithDifferentBytes_ShouldReturnFalse() { // Arrange - Thumbnail thumbnail1 = _thumbnailFixture.CreateThumbnail(); - Thumbnail thumbnail2 = _thumbnailFixture.CreateThumbnail(thumbnail1.Type); + Thumbnail thumbnail1 = _thumbnailFixture.Create(); + Thumbnail thumbnail2 = _thumbnailFixture.Create(thumbnail1.Type); // Act bool result = thumbnail1.Equals(thumbnail2); @@ -87,7 +79,7 @@ public class ThumbnailTests public void GetHashCode_WithSameProperties_ShouldReturnSameHashCode() { // Arrange - Thumbnail thumbnail1 = _thumbnailFixture.CreateThumbnail(); + Thumbnail thumbnail1 = _thumbnailFixture.Create(); Thumbnail thumbnail2 = new(thumbnail1.Type, thumbnail1.Bytes); // Act @@ -102,8 +94,8 @@ public class ThumbnailTests public void GetHashCode_WithDifferentProperties_ShouldReturnDifferentHashCode() { // Arrange - Thumbnail thumbnail1 = _thumbnailFixture.CreateThumbnail(); - Thumbnail thumbnail2 = _thumbnailFixture.CreateThumbnail(); + Thumbnail thumbnail1 = _thumbnailFixture.Create(); + Thumbnail thumbnail2 = _thumbnailFixture.Create(); // Act int hashCode1 = thumbnail1.GetHashCode(); @@ -117,10 +109,10 @@ public class ThumbnailTests public void GetEqualityComponents_ShouldReturnTypeAndBytes() { // Arrange - Thumbnail thumbnail = _thumbnailFixture.CreateThumbnail(); + Thumbnail thumbnail = _thumbnailFixture.Create(); // Act - List components = thumbnail.GetEqualityComponents().ToList(); + List components = [.. thumbnail.GetEqualityComponents()]; // Assert Assert.Equal(2, components.Count); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/BookLibraryAggregate/BookTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs similarity index 80% rename from tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/BookLibraryAggregate/BookTests.cs rename to tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs index db79dd75..11427070 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/BookLibraryAggregate/BookTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; -using Lumina.Domain.UnitTests.Core.Aggregates.BookLibraryAggregate.Fixtures; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Domain.UnitTests.Core.Aggregates.BookLibraryAggregate; +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; /// /// Contains unit tests for the class. @@ -15,11 +14,13 @@ namespace Lumina.Domain.UnitTests.Core.Aggregates.BookLibraryAggregate; [ExcludeFromCodeCoverage] public class BookTests { + private readonly BookFixture _bookFixture = new(); + [Fact] public void Create_WhenCalledWithValidData_ShouldCreateBookWithPendingMetadataStatus() { // Act - Book book = BookFixture.CreateValidBook(); + Book book = _bookFixture.Create(); // Assert Assert.NotNull(book); @@ -32,7 +33,7 @@ public class BookTests public void MarkMetadataAsEnriched_WhenCalled_ShouldUpdateStatusAndProvider() { // Arrange - Book book = BookFixture.CreateValidBook(); + Book book = _bookFixture.Create(); DateTime lastUpdateUtc = DateTime.UtcNow; // Act @@ -48,7 +49,7 @@ public class BookTests public void MarkMetadataAsFailed_WhenCalled_ShouldUpdateStatus() { // Arrange - Book book = BookFixture.CreateValidBook(); + Book book = _bookFixture.Create(); // Act book.MarkMetadataAsFailed(); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj b/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj index b4d6e017..d4b1d67c 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj @@ -41,5 +41,7 @@ + + diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/OptionsBuilderValidationUtilitiesTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/OptionsBuilderValidationUtilitiesTests.cs index c852568a..5cfd42aa 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/OptionsBuilderValidationUtilitiesTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/OptionsBuilderValidationUtilitiesTests.cs @@ -4,7 +4,7 @@ using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Infrastructure.Common.Utilities; using Lumina.Infrastructure.Common.Validation; -using Lumina.Infrastructure.UnitTests.Common.Utilities.Fixtures; +using Lumina.Infrastructure.Fixtures.Common.Utilities; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using NSubstitute; diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/ValidationOptionsTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/ValidationOptionsTests.cs index 05a9f49b..f103f529 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/ValidationOptionsTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validation/ValidationOptionsTests.cs @@ -4,7 +4,7 @@ using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Domain.Common.Primitives; using Lumina.Infrastructure.Common.Validation; -using Lumina.Infrastructure.UnitTests.Common.Validation.Fixtures; +using Lumina.Infrastructure.Fixtures.Common.Validation; using Microsoft.Extensions.Options; using NSubstitute; using System; diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs index d41b6411..650670ef 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs @@ -17,7 +17,7 @@ namespace Lumina.Infrastructure.UnitTests.Common.Validators; [ExcludeFromCodeCoverage] public class CommonSettingsDtoValidatorTests { - private readonly CommonSettingsDtoValidator _validator; + private readonly CommonSettingsDtoValidator _validator = new(); private readonly IFixture _fixture; /// @@ -26,11 +26,10 @@ public class CommonSettingsDtoValidatorTests public CommonSettingsDtoValidatorTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _validator = new(); } [Fact] - public void CommonSettingsModelValidator_WhenThemeProvided_ShouldNotHaveValidationError() + public void Validate_WhenThemeProvided_ShouldNotHaveValidationError() { // Arrange CommonSettingsDto model = _fixture.Build() @@ -45,7 +44,7 @@ public class CommonSettingsDtoValidatorTests } [Fact] - public void CommonSettingsModelValidator_WhenThemeNotProvided_ShouldNotHaveValidationError() + public void Validate_WhenThemeNotProvided_ShouldNotHaveValidationError() { // Arrange CommonSettingsDto model = _fixture.Build() diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs index cf80f2e2..f89b4fc7 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs @@ -17,7 +17,7 @@ namespace Lumina.Infrastructure.UnitTests.Common.Validators; [ExcludeFromCodeCoverage] public class DatabaseSettingsDtoValidatorTests { - private readonly DatabaseSettingsDtoValidator _validator; + private readonly DatabaseSettingsDtoValidator _validator = new(); private readonly IFixture _fixture; /// @@ -26,11 +26,10 @@ public class DatabaseSettingsDtoValidatorTests public DatabaseSettingsDtoValidatorTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _validator = new(); } [Fact] - public void DatabaseSettingsModelValidator_WhenDefaultConnectionProvided_ShouldNotHaveValidationError() + public void Validate_WhenDefaultConnectionProvided_ShouldNotHaveValidationError() { // Arrange DatabaseSettingsDto model = _fixture.Build() @@ -45,7 +44,7 @@ public class DatabaseSettingsDtoValidatorTests } [Fact] - public void DatabaseSettingsModelValidator_WhenDefaultConnectionNotProvided_ShouldHaveValidationError() + public void Validate_WhenDefaultConnectionNotProvided_ShouldHaveValidationError() { // Arrange DatabaseSettingsDto model = _fixture.Build() diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsDtoValidatorTests.cs index aae59a10..735bba56 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsDtoValidatorTests.cs @@ -17,7 +17,7 @@ namespace Lumina.Infrastructure.UnitTests.Common.Validators; [ExcludeFromCodeCoverage] public class EncryptionSettingsDtoValidatorTests { - private readonly EncryptionSettingsDtoValidator _validator; + private readonly EncryptionSettingsDtoValidator _validator = new(); private readonly IFixture _fixture; /// @@ -26,11 +26,10 @@ public class EncryptionSettingsDtoValidatorTests public EncryptionSettingsDtoValidatorTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _validator = new(); } [Fact] - public void EncryptionSettingsModelValidator_WhenValidBase64SecretKeyProvided_ShouldNotHaveValidationError() + public void Validate_WhenValidBase64SecretKeyProvided_ShouldNotHaveValidationError() { // Arrange EncryptionSettingsDto model = _fixture.Build() @@ -45,7 +44,7 @@ public class EncryptionSettingsDtoValidatorTests } [Fact] - public void EncryptionSettingsModelValidator_WhenSecretKeyIsEmpty_ShouldHaveValidationError() + public void Validate_WhenSecretKeyIsEmpty_ShouldHaveValidationError() { // Arrange EncryptionSettingsDto model = _fixture.Build() @@ -64,7 +63,7 @@ public class EncryptionSettingsDtoValidatorTests [InlineData("not-a-base64-string")] [InlineData("invalid!base64")] [InlineData("123")] - public void EncryptionSettingsModelValidator_WhenSecretKeyIsNotBase64_ShouldHaveValidationError(string invalidBase64) + public void Validate_WhenSecretKeyIsNotBase64_ShouldHaveValidationError(string invalidBase64) { // Arrange EncryptionSettingsDto model = _fixture.Build() diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsDtoValidatorTests.cs index 01b14622..97fc2c30 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsDtoValidatorTests.cs @@ -17,7 +17,7 @@ namespace Lumina.Infrastructure.UnitTests.Common.Validators; [ExcludeFromCodeCoverage] public class JwtSettingsDtoValidatorTests { - private readonly JwtSettingsDtoValidator _validator; + private readonly JwtSettingsDtoValidator _validator = new(); private readonly IFixture _fixture; /// @@ -26,11 +26,10 @@ public class JwtSettingsDtoValidatorTests public JwtSettingsDtoValidatorTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _validator = new(); } [Fact] - public void JwtSettingsModelValidator_WhenAllPropertiesValid_ShouldNotHaveValidationError() + public void Validate_WhenAllPropertiesValid_ShouldNotHaveValidationError() { // Arrange JwtSettingsDto model = _fixture.Build() @@ -48,7 +47,7 @@ public class JwtSettingsDtoValidatorTests } [Fact] - public void JwtSettingsModelValidator_WhenSecretKeyIsEmpty_ShouldHaveValidationErrors() + public void Validate_WhenSecretKeyIsEmpty_ShouldHaveValidationErrors() { // Arrange JwtSettingsDto model = _fixture.Build() @@ -68,7 +67,7 @@ public class JwtSettingsDtoValidatorTests } [Fact] - public void JwtSettingsModelValidator_WhenSecretKeyTooShort_ShouldHaveValidationError() + public void Validate_WhenSecretKeyTooShort_ShouldHaveValidationError() { // Arrange JwtSettingsDto model = _fixture.Build() @@ -90,7 +89,7 @@ public class JwtSettingsDtoValidatorTests [InlineData(0)] [InlineData(-1)] [InlineData(-60)] - public void JwtSettingsModelValidator_WhenExpiryMinutesNotPositive_ShouldHaveValidationError(int minutes) + public void Validate_WhenExpiryMinutesNotPositive_ShouldHaveValidationError(int minutes) { // Arrange JwtSettingsDto model = _fixture.Build() @@ -109,7 +108,7 @@ public class JwtSettingsDtoValidatorTests } [Fact] - public void JwtSettingsModelValidator_WhenIssuerIsEmpty_ShouldHaveValidationError() + public void Validate_WhenIssuerIsEmpty_ShouldHaveValidationError() { // Arrange JwtSettingsDto model = _fixture.Build() @@ -128,7 +127,7 @@ public class JwtSettingsDtoValidatorTests } [Fact] - public void JwtSettingsModelValidator_WhenAudienceIsEmpty_ShouldHaveValidationError() + public void Validate_WhenAudienceIsEmpty_ShouldHaveValidationError() { // Arrange JwtSettingsDto model = _fixture.Build() diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsDtoValidatorTests.cs index d7c19f9f..809b4731 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsDtoValidatorTests.cs @@ -17,7 +17,7 @@ namespace Lumina.Infrastructure.UnitTests.Common.Validators; [ExcludeFromCodeCoverage] public class MediaSettingsDtoValidatorTests { - private readonly MediaSettingsDtoValidator _validator; + private readonly MediaSettingsDtoValidator _validator = new(); private readonly IFixture _fixture; /// @@ -26,11 +26,10 @@ public class MediaSettingsDtoValidatorTests public MediaSettingsDtoValidatorTests() { _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _validator = new(); } [Fact] - public void MediaSettingsModelValidator_WhenRootDirectoryProvided_ShouldNotHaveValidationError() + public void Validate_WhenRootDirectoryProvided_ShouldNotHaveValidationError() { // Arrange MediaSettingsDto model = _fixture.Build() @@ -45,7 +44,7 @@ public class MediaSettingsDtoValidatorTests } [Fact] - public void MediaSettingsModelValidator_WhenRootDirectoryIsEmpty_ShouldHaveValidationError() + public void Validate_WhenRootDirectoryIsEmpty_ShouldHaveValidationError() { // Arrange MediaSettingsDto model = _fixture.Build() @@ -61,7 +60,7 @@ public class MediaSettingsDtoValidatorTests } [Fact] - public void MediaSettingsModelValidator_WhenRootDirectoryIsWhitespace_ShouldHaveValidationError() + public void Validate_WhenRootDirectoryIsWhitespace_ShouldHaveValidationError() { // Arrange MediaSettingsDto model = _fixture.Build() @@ -77,7 +76,7 @@ public class MediaSettingsDtoValidatorTests } [Fact] - public void MediaSettingsModelValidator_WhenMediaLibrariesDirectoryIsEmpty_ShouldHaveValidationError() + public void Validate_WhenMediaLibrariesDirectoryIsEmpty_ShouldHaveValidationError() { // Arrange MediaSettingsDto model = _fixture.Build() @@ -93,7 +92,7 @@ public class MediaSettingsDtoValidatorTests } [Fact] - public void MediaSettingsModelValidator_WhenMediaLibrariesDirectoryProvided_ShouldNotHaveValidationError() + public void Validate_WhenMediaLibrariesDirectoryProvided_ShouldNotHaveValidationError() { // Arrange MediaSettingsDto model = _fixture.Build() @@ -108,7 +107,7 @@ public class MediaSettingsDtoValidatorTests } [Fact] - public void MediaSettingsModelValidator_WhenMediaLibrariesDirectoryIsWhitespace_ShouldHaveValidationError() + public void Validate_WhenMediaLibrariesDirectoryIsWhitespace_ShouldHaveValidationError() { // Arrange MediaSettingsDto model = _fixture.Build() diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/JwtTokenGeneratorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/JwtTokenGeneratorTests.cs index b3fb32db..a44ebe31 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/JwtTokenGeneratorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/JwtTokenGeneratorTests.cs @@ -2,7 +2,7 @@ using Lumina.Application.Common.Infrastructure.Time; using Lumina.Infrastructure.Common.Models.DTO.Configuration; using Lumina.Infrastructure.Core.Authentication; -using Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures; +using Lumina.Infrastructure.Fixtures.Core.Authentication; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using NSubstitute; diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/QRCodeGeneratorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/QRCodeGeneratorTests.cs index 1573c1be..3bbc5912 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/QRCodeGeneratorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/QRCodeGeneratorTests.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Infrastructure.Core.Authentication; -using Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures; +using Lumina.Infrastructure.Fixtures.Core.Authentication; using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -13,15 +13,7 @@ namespace Lumina.Infrastructure.UnitTests.Core.Authentication; [ExcludeFromCodeCoverage] public class QRCodeGeneratorTests { - private readonly QRCodeGenerator _sut; - - /// - /// Initializes a new instance of the class. - /// - public QRCodeGeneratorTests() - { - _sut = new QRCodeGenerator(); - } + private readonly QRCodeGenerator _sut = new(); [Fact] public void GenerateQrCodeDataUri_WhenCalled_ShouldReturnValidDataUri() diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TokenGeneratorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TokenGeneratorTests.cs index 6ac19cde..b6f6ea42 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TokenGeneratorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TokenGeneratorTests.cs @@ -11,15 +11,7 @@ namespace Lumina.Infrastructure.UnitTests.Core.Authentication; [ExcludeFromCodeCoverage] public class TokenGeneratorTests { - private readonly TokenGenerator _sut; - - /// - /// Initializes a new instance of the class. - /// - public TokenGeneratorTests() - { - _sut = new TokenGenerator(); - } + private readonly TokenGenerator _sut = new(); [Fact] public void GenerateToken_WhenCalled_ShouldGenerateNonEmptyToken() diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TotpTokenGeneratorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TotpTokenGeneratorTests.cs index fc8adccc..72dfe00b 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TotpTokenGeneratorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TotpTokenGeneratorTests.cs @@ -12,15 +12,7 @@ namespace Lumina.Infrastructure.UnitTests.Core.Authentication; [ExcludeFromCodeCoverage] public class TotpTokenGeneratorTests { - private readonly TotpTokenGenerator _sut; - - /// - /// Initializes a new instance of the class. - /// - public TotpTokenGeneratorTests() - { - _sut = new TotpTokenGenerator(); - } + private readonly TotpTokenGenerator _sut = new(); [Fact] public void GenerateSecret_WhenCalled_ShouldGenerateNonEmptySecret() diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs index c7205cd1..d56b04ae 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs @@ -9,7 +9,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Infrastructure.Core.Authorization; using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory; -using Lumina.Infrastructure.UnitTests.Core.Authorization.Fixtures; +using Lumina.Infrastructure.Fixtures.Core.Authorization; using NSubstitute; using NSubstitute.ExceptionExtensions; using System; diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Common/Factory/AuthorizationPolicyFactoryTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Common/Factory/AuthorizationPolicyFactoryTests.cs index a319b479..70b5cbdd 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Common/Factory/AuthorizationPolicyFactoryTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Common/Factory/AuthorizationPolicyFactoryTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory; -using Lumina.Infrastructure.UnitTests.Core.Authorization.Policies.Common.Factory.Fixtures; +using Lumina.Infrastructure.Fixtures.Core.Authorization; using Microsoft.Extensions.DependencyInjection; using NSubstitute; using System; @@ -48,7 +48,7 @@ public class AuthorizationPolicyFactoryTests Action act = () => policyFactory.CreatePolicy(); InvalidOperationException exception = Assert.Throws(() => policyFactory.CreatePolicy()); - Assert.Equal("No service for type 'Lumina.Infrastructure.UnitTests.Core.Authorization.Policies.Common.Factory.Fixtures.IUnregisteredPolicy' has been registered.", + Assert.Equal("No service for type 'Lumina.Infrastructure.Fixtures.Core.Authorization.IUnregisteredPolicy' has been registered.", exception.Message); } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/CryptographyServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/CryptographyServiceTests.cs index 7c72a4b4..82d89ff7 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/CryptographyServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/CryptographyServiceTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Infrastructure.Common.Models.DTO.Configuration; using Lumina.Infrastructure.Core.Security; -using Lumina.Infrastructure.UnitTests.Core.Security.Fixtures; +using Lumina.Infrastructure.Fixtures.Core.Security; using Microsoft.Extensions.Options; using System; using System.Diagnostics.CodeAnalysis; diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/HashServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/HashServiceTests.cs index de079de3..72599e89 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/HashServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/HashServiceTests.cs @@ -12,15 +12,7 @@ namespace Lumina.Infrastructure.UnitTests.Core.Security; [ExcludeFromCodeCoverage] public class HashServiceTests { - private readonly PasswordHashService _sut; - - /// - /// Initializes a new instance of the class. - /// - public HashServiceTests() - { - _sut = new PasswordHashService(); - } + private readonly PasswordHashService _sut = new(); [Fact] public void HashString_WhenCalled_ShouldReturnNonEmptyHash() diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj index 3caf1927..9daa4aa2 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj @@ -40,6 +40,7 @@ + diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Fakes/FakeBookMetadataProvider.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Common/Fakes/FakeBookMetadataProvider.cs similarity index 99% rename from tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Fakes/FakeBookMetadataProvider.cs rename to tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Common/Fakes/FakeBookMetadataProvider.cs index c72dfc21..598ff362 100644 --- a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Fakes/FakeBookMetadataProvider.cs +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Common/Fakes/FakeBookMetadataProvider.cs @@ -13,7 +13,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Plugins.Contracts.UnitTests.Fakes; +namespace Lumina.Plugins.Contracts.UnitTests.Common.Fakes; /// /// A fake book metadata provider used to exercise the plugin contracts from outside. diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Metadata/RemoteMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/RemoteMetadataProviderTests.cs similarity index 79% rename from tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Metadata/RemoteMetadataProviderTests.cs rename to tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/RemoteMetadataProviderTests.cs index 2c94544a..a08c8ba3 100644 --- a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Metadata/RemoteMetadataProviderTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/RemoteMetadataProviderTests.cs @@ -2,21 +2,23 @@ using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Plugins.Contracts.Core.Metadata; -using Lumina.Plugins.Contracts.UnitTests.Fakes; +using Lumina.Plugins.Contracts.UnitTests.Common.Fakes; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Plugins.Contracts.UnitTests.Metadata; +namespace Lumina.Plugins.Contracts.UnitTests.Core.Metadata; /// /// Contains unit tests for the contracts. /// +[ExcludeFromCodeCoverage] public class RemoteMetadataProviderTests { - private readonly IRemoteMetadataProvider _provider = new FakeBookMetadataProvider(); + private readonly IRemoteMetadataProvider _sut = new FakeBookMetadataProvider(); [Fact] public async Task GetMetadataAsync_WhenCalledThroughNonGenericInterface_ShouldReturnTypedMetadata() @@ -28,7 +30,7 @@ public class RemoteMetadataProviderTests Title: "The Fellowship of the Ring"); // Act - MetadataDto? result = await _provider.GetMetadataAsync(lookup, CancellationToken.None); + MetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); // Assert Assert.NotNull(result); @@ -46,7 +48,7 @@ public class RemoteMetadataProviderTests Path: "/books/unknown.epub"); // Act - MetadataDto? result = await _provider.GetMetadataAsync(lookup, CancellationToken.None); + MetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); // Assert Assert.Null(result); @@ -62,7 +64,7 @@ public class RemoteMetadataProviderTests Title: "The Fellowship of the Ring"); // Act - IReadOnlyList result = await _provider.GetSearchResultsAsync(lookup, CancellationToken.None); + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); // Assert Assert.Single(result); diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Plugins/PluginTests.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Plugins/PluginTests.cs similarity index 73% rename from tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Plugins/PluginTests.cs rename to tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Plugins/PluginTests.cs index ed6f0901..048b6ab4 100644 --- a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Plugins/PluginTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Plugins/PluginTests.cs @@ -1,24 +1,28 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Plugins.Contracts.Core.Plugins; using Lumina.Plugins.Contracts.Core.Plugins.Settings; -using Lumina.Plugins.Contracts.UnitTests.Fakes; +using Lumina.Plugins.Contracts.UnitTests.Common.Fakes; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Plugins.Contracts.UnitTests.Plugins; +namespace Lumina.Plugins.Contracts.UnitTests.Core.Plugins; /// /// Contains unit tests for the contract. /// +[ExcludeFromCodeCoverage] public class PluginTests { - private readonly IPlugin _plugin = new FakeBookMetadataProvider(); + private readonly IPlugin _sut = new FakeBookMetadataProvider(); [Fact] public void GetSettingsSchema_WhenCalled_ShouldReturnDeclaredSettings() { + // Arrange + // Act - IReadOnlyList schema = _plugin.GetSettingsSchema(); + IReadOnlyList schema = _sut.GetSettingsSchema(); // Assert Assert.Equal(2, schema.Count); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs index 7443689f..2f382176 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs @@ -2,7 +2,7 @@ using FastEndpoints; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Primitives; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.Common.Fixtures; +using Lumina.Presentation.Api.Fixtures.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using System.Collections.Generic; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs index b859460c..01355311 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Directories; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Directories; using Lumina.Contracts.Requests.FileSystemManagement.Directories; using Lumina.Contracts.Responses.FileSystemManagement.Directories; using Lumina.Domain.Common.Primitives; @@ -27,16 +27,16 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class GetDirectoriesEndpointTests { - private readonly IFixture _fixture; private readonly IQueryHandler>> _mockHandler; private readonly GetDirectoriesEndpoint _sut; + private readonly GetDirectoriesRequestFixture _getDirectoriesRequestFixture = new(); + private readonly DirectoryResponseFixture _directoryResponseFixture = new(); /// /// Initializes a new instance of the class. /// public GetDirectoriesEndpointTests() { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockHandler = Substitute.For>>>(); _sut = Factory.Create(_mockHandler); } @@ -45,9 +45,9 @@ public class GetDirectoriesEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithDirectoryResponses() { // Arrange - GetDirectoriesRequest request = _fixture.Create(); + GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - List expectedResponses = [.. _fixture.CreateMany(3)]; + List expectedResponses = [.. _directoryResponseFixture.CreateMany(3)]; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponses.AsEnumerable())); @@ -63,7 +63,7 @@ public class GetDirectoriesEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange - GetDirectoriesRequest request = _fixture.Create(); + GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("Directory.NotFound", "The requested directory was not found."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -89,7 +89,7 @@ public class GetDirectoriesEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() { // Arrange - GetDirectoriesRequest request = _fixture.Create(); + GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -115,7 +115,7 @@ public class GetDirectoriesEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendGetDirectoriesQueryToHandler() { // Arrange - GetDirectoriesRequest request = _fixture.Create(); + GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Enumerable.Empty())); @@ -133,7 +133,7 @@ public class GetDirectoriesEndpointTests public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { // Arrange - GetDirectoriesRequest request = _fixture.Create(); + GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(); CancellationTokenSource cts = new(); TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); @@ -144,7 +144,7 @@ public class GetDirectoriesEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(_fixture.CreateMany(3).AsEnumerable()); + return Result.From(_directoryResponseFixture.CreateMany(3).AsEnumerable()); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs index 1e0e0a67..61619e12 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs @@ -2,10 +2,10 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Common; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.GetDrives; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -27,7 +27,7 @@ public class GetDrivesEndpointTests { private readonly IQueryHandler>> _mockHandler; private readonly GetDrivesEndpoint _sut; - private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; + private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -35,7 +35,6 @@ public class GetDrivesEndpointTests public GetDrivesEndpointTests() { _mockHandler = Substitute.For>>>(); - _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); _sut = Factory.Create(_mockHandler); } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs index 7a0d5075..e2bfe3cd 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs @@ -20,15 +20,15 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. /// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] -public class GetFileSystemTypeEndpointTests +public class GetTypeEndpointTests { private readonly IQueryHandler _mockHandler; private readonly GetTypeEndpoint _sut; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public GetFileSystemTypeEndpointTests() + public GetTypeEndpointTests() { _mockHandler = Substitute.For>(); _sut = Factory.Create(_mockHandler); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs index 1351a284..04e95ae8 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Files; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Files; using Lumina.Contracts.Requests.FileSystemManagement.Files; using Lumina.Contracts.Responses.FileSystemManagement.Files; using Lumina.Domain.Common.Primitives; @@ -27,16 +27,16 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class GetFilesEndpointTests { - private readonly IFixture _fixture; private readonly IQueryHandler>> _mockHandler; private readonly GetFilesEndpoint _sut; + private readonly GetFilesRequestFixture _getFilesRequestFixture = new(); + private readonly FileResponseFixture _fileResponseFixture = new(); /// /// Initializes a new instance of the class. /// public GetFilesEndpointTests() { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockHandler = Substitute.For>>>(); _sut = Factory.Create(_mockHandler); } @@ -45,9 +45,9 @@ public class GetFilesEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileResponses() { // Arrange - GetFilesRequest request = _fixture.Create(); + GetFilesRequest request = _getFilesRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - List expectedResponses = [.. _fixture.CreateMany(3)]; + List expectedResponses = [.. _fileResponseFixture.CreateMany(3)]; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponses.AsEnumerable())); @@ -63,7 +63,7 @@ public class GetFilesEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange - GetFilesRequest request = _fixture.Create(); + GetFilesRequest request = _getFilesRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("File.NotFound", "The requested file was not found."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -89,7 +89,7 @@ public class GetFilesEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() { // Arrange - GetFilesRequest request = _fixture.Create(); + GetFilesRequest request = _getFilesRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -115,7 +115,7 @@ public class GetFilesEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendGetFilesQueryToSender() { // Arrange - GetFilesRequest request = _fixture.Create(); + GetFilesRequest request = _getFilesRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Enumerable.Empty())); @@ -134,7 +134,7 @@ public class GetFilesEndpointTests public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { // Arrange - GetFilesRequest request = _fixture.Create(); + GetFilesRequest request = _getFilesRequestFixture.Create(); CancellationTokenSource cts = new(); TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); @@ -145,7 +145,7 @@ public class GetFilesEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(_fixture.CreateMany(3).AsEnumerable()); + return Result.From(_fileResponseFixture.CreateMany(3).AsEnumerable()); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs index 69ca18ed..4f6d6440 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs @@ -1,14 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Files; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Common; using Lumina.Contracts.Requests.FileSystemManagement.Files; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -28,19 +27,17 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement. [ExcludeFromCodeCoverage] public class GetTreeFilesEndpointTests { - private readonly IFixture _fixture; private readonly IQueryHandler>> _mockHandler; private readonly GetTreeFilesEndpoint _sut; - private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; + private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture = new(); + private readonly GetTreeFilesRequestFixture _getTreeFilesRequestFixture = new(); /// /// Initializes a new instance of the class. /// public GetTreeFilesEndpointTests() { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); _mockHandler = Substitute.For>>>(); - _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); _sut = Factory.Create(_mockHandler); } @@ -48,7 +45,7 @@ public class GetTreeFilesEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses() { // Arrange - GetTreeFilesRequest request = _fixture.Create(); + GetTreeFilesRequest request = _getTreeFilesRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -66,7 +63,7 @@ public class GetTreeFilesEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange - GetTreeFilesRequest request = _fixture.Create(); + GetTreeFilesRequest request = _getTreeFilesRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("File.NotFound", "The requested file was not found."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -92,7 +89,7 @@ public class GetTreeFilesEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() { // Arrange - GetTreeFilesRequest request = _fixture.Create(); + GetTreeFilesRequest request = _getTreeFilesRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -118,7 +115,7 @@ public class GetTreeFilesEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendGetTreeFilesQueryToSender() { // Arrange - GetTreeFilesRequest request = _fixture.Create(); + GetTreeFilesRequest request = _getTreeFilesRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Enumerable.Empty())); @@ -137,7 +134,7 @@ public class GetTreeFilesEndpointTests public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { // Arrange - GetTreeFilesRequest request = _fixture.Create(); + GetTreeFilesRequest request = _getTreeFilesRequestFixture.Create(); CancellationTokenSource cts = new(); TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs deleted file mode 100644 index cd87c6d0..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs +++ /dev/null @@ -1,58 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class FileSystemTreeNodeResponseFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a single with a nested structure. - /// - /// The current depth in the tree structure. Default is 0 (root level). - /// The maximum depth of the tree structure. Default is 2. - /// The maximum number of children for each node. Default is 3. - /// A with a nested structure. - public FileSystemTreeNodeResponse Create(int currentDepth = 0, int maxDepth = 2, int maxChildren = 3) - { - FileSystemTreeNodeResponse response = new() - { - Path = _faker.System.FilePath(), - Name = _faker.System.FileName(), - ItemType = FileSystemItemType.Directory, - IsExpanded = _faker.Random.Bool(), - ChildrenLoaded = true, - Children = [] - }; - if (currentDepth < maxDepth) - { - int childCount = _faker.Random.Int(1, maxChildren); - for (int i = 0; i < childCount; i++) - response.Children.Add(Create(currentDepth + 1, maxDepth, maxChildren)); - } - return response; - } - - /// - /// Creates a list of objects, each with a nested structure. - /// - /// The number of root-level nodes to create. Default is 2. - /// The maximum depth of the tree structure for each root node. Default is 2. - /// The maximum number of children for each node. Default is 3. - /// A list of objects with nested structures. - public List CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3) - { - return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList(); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/PathSegmentResponseFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/PathSegmentResponseFixture.cs deleted file mode 100644 index e38fb301..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/PathSegmentResponseFixture.cs +++ /dev/null @@ -1,37 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.Responses.FileSystemManagement.Path; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class PathSegmentResponseFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a random valid . - /// - /// The created . - public PathSegmentResponse Create() - { - return new PathSegmentResponse(_faker.System.DirectoryPath()); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return Enumerable.Range(0, count).Select(_ => Create()).ToList(); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/PathSeparatorResponseFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/PathSeparatorResponseFixture.cs deleted file mode 100644 index 79a80e14..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/PathSeparatorResponseFixture.cs +++ /dev/null @@ -1,37 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.Responses.FileSystemManagement.Path; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class PathSeparatorResponseFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a random valid . - /// - /// The created . - public PathSeparatorResponse Create() - { - return new PathSeparatorResponse(_faker.System.DirectoryPath()); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return Enumerable.Range(0, count).Select(_ => Create()).ToList(); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/ThumbnailResponseFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/ThumbnailResponseFixture.cs deleted file mode 100644 index 54348fb2..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Fixtures/ThumbnailResponseFixture.cs +++ /dev/null @@ -1,30 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; -using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class ThumbnailResponseFixture -{ - /// - /// Creates a random valid query to get a thumbnail. - /// - /// The created query. - public static ThumbnailResponse CreateThumbnailResponse() - { - return new Faker() - .CustomInstantiator(f => new ThumbnailResponse( - default, - default! - )) - .RuleFor(x => x.Type, f => f.PickRandom()) - .RuleFor(x => x.Bytes, f => f.Random.Bytes(20)); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs index da53bac9..a8e555e9 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs @@ -2,11 +2,11 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -26,7 +26,7 @@ public class CheckPathExistsEndpointTests { private readonly IQueryHandler> _mockHandler; private readonly CheckPathExistsEndpoint _sut; - private readonly CheckPathExistsRequestFixture _checkPathExistsRequestFixture; + private readonly CheckPathExistsRequestFixture _checkPathExistsRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -35,7 +35,6 @@ public class CheckPathExistsEndpointTests { _mockHandler = Substitute.For>>(); _sut = Factory.Create(_mockHandler); - _checkPathExistsRequestFixture = new CheckPathExistsRequestFixture(); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs index dbee370b..e46be9e1 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs @@ -1,11 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CombinePath; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -25,8 +26,8 @@ public class CombinePathEndpointTests { private readonly ICommandHandler> _mockHandler; private readonly CombinePathEndpoint _sut; - private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; - private readonly CombinePathRequestFixture _combinePathRequestFixture; + private readonly PathSegmentResponseFixture _pathSegmentResponseFixture = new(); + private readonly CombinePathRequestFixture _combinePathRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -35,8 +36,6 @@ public class CombinePathEndpointTests { _mockHandler = Substitute.For>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); - _pathSegmentResponseFixture = new PathSegmentResponseFixture(); - _combinePathRequestFixture = new CombinePathRequestFixture(); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs index 3bf48f13..12f46f8f 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs @@ -2,11 +2,12 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathParent; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -28,8 +29,8 @@ public class GetPathParentEndpointTests { private readonly IQueryHandler>> _mockHandler; private readonly GetPathParentEndpoint _sut; - private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; - private readonly GetPathParentRequestFixture _getPathParentRequestFixture; + private readonly PathSegmentResponseFixture _pathSegmentResponseFixture = new(); + private readonly GetPathParentRequestFixture _getPathParentRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -38,8 +39,6 @@ public class GetPathParentEndpointTests { _mockHandler = Substitute.For>>>(); _sut = Factory.Create(_mockHandler); - _pathSegmentResponseFixture = new PathSegmentResponseFixture(); - _getPathParentRequestFixture = new GetPathParentRequestFixture(); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs index c5b06a4a..114649d4 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs @@ -2,11 +2,12 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -26,8 +27,8 @@ public class GetPathRootEndpointTests { private readonly IQueryHandler> _mockHandler; private readonly GetPathRootEndpoint _sut; - private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; - private readonly GetPathRootRequestFixture _getPathRootRequestFixture; + private readonly PathSegmentResponseFixture _pathSegmentResponseFixture = new(); + private readonly GetPathRootRequestFixture _getPathRootRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -36,8 +37,6 @@ public class GetPathRootEndpointTests { _mockHandler = Substitute.For>>(); _sut = Factory.Create(_mockHandler); - _pathSegmentResponseFixture = new PathSegmentResponseFixture(); - _getPathRootRequestFixture = new GetPathRootRequestFixture(); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs index 39d4baf2..a6d471ce 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs @@ -2,9 +2,9 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSeparator; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -24,7 +24,7 @@ public class GetPathSeparatorEndpointTests { private readonly IQueryHandler _mockHandler; private readonly GetPathSeparatorEndpoint _sut; - private readonly PathSeparatorResponseFixture _pathSeparatorResponseFixture; + private readonly PathSeparatorResponseFixture _pathSeparatorResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -33,7 +33,6 @@ public class GetPathSeparatorEndpointTests { _mockHandler = Substitute.For>(); _sut = Factory.Create(_mockHandler); - _pathSeparatorResponseFixture = new PathSeparatorResponseFixture(); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs index 7c7fe6e4..26e8ec27 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs @@ -1,11 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.SplitPath; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -27,8 +28,8 @@ public class SplitPathEndpointTests { private readonly ICommandHandler>> _mockHandler; private readonly SplitPathEndpoint _sut; - private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; - private readonly SplitPathRequestFixture _splitPathRequestFixture; + private readonly PathSegmentResponseFixture _pathSegmentResponseFixture = new(); + private readonly SplitPathRequestFixture _splitPathRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -37,8 +38,6 @@ public class SplitPathEndpointTests { _mockHandler = Substitute.For>>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); - _pathSegmentResponseFixture = new PathSegmentResponseFixture(); - _splitPathRequestFixture = new SplitPathRequestFixture(); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs index 7ff2d1d2..530fb3a3 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs @@ -2,11 +2,11 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.ValidatePath; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -26,7 +26,7 @@ public class ValidatePathEndpointTests { private readonly IQueryHandler> _mockHandler; private readonly ValidatePathEndpoint _sut; - private readonly ValidatePathRequestFixture _validatePathRequestFixture; + private readonly ValidatePathRequestFixture _validatePathRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -35,7 +35,6 @@ public class ValidatePathEndpointTests { _mockHandler = Substitute.For>>(); _sut = Factory.Create(_mockHandler); - _validatePathRequestFixture = new ValidatePathRequestFixture(); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs index d087b5a4..689fb0f5 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs @@ -2,12 +2,13 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail; +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Thumbnails; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Thumbnails; using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Utilities; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -27,7 +28,8 @@ public class GetThumbnailEndpointTests { private readonly IQueryHandler> _mockHandler; private readonly GetThumbnailEndpoint _sut; - private readonly GetThumbnailRequestFixture _getThumbnailRequestFixture; + private readonly GetThumbnailRequestFixture _getThumbnailRequestFixture = new(); + private readonly ThumbnailResponseFixture _thumbnailResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -36,7 +38,6 @@ public class GetThumbnailEndpointTests { _mockHandler = Substitute.For>>(); _sut = Factory.Create(_mockHandler); - _getThumbnailRequestFixture = new GetThumbnailRequestFixture(); } [Fact] @@ -45,7 +46,7 @@ public class GetThumbnailEndpointTests // Arrange GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/file.jpg", 80); CancellationToken cancellationToken = CancellationToken.None; - ThumbnailResponse expectedResponse = ThumbnailResponseFixture.CreateThumbnailResponse(); + ThumbnailResponse expectedResponse = _thumbnailResponseFixture.Create(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -117,7 +118,7 @@ public class GetThumbnailEndpointTests GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/file.jpg", 80); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(ThumbnailResponseFixture.CreateThumbnailResponse())); + .Returns(Result.From(_thumbnailResponseFixture.Create())); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -141,7 +142,7 @@ public class GetThumbnailEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(ThumbnailResponseFixture.CreateThumbnailResponse()); + return Result.From(_thumbnailResponseFixture.Create()); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs similarity index 57% rename from tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs rename to tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs index 0791190b..dc9ca110 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books; +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook; internal class AddBookEndpointTests { } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/Fixtures/RegistrationRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/Fixtures/RegistrationRequestFixture.cs deleted file mode 100644 index 2b4bbd5a..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/Fixtures/RegistrationRequestFixture.cs +++ /dev/null @@ -1,39 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.Requests.Authentication; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.ApplicationSetup.Fixtures; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class RegistrationRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a with default or random values. - /// - /// The username for registration. - /// The password for registration. - /// The password confirmation. - /// Whether to use two-factor authentication. - /// The created . - public RegistrationRequest Create( - string? username = null, - string? password = null, - string? passwordConfirm = null, - bool? use2fa = null) - { - string generatedPassword = password ?? _faker.Internet.Password(); - return new RegistrationRequest( - Username: username ?? _faker.Internet.UserName(), - Password: generatedPassword, - PasswordConfirm: passwordConfirm ?? generatedPassword, - Use2fa: use2fa ?? _faker.Random.Bool() - ); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs index 1f422d8b..b6077b29 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.ApplicationSetup.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -25,7 +25,7 @@ public class SetupApplicationEndpointTests { private readonly ICommandHandler> _mockHandler; private readonly SetupApplicationEndpoint _sut; - private readonly RegistrationRequestFixture _registrationRequestFixture; + private readonly RegistrationRequestFixture _registrationRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -34,7 +34,6 @@ public class SetupApplicationEndpointTests { _mockHandler = Substitute.For>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); - _registrationRequestFixture = new RegistrationRequestFixture(); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs index 243f0ed7..6351bd06 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.ChangePassword; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -25,7 +25,7 @@ public class ChangePasswordEndpointTests { private readonly ICommandHandler> _mockHandler; private readonly ChangePasswordEndpoint _sut; - private readonly ChangePasswordRequestFixture _changePasswordRequestFixture; + private readonly ChangePasswordRequestFixture _changePasswordRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -34,7 +34,6 @@ public class ChangePasswordEndpointTests { _mockHandler = Substitute.For>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); - _changePasswordRequestFixture = new ChangePasswordRequestFixture(); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs deleted file mode 100644 index d37b5eba..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs +++ /dev/null @@ -1,39 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.Requests.Authentication; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword.Fixtures; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class ChangePasswordRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a with default or random values. - /// - /// The username for the password change. - /// The current password. - /// The new password. - /// The new password confirmation. - /// The created . - public ChangePasswordRequest Create( - string? username = null, - string? currentPassword = null, - string? newPassword = null, - string? newPasswordConfirm = null) - { - string generatedNewPassword = newPassword ?? _faker.Internet.Password(); - return new ChangePasswordRequest( - Username: username ?? _faker.Internet.UserName(), - CurrentPassword: currentPassword ?? _faker.Internet.Password(), - NewPassword: generatedNewPassword, - NewPasswordConfirm: newPasswordConfirm ?? generatedNewPassword - ); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/Fixtures/LoginRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/Fixtures/LoginRequestFixture.cs deleted file mode 100644 index 4f706305..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/Fixtures/LoginRequestFixture.cs +++ /dev/null @@ -1,35 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.Requests.Authentication; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.Login.Fixtures; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class LoginRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a with default or random values. - /// - /// The username for login. - /// The password for login. - /// The TOTP code for two-factor authentication. - /// The created . - public LoginRequest Create( - string? username = null, - string? password = null, - string? totpCode = null) - { - return new LoginRequest( - Username: username ?? _faker.Internet.UserName(), - Password: password ?? _faker.Internet.Password(), - TotpCode: totpCode ?? _faker.Random.Number(100000, 999999).ToString() - ); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs index 0e6a6b52..fde135ee 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs @@ -2,11 +2,11 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Login; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.Login.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -26,7 +26,7 @@ public class LoginEndpointTests { private readonly IQueryHandler> _mockHandler; private readonly LoginEndpoint _sut; - private readonly LoginRequestFixture _loginRequestFixture; + private readonly LoginRequestFixture _loginRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -35,7 +35,6 @@ public class LoginEndpointTests { _mockHandler = Substitute.For>>(); _sut = Factory.Create(_mockHandler); - _loginRequestFixture = new LoginRequestFixture(); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs deleted file mode 100644 index a8cb5d73..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs +++ /dev/null @@ -1,32 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.Requests.Authentication; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword.Fixtures; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class RecoverPasswordRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a with default or random values. - /// - /// The username for password recovery. - /// The TOTP code for verification. - /// The created . - public RecoverPasswordRequest Create( - string? username = null, - string? totpCode = null) - { - return new RecoverPasswordRequest( - Username: username ?? _faker.Internet.UserName(), - TotpCode: totpCode ?? _faker.Random.Number(100000, 999999).ToString() - ); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs index 4045c969..79250010 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -25,7 +25,7 @@ public class RecoverPasswordEndpointTests { private readonly ICommandHandler> _mockHandler; private readonly RecoverPasswordEndpoint _sut; - private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture; + private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -34,7 +34,6 @@ public class RecoverPasswordEndpointTests { _mockHandler = Substitute.For>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); - _recoverPasswordRequestFixture = new RecoverPasswordRequestFixture(); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/Fixtures/RegistrationRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/Fixtures/RegistrationRequestFixture.cs deleted file mode 100644 index ea6955fe..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/Fixtures/RegistrationRequestFixture.cs +++ /dev/null @@ -1,39 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.Requests.Authentication; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.Register.Fixtures; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class RegistrationRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a with default or random values. - /// - /// The username for registration. - /// The password for registration. - /// The password confirmation. - /// Whether to use two-factor authentication. - /// The created . - public RegistrationRequest Create( - string? username = null, - string? password = null, - string? passwordConfirm = null, - bool? use2fa = null) - { - string generatedPassword = password ?? _faker.Internet.Password(); - return new RegistrationRequest( - Username: username ?? _faker.Internet.UserName(), - Password: generatedPassword, - PasswordConfirm: passwordConfirm ?? generatedPassword, - Use2fa: use2fa ?? _faker.Random.Bool() - ); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs index f003d344..f7a8184c 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.ApplicationSetup.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -25,7 +25,7 @@ public class RegisterEndpointTests { private readonly ICommandHandler> _mockHandler; private readonly RegisterEndpoint _sut; - private readonly RegistrationRequestFixture _registrationRequestFixture; + private readonly RegistrationRequestFixture _registrationRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -34,7 +34,6 @@ public class RegisterEndpointTests { _mockHandler = Substitute.For>>(); _sut = FastEndpoints.Factory.Create(_mockHandler); - _registrationRequestFixture = new RegistrationRequestFixture(); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs index 2e38b242..cb9bfaa0 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs @@ -2,12 +2,12 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.GetAuthorization; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authorization.GetAuthorization.Fixtures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; @@ -29,6 +29,7 @@ public class GetAuthorizationEndpointTests { private readonly IQueryHandler> _mockHandler; private readonly GetAuthorizationEndpoint _sut; + private readonly GetAuthorizationRequestFixture _getAuthorizationRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -43,7 +44,7 @@ public class GetAuthorizationEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithAuthorizationResponse() { // Arrange - GetAuthorizationRequest request = GetAuthorizationRequestFixture.Create(); + GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; AuthorizationResponse expectedResponse = new( request.UserId!.Value, @@ -65,7 +66,7 @@ public class GetAuthorizationEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange - GetAuthorizationRequest request = GetAuthorizationRequestFixture.Create(); + GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Unauthorized("Authorization.Failed", "User is not authorized."); @@ -92,7 +93,7 @@ public class GetAuthorizationEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendGetAuthorizationQueryToSender() { // Arrange - GetAuthorizationRequest request = GetAuthorizationRequestFixture.Create(); + GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -116,7 +117,7 @@ public class GetAuthorizationEndpointTests public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { // Arrange - GetAuthorizationRequest request = GetAuthorizationRequestFixture.Create(); + GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(); CancellationTokenSource cts = new(); TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj index 33bdde26..a16f6132 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj @@ -41,5 +41,7 @@ + +