mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 04:11:10 +00:00
Centralizes and standardizes test fixtures.
This commit is contained in:
1 parent
dfc513da4f
commit
b648e2f054
294 files changed
+3807
-4437
No files matched your search
+6
-6
@@ -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;
|
||||
@@ -64,7 +64,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<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
@@ -81,7 +81,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<CancellationToken>())
|
||||
@@ -102,7 +102,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<CancellationToken>())
|
||||
@@ -124,7 +124,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<CancellationToken>())
|
||||
.Returns(true);
|
||||
@@ -145,7 +145,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()
|
||||
{
|
||||
|
||||
+8
-8
@@ -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;
|
||||
@@ -33,7 +33,7 @@ public class AddRoleCommandValidatorTests
|
||||
public void Validate_WhenRoleNameIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddRoleCommand command = _fixture.CreateCommand();
|
||||
AddRoleCommand command = _fixture.Create();
|
||||
command = command with { RoleName = null! };
|
||||
|
||||
// Act
|
||||
@@ -47,7 +47,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 +61,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 +75,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 +89,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 +103,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 +117,7 @@ public class AddRoleCommandValidatorTests
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddRoleCommand command = _fixture.CreateCommand();
|
||||
AddRoleCommand command = _fixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
-34
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AddRoleCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddRoleCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command to add a role.
|
||||
/// </summary>
|
||||
/// <param name="permissionCount">The number of permissions to generate.</param>
|
||||
/// <returns>The created command to add a role.</returns>
|
||||
public AddRoleCommand CreateCommand(int permissionCount = 3)
|
||||
{
|
||||
return new Faker<AddRoleCommand>()
|
||||
.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();
|
||||
}
|
||||
}
|
||||
+7
-7
@@ -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;
|
||||
@@ -61,7 +61,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<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
@@ -78,7 +78,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<CancellationToken>())
|
||||
.Returns(true);
|
||||
@@ -98,7 +98,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<CancellationToken>())
|
||||
@@ -119,7 +119,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<CancellationToken>())
|
||||
@@ -140,7 +140,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 +164,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<CancellationToken>())
|
||||
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.DeleteRole.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="DeleteRoleCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteRoleCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command to delete a role.
|
||||
/// </summary>
|
||||
/// <returns>The created command.</returns>
|
||||
public DeleteRoleCommand CreateCommand()
|
||||
{
|
||||
return new Faker<DeleteRoleCommand>()
|
||||
.CustomInstantiator(f => new DeleteRoleCommand(
|
||||
Guid.NewGuid()))
|
||||
.Generate();
|
||||
}
|
||||
}
|
||||
-46
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateRoleCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateRoleCommandFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateRoleCommandFixture"/> class.
|
||||
/// </summary>
|
||||
public UpdateRoleCommandFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid command to update a role.
|
||||
/// </summary>
|
||||
/// <param name="permissionCount">The number of permissions to generate.</param>
|
||||
/// <returns>The created command to update a role.</returns>
|
||||
public UpdateRoleCommand CreateCommand(int permissionCount = 3)
|
||||
{
|
||||
return new Faker<UpdateRoleCommand>()
|
||||
.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();
|
||||
}
|
||||
}
|
||||
+6
-6
@@ -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;
|
||||
@@ -64,7 +64,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<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
@@ -81,7 +81,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<CancellationToken>())
|
||||
@@ -102,7 +102,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<CancellationToken>())
|
||||
@@ -124,7 +124,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<CancellationToken>())
|
||||
.Returns(true);
|
||||
@@ -145,7 +145,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,
|
||||
|
||||
+9
-9
@@ -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;
|
||||
@@ -33,7 +33,7 @@ public class UpdateRoleCommandValidatorTests
|
||||
public void Validate_WhenRoleIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateRoleCommand command = _fixture.CreateCommand();
|
||||
UpdateRoleCommand command = _fixture.Create();
|
||||
command = command with { RoleId = Guid.Empty };
|
||||
|
||||
// Act
|
||||
@@ -47,7 +47,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 +61,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 +75,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 +89,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 +103,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 +117,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 +131,7 @@ public class UpdateRoleCommandValidatorTests
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateRoleCommand command = _fixture.CreateCommand();
|
||||
UpdateRoleCommand command = _fixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.GetRolePermissions.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetRolePermissionsQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRolePermissionsQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get role permissions.
|
||||
/// </summary>
|
||||
/// <returns>The created query.</returns>
|
||||
public GetRolePermissionsQuery CreateQuery()
|
||||
{
|
||||
return new Faker<GetRolePermissionsQuery>()
|
||||
.CustomInstantiator(f => new GetRolePermissionsQuery(
|
||||
Guid.NewGuid()))
|
||||
.Generate();
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -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;
|
||||
@@ -63,7 +63,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<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
@@ -80,7 +80,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<CancellationToken>())
|
||||
@@ -100,7 +100,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<CancellationToken>())
|
||||
.Returns(true);
|
||||
@@ -119,7 +119,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,
|
||||
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.GetRoles.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetRolesQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRolesQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get roles.
|
||||
/// </summary>
|
||||
/// <returns>The created query.</returns>
|
||||
public GetRolesQuery CreateQuery()
|
||||
{
|
||||
return new GetRolesQuery();
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -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;
|
||||
@@ -58,7 +58,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<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
@@ -75,7 +75,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<CancellationToken>())
|
||||
@@ -95,7 +95,7 @@ public class GetRolesQueryHandlerTests
|
||||
public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnRoles()
|
||||
{
|
||||
// Arrange
|
||||
GetRolesQuery query = _getRolesQueryFixture.CreateQuery();
|
||||
GetRolesQuery query = _getRolesQueryFixture.Create();
|
||||
IEnumerable<RoleEntity> roles =
|
||||
[
|
||||
new RoleEntity { Id = Guid.NewGuid(), RoleName = "Admin" },
|
||||
|
||||
-115
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="Directory"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DirectoryFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DirectoryFixture"/> class.
|
||||
/// </summary>
|
||||
public DirectoryFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="Directory"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">Optional. The directory path. If not provided, a random path is generated.</param>
|
||||
/// <param name="name">Optional. The directory name. If not provided, a random name is generated.</param>
|
||||
/// <param name="dateCreated">Optional. The directory's creation date. If not provided, a random past date is generated.</param>
|
||||
/// <param name="dateModified">Optional. The directory's modification date. If not provided, a recent date is generated.</param>
|
||||
/// <param name="status">Optional. The directory's status. If not provided, a random status is assigned.</param>
|
||||
/// <param name="childItems">Optional. A list of child items to be added to the directory.</param>
|
||||
/// <returns>A newly created Directory instance.</returns>
|
||||
/// <exception cref="InvalidOperationException">Thrown if the Directory creation fails.</exception>
|
||||
public Directory CreateDirectory(
|
||||
string? path = null,
|
||||
string? name = null,
|
||||
Optional<DateTime>? dateCreated = null,
|
||||
Optional<DateTime>? dateModified = null,
|
||||
FileSystemItemStatus? status = null,
|
||||
List<FileSystemItem>? childItems = null)
|
||||
{
|
||||
path ??= _faker.System.FilePath();
|
||||
name ??= _faker.System.FileName();
|
||||
dateCreated ??= Optional<DateTime>.Some(_faker.Date.Past());
|
||||
dateModified ??= Optional<DateTime>.Some(_faker.Date.Recent());
|
||||
status ??= _faker.PickRandom<FileSystemItemStatus>();
|
||||
|
||||
Result<Directory> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="Directory"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<Directory> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => CreateDirectory())];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of nested <see cref="Directory"/> objects with a hierarchical structure.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of top-level directories to create. Default is 3.</param>
|
||||
/// <param name="maxDepth">The maximum depth of the directory hierarchy. Default is 3.</param>
|
||||
/// <param name="maxChildrenPerDirectory">The maximum number of child items (files or directories) per directory. Default is 3.</param>
|
||||
/// <returns>A list of <see cref="Directory"/> objects with nested structures.</returns>
|
||||
public List<Directory> CreateManyNested(int count = 3, int maxDepth = 3, int maxChildrenPerDirectory = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => CreateNestedDirectory(1, maxDepth, maxChildrenPerDirectory))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recursively creates a nested <see cref="Directory"/> structure.
|
||||
/// </summary>
|
||||
/// <param name="currentDepth">The current depth in the directory hierarchy.</param>
|
||||
/// <param name="maxDepth">The maximum allowed depth for the directory hierarchy.</param>
|
||||
/// <param name="maxChildrenPerDirectory">The maximum number of child items (files or directories) allowed per directory.</param>
|
||||
/// <returns>A <see cref="Directory"/> object that may contain nested directories and files.</returns>
|
||||
private Directory CreateNestedDirectory(int currentDepth, int maxDepth, int maxChildrenPerDirectory)
|
||||
{
|
||||
List<FileSystemItem> 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<Updated> addResult = childDirectory.SetParent(childDirectory);
|
||||
if (!addResult.IsFailure)
|
||||
childItems.Add(childDirectory);
|
||||
}
|
||||
}
|
||||
return CreateDirectory(childItems: childItems);
|
||||
}
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="DirectoryResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DirectoryResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly FileSystemItemDtoFixture _fileSystemItemModelFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="DirectoryResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="itemCount">The number of children elements to create.</param>
|
||||
/// <returns>The created <see cref="DirectoryResponse"/>.</returns>
|
||||
public DirectoryResponse Create(int itemCount = 3)
|
||||
{
|
||||
return new DirectoryResponse(
|
||||
_faker.System.FilePath(),
|
||||
_faker.System.FileName(),
|
||||
_faker.Date.Past(),
|
||||
_faker.Date.Recent(),
|
||||
_fileSystemItemModelFixture.CreateMany(itemCount)
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="DirectoryResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <param name="itemCount">The number of children elemens to create for each element.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<DirectoryResponse> CreateMany(int count = 3, int itemCount = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count).Select(_ => Create(itemCount)).ToList();
|
||||
}
|
||||
}
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.DTO.FileSystemManagement;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FileSystemItemDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileSystemItemDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="FileSystemItemDto"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="FileSystemItemDto"/>.</returns>
|
||||
public FileSystemItemDto Create()
|
||||
{
|
||||
return new FileSystemItemDto(
|
||||
_faker.System.FilePath(),
|
||||
_faker.System.FileName(),
|
||||
_faker.Date.Past(),
|
||||
_faker.Date.Recent()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="FileSystemItemDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<FileSystemItemDto> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
|
||||
}
|
||||
}
|
||||
-58
@@ -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.Directories.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FileSystemTreeNodeResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileSystemTreeNodeResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a single <see cref="FileSystemTreeNodeResponse"/> with a nested structure.
|
||||
/// </summary>
|
||||
/// <param name="currentDepth">The current depth in the tree structure. Default is 0 (root level).</param>
|
||||
/// <param name="maxDepth">The maximum depth of the tree structure. Default is 2.</param>
|
||||
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
|
||||
/// <returns>A <see cref="FileSystemTreeNodeResponse"/> with a nested structure.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="FileSystemTreeNodeResponse"/> objects, each with a nested structure.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of root-level nodes to create. Default is 2.</param>
|
||||
/// <param name="maxDepth">The maximum depth of the tree structure for each root node. Default is 2.</param>
|
||||
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
|
||||
/// <returns>A list of <see cref="FileSystemTreeNodeResponse"/> objects with nested structures.</returns>
|
||||
public List<FileSystemTreeNodeResponse> CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList();
|
||||
}
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetDirectoriesQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDirectoriesQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get directories.
|
||||
/// </summary>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <returns>The created query to get directories.</returns>
|
||||
public static GetDirectoriesQuery CreateGetDirectoriesQuery(bool includeHiddenElements = false)
|
||||
{
|
||||
return new Faker<GetDirectoriesQuery>()
|
||||
.CustomInstantiator(f => new GetDirectoriesQuery(
|
||||
default!,
|
||||
default
|
||||
))
|
||||
.RuleFor(x => x.Path, f => f.System.DirectoryPath())
|
||||
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
|
||||
}
|
||||
}
|
||||
+8
-6
@@ -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;
|
||||
@@ -30,6 +30,7 @@ public class GetDirectoriesQueryHandlerTests
|
||||
private readonly IDirectoryService _mockDirectoryService;
|
||||
private readonly GetDirectoriesQueryHandler _sut;
|
||||
private readonly DirectoryFixture _directoryFixture;
|
||||
private readonly GetDirectoriesQueryFixture _getDirectoriesQueryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDirectoriesQueryHandlerTests"/> class.
|
||||
@@ -43,13 +44,14 @@ public class GetDirectoriesQueryHandlerTests
|
||||
.Returns([]);
|
||||
_sut = new GetDirectoriesQueryHandler(_mockDirectoryService, mockValidator);
|
||||
_directoryFixture = new DirectoryFixture();
|
||||
_getDirectoriesQueryFixture = new GetDirectoriesQueryFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalledWithValidQueryWithoutFilesIncluded_ShouldReturnSuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoriesQuery getDirectoriesQuery = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(false);
|
||||
GetDirectoriesQuery getDirectoriesQuery = _getDirectoriesQueryFixture.Create(includeHiddenElements: false);
|
||||
|
||||
IEnumerable<Directory> directories = _directoryFixture.CreateMany();
|
||||
|
||||
@@ -83,7 +85,7 @@ public class GetDirectoriesQueryHandlerTests
|
||||
public async Task HandleAsync_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoriesQuery getDirectoriesQuery = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(true);
|
||||
GetDirectoriesQuery getDirectoriesQuery = _getDirectoriesQueryFixture.Create(includeHiddenElements: true);
|
||||
|
||||
IEnumerable<Directory> directories = _directoryFixture.CreateMany();
|
||||
|
||||
@@ -117,7 +119,7 @@ public class GetDirectoriesQueryHandlerTests
|
||||
public async Task HandleAsync_WhenDirectoryServiceReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoriesQuery query = _fixture.Create<GetDirectoriesQuery>();
|
||||
GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create();
|
||||
Error error = Error.Failure("DirectoryService.Error", "An error occurred");
|
||||
_mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements)
|
||||
.Returns(error);
|
||||
@@ -135,7 +137,7 @@ public class GetDirectoriesQueryHandlerTests
|
||||
public async Task HandleAsync_WhenDirectoryServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoriesQuery query = _fixture.Create<GetDirectoriesQuery>();
|
||||
GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create();
|
||||
Result<IEnumerable<Directory>> emptyList = Result.From(Enumerable.Empty<Directory>());
|
||||
_mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements)
|
||||
.Returns(emptyList);
|
||||
|
||||
+9
-7
@@ -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;
|
||||
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Que
|
||||
public class GetDirectoriesQueryValidatorTests
|
||||
{
|
||||
private readonly GetDirectoriesQueryValidator _validator;
|
||||
private readonly GetDirectoriesQueryFixture _getDirectoriesQueryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDirectoriesQueryValidatorTests"/> class.
|
||||
@@ -24,13 +25,14 @@ public class GetDirectoriesQueryValidatorTests
|
||||
public GetDirectoriesQueryValidatorTests()
|
||||
{
|
||||
_validator = new GetDirectoriesQueryValidator();
|
||||
_getDirectoriesQueryFixture = new GetDirectoriesQueryFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery();
|
||||
GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create();
|
||||
query = query with { Path = null! };
|
||||
|
||||
// Act
|
||||
@@ -44,7 +46,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 +60,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 +74,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 +88,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 +102,7 @@ public class GetDirectoriesQueryValidatorTests
|
||||
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery();
|
||||
GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create();
|
||||
query = query with { IncludeHiddenElements = false };
|
||||
|
||||
// Act
|
||||
|
||||
-58
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetDrivesQueryFixture"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDrivesQueryFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a single <see cref="FileSystemTreeNodeResponse"/> with a nested structure.
|
||||
/// </summary>
|
||||
/// <param name="currentDepth">The current depth in the tree structure. Default is 0 (root level).</param>
|
||||
/// <param name="maxDepth">The maximum depth of the tree structure. Default is 2.</param>
|
||||
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
|
||||
/// <returns>A <see cref="FileSystemTreeNodeResponse"/> with a nested structure.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="FileSystemTreeNodeResponse"/> objects, each with a nested structure.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of root-level nodes to create. Default is 2.</param>
|
||||
/// <param name="maxDepth">The maximum depth of the tree structure for each root node. Default is 2.</param>
|
||||
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
|
||||
/// <returns>A list of <see cref="FileSystemTreeNodeResponse"/> objects with nested structures.</returns>
|
||||
public List<FileSystemTreeNodeResponse> CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList();
|
||||
}
|
||||
}
|
||||
+6
-7
@@ -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,17 +23,17 @@ 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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDrivesQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public GetDrivesQueryHandlerTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_mockDriveService = Substitute.For<IDriveService>();
|
||||
_getDrivesQueryFixture = new GetDrivesQueryFixture();
|
||||
_sut = new GetDrivesQueryHandler(_mockDriveService);
|
||||
}
|
||||
|
||||
@@ -42,7 +41,7 @@ public class GetDrivesQueryHandlerTests
|
||||
public async Task HandleAsync_WhenCalled_ShouldReturnSuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetDrivesQuery getDrivesQuery = _fixture.Create<GetDrivesQuery>();
|
||||
GetDrivesQuery getDrivesQuery = _getDrivesQueryFixture.Create();
|
||||
|
||||
IEnumerable<FileSystemItem> drives =
|
||||
[
|
||||
@@ -84,7 +83,7 @@ public class GetDrivesQueryHandlerTests
|
||||
public async Task HandleAsync_WhenDriveServiceReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
GetDrivesQuery query = _fixture.Create<GetDrivesQuery>();
|
||||
GetDrivesQuery query = _getDrivesQueryFixture.Create();
|
||||
Error error = Error.Failure("DriveService.Error", "An error occurred");
|
||||
_mockDriveService.GetDrives()
|
||||
.Returns(error);
|
||||
@@ -102,7 +101,7 @@ public class GetDrivesQueryHandlerTests
|
||||
public async Task HandleAsync_WhenDriveServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetDrivesQuery query = _fixture.Create<GetDrivesQuery>();
|
||||
GetDrivesQuery query = _getDrivesQueryFixture.Create();
|
||||
Result<IEnumerable<FileSystemItem>> emptyList = Result.From(Enumerable.Empty<FileSystemItem>());
|
||||
_mockDriveService.GetDrives()
|
||||
.Returns(emptyList);
|
||||
|
||||
-33
@@ -1,33 +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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UnixRootItem"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UnixRootItemFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="UnixRootItem"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="UnixRootItem"/>.</returns>
|
||||
public UnixRootItem Create()
|
||||
{
|
||||
Result<UnixRootItem> unixRootItemResult = UnixRootItem.Create(
|
||||
_faker.PickRandom<FileSystemItemStatus>()
|
||||
);
|
||||
if (unixRootItemResult.IsFailure)
|
||||
throw new InvalidOperationException("Failed to create File: " + string.Join(", ", unixRootItemResult.Errors));
|
||||
return unixRootItemResult.Value;
|
||||
}
|
||||
}
|
||||
-35
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="WindowsRootItem"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class WindowsRootItemFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="WindowsRootItem"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="WindowsRootItem"/>.</returns>
|
||||
public WindowsRootItem Create()
|
||||
{
|
||||
Result<WindowsRootItem> windowsRootItemResult = WindowsRootItem.Create(
|
||||
_faker.System.FilePath(),
|
||||
_faker.System.FileName(),
|
||||
_faker.PickRandom<FileSystemItemStatus>()
|
||||
);
|
||||
if (windowsRootItemResult.IsFailure)
|
||||
throw new InvalidOperationException("Failed to create File: " + string.Join(", ", windowsRootItemResult.Errors));
|
||||
return windowsRootItemResult.Value;
|
||||
}
|
||||
}
|
||||
+9
-6
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFileSystemQueryHandlerTests"/> class.
|
||||
@@ -34,6 +36,7 @@ public class GetFileSystemQueryHandlerTests
|
||||
_mockPlatformContextManager = Substitute.For<IPlatformContextManager>();
|
||||
_mockPlatformContext = Substitute.For<IPlatformContext>();
|
||||
_mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext);
|
||||
_getFileSystemQueryFixture = new GetFileSystemQueryFixture();
|
||||
_sut = new GetFileSystemQueryHandler(_mockPlatformContextManager);
|
||||
}
|
||||
|
||||
@@ -43,7 +46,7 @@ public class GetFileSystemQueryHandlerTests
|
||||
public async Task HandleAsync_WhenCalled_ShouldReturnCorrectFileSystemTypeResponse(PlatformType platformType)
|
||||
{
|
||||
// Arrange
|
||||
GetFileSystemQuery query = _fixture.Create<GetFileSystemQuery>();
|
||||
GetFileSystemQuery query = _getFileSystemQueryFixture.Create();
|
||||
_mockPlatformContext.Platform.Returns(platformType);
|
||||
|
||||
// Act
|
||||
@@ -59,7 +62,7 @@ public class GetFileSystemQueryHandlerTests
|
||||
public async Task HandleAsync_WhenCalled_ShouldReturnValueTaskResult()
|
||||
{
|
||||
// Arrange
|
||||
GetFileSystemQuery query = _fixture.Create<GetFileSystemQuery>();
|
||||
GetFileSystemQuery query = _getFileSystemQueryFixture.Create();
|
||||
_mockPlatformContext.Platform.Returns(PlatformType.Unix);
|
||||
|
||||
// Act
|
||||
@@ -76,8 +79,8 @@ public class GetFileSystemQueryHandlerTests
|
||||
public async Task HandleAsync_WhenCalled_ShouldNotDependOnQueryContent()
|
||||
{
|
||||
// Arrange
|
||||
GetFileSystemQuery query1 = _fixture.Create<GetFileSystemQuery>();
|
||||
GetFileSystemQuery query2 = _fixture.Create<GetFileSystemQuery>();
|
||||
GetFileSystemQuery query1 = _getFileSystemQueryFixture.Create();
|
||||
GetFileSystemQuery query2 = _getFileSystemQueryFixture.Create();
|
||||
_mockPlatformContext.Platform.Returns(PlatformType.Windows);
|
||||
|
||||
// Act
|
||||
@@ -93,7 +96,7 @@ public class GetFileSystemQueryHandlerTests
|
||||
public async Task HandleAsync_WhenCalled_ShouldIgnoreCancellationToken()
|
||||
{
|
||||
// Arrange
|
||||
GetFileSystemQuery query = _fixture.Create<GetFileSystemQuery>();
|
||||
GetFileSystemQuery query = _getFileSystemQueryFixture.Create();
|
||||
_mockPlatformContext.Platform.Returns(PlatformType.Unix);
|
||||
CancellationToken cancellationToken = new(true);
|
||||
|
||||
|
||||
-81
@@ -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.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="File"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileFixture"/> class.
|
||||
/// </summary>
|
||||
public FileFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="File"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="File"/>.</returns>
|
||||
public File CreateFile(
|
||||
string? path = null,
|
||||
string? name = null,
|
||||
Optional<DateTime>? dateCreated = null,
|
||||
Optional<DateTime>? dateModified = null,
|
||||
long? size = null,
|
||||
FileSystemItemStatus? status = null)
|
||||
{
|
||||
path ??= _faker.System.FilePath();
|
||||
name ??= _faker.System.FileName();
|
||||
dateCreated ??= Optional<DateTime>.Some(_faker.Date.Past());
|
||||
dateModified ??= Optional<DateTime>.Some(_faker.Date.Recent());
|
||||
size ??= _faker.Random.Long();
|
||||
status ??= _faker.PickRandom<FileSystemItemStatus>();
|
||||
|
||||
Result<File> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="File"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<File> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => CreateFile())];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="File"/>, without creationg and modification dates.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static File CreateFileWithoutDates()
|
||||
{
|
||||
return File.Create(
|
||||
"/path/to/file_without_dates.txt",
|
||||
"file_without_dates.txt",
|
||||
Optional<DateTime>.None(),
|
||||
Optional<DateTime>.None(),
|
||||
2048,
|
||||
FileSystemItemStatus.Accessible
|
||||
).Value;
|
||||
}
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Files;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FileResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="FileResponse"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="FileResponse"/>.</returns>
|
||||
public FileResponse Create()
|
||||
{
|
||||
return new FileResponse(
|
||||
_faker.System.FilePath(),
|
||||
_faker.System.FileName(),
|
||||
_faker.Date.Past(),
|
||||
_faker.Date.Recent(),
|
||||
_faker.Random.Long()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="FileResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<FileResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
|
||||
}
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetFilesQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFilesQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get files.
|
||||
/// </summary>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <returns>The created query to get files.</returns>
|
||||
public static GetFilesQuery CreateGetFilesQuery(bool includeHiddenElements = false)
|
||||
{
|
||||
return new Faker<GetFilesQuery>()
|
||||
.CustomInstantiator(f => new GetFilesQuery(
|
||||
default!,
|
||||
default
|
||||
))
|
||||
.RuleFor(x => x.Path, f => f.System.FilePath())
|
||||
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
|
||||
}
|
||||
}
|
||||
+8
-6
@@ -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;
|
||||
@@ -30,6 +30,7 @@ public class GetFilesQueryHandlerTests
|
||||
private readonly IFileService _mockFileService;
|
||||
private readonly GetFilesQueryHandler _sut;
|
||||
private readonly FileFixture _fileFixture;
|
||||
private readonly GetFilesQueryFixture _getFilesQueryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFilesQueryHandlerTests"/> class.
|
||||
@@ -43,13 +44,14 @@ public class GetFilesQueryHandlerTests
|
||||
.Returns([]);
|
||||
_sut = new GetFilesQueryHandler(_mockFileService, mockValidator);
|
||||
_fileFixture = new FileFixture();
|
||||
_getFilesQueryFixture = new GetFilesQueryFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetFilesQuery getFilesQuery = GetFilesQueryFixture.CreateGetFilesQuery(false);
|
||||
GetFilesQuery getFilesQuery = _getFilesQueryFixture.Create(includeHiddenElements: false);
|
||||
|
||||
IEnumerable<File> files = _fileFixture.CreateMany();
|
||||
|
||||
@@ -83,7 +85,7 @@ public class GetFilesQueryHandlerTests
|
||||
public async Task HandleAsync_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetFilesQuery getFilesQuery = GetFilesQueryFixture.CreateGetFilesQuery(true);
|
||||
GetFilesQuery getFilesQuery = _getFilesQueryFixture.Create(includeHiddenElements: true);
|
||||
|
||||
IEnumerable<File> files = _fileFixture.CreateMany();
|
||||
|
||||
@@ -117,7 +119,7 @@ public class GetFilesQueryHandlerTests
|
||||
public async Task HandleAsync_WhenFileServiceReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
GetFilesQuery query = _fixture.Create<GetFilesQuery>();
|
||||
GetFilesQuery query = _getFilesQueryFixture.Create();
|
||||
Error error = Error.Failure("FileService.Error", "An error occurred");
|
||||
_mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements)
|
||||
.Returns(error);
|
||||
@@ -135,7 +137,7 @@ public class GetFilesQueryHandlerTests
|
||||
public async Task HandleAsync_WhenFileServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetFilesQuery query = _fixture.Create<GetFilesQuery>();
|
||||
GetFilesQuery query = _getFilesQueryFixture.Create();
|
||||
Result<IEnumerable<File>> emptyList = Result.From(Enumerable.Empty<File>());
|
||||
_mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements)
|
||||
.Returns(emptyList);
|
||||
|
||||
+9
-7
@@ -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;
|
||||
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.G
|
||||
public class GetFilesQueryValidatorTests
|
||||
{
|
||||
private readonly GetFilesQueryValidator _validator;
|
||||
private readonly GetFilesQueryFixture _getFilesQueryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFilesQueryValidatorTests"/> class.
|
||||
@@ -24,13 +25,14 @@ public class GetFilesQueryValidatorTests
|
||||
public GetFilesQueryValidatorTests()
|
||||
{
|
||||
_validator = new GetFilesQueryValidator();
|
||||
_getFilesQueryFixture = new GetFilesQueryFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery();
|
||||
GetFilesQuery query = _getFilesQueryFixture.Create();
|
||||
query = query with { Path = null! };
|
||||
|
||||
// Act
|
||||
@@ -44,7 +46,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 +60,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 +74,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 +88,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 +102,7 @@ public class GetFilesQueryValidatorTests
|
||||
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery();
|
||||
GetFilesQuery query = _getFilesQueryFixture.Create();
|
||||
query = query with { IncludeHiddenElements = false };
|
||||
|
||||
// Act
|
||||
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetTreeFilesQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTreeFilesQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get files.
|
||||
/// </summary>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <returns>The created query to get files.</returns>
|
||||
public static GetTreeFilesQuery CreateGetFilesQuery(bool includeHiddenElements = false)
|
||||
{
|
||||
return new Faker<GetTreeFilesQuery>()
|
||||
.CustomInstantiator(f => new GetTreeFilesQuery(
|
||||
default!,
|
||||
default
|
||||
))
|
||||
.RuleFor(x => x.Path, f => f.System.FilePath())
|
||||
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
|
||||
}
|
||||
}
|
||||
+8
-6
@@ -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;
|
||||
@@ -30,6 +30,7 @@ public class GetTreeFilesQueryHandlerTests
|
||||
private readonly IFileService _mockFileService;
|
||||
private readonly GetTreeFilesQueryHandler _sut;
|
||||
private readonly FileFixture _fileFixture;
|
||||
private readonly GetTreeFilesQueryFixture _getTreeFilesQueryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTreeFilesQueryHandler"/> class.
|
||||
@@ -43,13 +44,14 @@ public class GetTreeFilesQueryHandlerTests
|
||||
.Returns([]);
|
||||
_sut = new GetTreeFilesQueryHandler(_mockFileService, mockValidator);
|
||||
_fileFixture = new FileFixture();
|
||||
_getTreeFilesQueryFixture = new GetTreeFilesQueryFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeFilesQuery getFilesQuery = GetTreeFilesQueryFixture.CreateGetFilesQuery(false);
|
||||
GetTreeFilesQuery getFilesQuery = _getTreeFilesQueryFixture.Create(includeHiddenElements: false);
|
||||
|
||||
IEnumerable<File> files = _fileFixture.CreateMany();
|
||||
|
||||
@@ -84,7 +86,7 @@ public class GetTreeFilesQueryHandlerTests
|
||||
public async Task HandleAsync_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeFilesQuery getFilesQuery = GetTreeFilesQueryFixture.CreateGetFilesQuery(true);
|
||||
GetTreeFilesQuery getFilesQuery = _getTreeFilesQueryFixture.Create(includeHiddenElements: true);
|
||||
|
||||
IEnumerable<File> files = _fileFixture.CreateMany();
|
||||
|
||||
@@ -119,7 +121,7 @@ public class GetTreeFilesQueryHandlerTests
|
||||
public async Task HandleAsync_WhenFileServiceReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeFilesQuery query = _fixture.Create<GetTreeFilesQuery>();
|
||||
GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create();
|
||||
Error error = Error.Failure("FileService.Error", "An error occurred");
|
||||
_mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements)
|
||||
.Returns(error);
|
||||
@@ -137,7 +139,7 @@ public class GetTreeFilesQueryHandlerTests
|
||||
public async Task HandleAsync_WhenFileServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeFilesQuery query = _fixture.Create<GetTreeFilesQuery>();
|
||||
GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create();
|
||||
Result<IEnumerable<File>> emptyList = Result.From(Enumerable.Empty<File>());
|
||||
_mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements)
|
||||
.Returns(emptyList);
|
||||
|
||||
+9
-7
@@ -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;
|
||||
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.G
|
||||
public class GetTreeFilesQueryValidatorTests
|
||||
{
|
||||
private readonly GetTreeFilesQueryValidator _validator;
|
||||
private readonly GetTreeFilesQueryFixture _getTreeFilesQueryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTreeFilesQueryValidatorTests"/> class.
|
||||
@@ -24,13 +25,14 @@ public class GetTreeFilesQueryValidatorTests
|
||||
public GetTreeFilesQueryValidatorTests()
|
||||
{
|
||||
_validator = new GetTreeFilesQueryValidator();
|
||||
_getTreeFilesQueryFixture = new GetTreeFilesQueryFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery();
|
||||
GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create();
|
||||
query = query with { Path = null! };
|
||||
|
||||
// Act
|
||||
@@ -44,7 +46,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 +60,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 +74,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 +88,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 +102,7 @@ public class GetTreeFilesQueryValidatorTests
|
||||
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery();
|
||||
GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create();
|
||||
query = query with { IncludeHiddenElements = false };
|
||||
|
||||
// Act
|
||||
|
||||
-42
@@ -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.Application.UnitTests.Core.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FileSystemPathId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileSystemPathIdFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemPathIdFixture"/> class.
|
||||
/// </summary>
|
||||
public FileSystemPathIdFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="FileSystemPathId"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file system path element.</param>
|
||||
/// <returns>The created <see cref="FileSystemPathId"/>.</returns>
|
||||
public FileSystemPathId CreateFileSystemPathId(string? path = null)
|
||||
{
|
||||
path ??= _faker.System.FilePath();
|
||||
|
||||
Result<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
|
||||
|
||||
if (fileSystemPathIdResult.IsFailure)
|
||||
throw new InvalidOperationException("Failed to create FileSystemPathId: " + string.Join(", ", fileSystemPathIdResult.Errors));
|
||||
return fileSystemPathIdResult.Value;
|
||||
}
|
||||
}
|
||||
-29
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="CombinePathCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CombinePathCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command to combine paths.
|
||||
/// </summary>
|
||||
/// <returns>The created command.</returns>
|
||||
public static CombinePathCommand CreateCombinePathCommand()
|
||||
{
|
||||
return new Faker<CombinePathCommand>()
|
||||
.CustomInstantiator(f => new CombinePathCommand(
|
||||
default!,
|
||||
default!
|
||||
))
|
||||
.RuleFor(x => x.OriginalPath, f => f.System.FilePath())
|
||||
.RuleFor(x => x.NewPath, f => f.System.FilePath());
|
||||
}
|
||||
}
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="SplitPathCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SplitPathCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command for splitting paths.
|
||||
/// </summary>
|
||||
/// <returns>The created command.</returns>
|
||||
public static SplitPathCommand CreateSplitPathCommand()
|
||||
{
|
||||
return new Faker<SplitPathCommand>()
|
||||
.CustomInstantiator(f => new SplitPathCommand(
|
||||
default!
|
||||
))
|
||||
.RuleFor(x => x.Path, f => f.System.FilePath());
|
||||
}
|
||||
}
|
||||
-58
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PathSegment"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PathSegmentFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PathSegmentFixture"/> class.
|
||||
/// </summary>
|
||||
public PathSegmentFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="PathSegment"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="PathSegment"/>.</returns>
|
||||
public PathSegment CreatePathSegment(
|
||||
string? name = null,
|
||||
bool? isDirectory = null,
|
||||
bool? isDrive = null)
|
||||
{
|
||||
name ??= _faker.System.FileName();
|
||||
isDirectory ??= true;
|
||||
isDrive ??= false;
|
||||
|
||||
Result<PathSegment> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="PathSegment"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<PathSegment> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count).Select(_ => CreatePathSegment()).ToList();
|
||||
}
|
||||
}
|
||||
-37
@@ -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.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PathSegmentResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PathSegmentResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="PathSegmentResponse"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="PathSegmentResponse"/>.</returns>
|
||||
public PathSegmentResponse Create()
|
||||
{
|
||||
return new PathSegmentResponse(_faker.System.DirectoryPath());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="PathSegmentResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<PathSegmentResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
|
||||
}
|
||||
}
|
||||
-37
@@ -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.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PathSeparatorResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PathSeparatorResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="PathSeparatorResponse"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="PathSeparatorResponse"/>.</returns>
|
||||
public PathSeparatorResponse Create()
|
||||
{
|
||||
return new PathSeparatorResponse(_faker.System.DirectoryPath());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="PathSeparatorResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<PathSeparatorResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
|
||||
}
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="CheckPathExistsQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CheckPathExistsQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to check if paths exist.
|
||||
/// </summary>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
|
||||
/// <returns>The created query.</returns>
|
||||
public static CheckPathExistsQuery CreateCheckPathExistsQuery(bool includeHiddenElements = true)
|
||||
{
|
||||
return new Faker<CheckPathExistsQuery>()
|
||||
.CustomInstantiator(f => new CheckPathExistsQuery(
|
||||
default!,
|
||||
default
|
||||
))
|
||||
.RuleFor(x => x.Path, f => f.System.FilePath())
|
||||
.RuleFor(x => x.IncludeHiddenElements, includeHiddenElements);
|
||||
}
|
||||
}
|
||||
-27
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetPathParentQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathParentQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to check if paths exist.
|
||||
/// </summary>
|
||||
/// <returns>The created query.</returns>
|
||||
public static GetPathParentQuery CreateGetPathParentQuery()
|
||||
{
|
||||
return new Faker<GetPathParentQuery>()
|
||||
.CustomInstantiator(f => new GetPathParentQuery(
|
||||
default!
|
||||
))
|
||||
.RuleFor(x => x.Path, f => f.System.FilePath());
|
||||
}
|
||||
}
|
||||
-27
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetPathRootQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathRootQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to check if paths exist.
|
||||
/// </summary>
|
||||
/// <returns>The created query.</returns>
|
||||
public static GetPathRootQuery CreateGetPathRootQuery()
|
||||
{
|
||||
return new Faker<GetPathRootQuery>()
|
||||
.CustomInstantiator(f => new GetPathRootQuery(
|
||||
default!
|
||||
))
|
||||
.RuleFor(x => x.Path, f => f.System.FilePath());
|
||||
}
|
||||
}
|
||||
-27
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ValidatePathQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ValidatePathQueryFixure
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to check if paths exist.
|
||||
/// </summary>
|
||||
/// <returns>The created query.</returns>
|
||||
public static ValidatePathQuery CreateValidatePathQuery()
|
||||
{
|
||||
return new Faker<ValidatePathQuery>()
|
||||
.CustomInstantiator(f => new ValidatePathQuery(
|
||||
default!
|
||||
))
|
||||
.RuleFor(x => x.Path, f => f.System.FilePath());
|
||||
}
|
||||
}
|
||||
+7
-5
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CombinePathCommandHandler"/> class.
|
||||
@@ -24,6 +24,7 @@ public class CombinePathCommandHandlerTests
|
||||
private readonly IFixture _fixture;
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly CombinePathCommandHandler _sut;
|
||||
private readonly CombinePathCommandFixture _combinePathCommandFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CombinePathCommandHandlerTests"/> class.
|
||||
@@ -36,13 +37,14 @@ public class CombinePathCommandHandlerTests
|
||||
mockValidator.Validate(Arg.Any<CombinePathCommand>())
|
||||
.Returns([]);
|
||||
_sut = new CombinePathCommandHandler(_mockPathService, mockValidator);
|
||||
_combinePathCommandFixture = new CombinePathCommandFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
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 +64,7 @@ public class CombinePathCommandHandlerTests
|
||||
public async Task HandleAsync_WhenPathServiceReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
CombinePathCommand command = _fixture.Create<CombinePathCommand>();
|
||||
CombinePathCommand command = _combinePathCommandFixture.Create();
|
||||
Error error = Error.Failure("PathService.Error", "An error occurred");
|
||||
_mockPathService.CombinePath(command.OriginalPath!, command.NewPath!)
|
||||
.Returns(error);
|
||||
@@ -80,7 +82,7 @@ public class CombinePathCommandHandlerTests
|
||||
public async Task HandleAsync_WhenPathServiceReturnsEmptyString_ShouldReturnSuccessResultWithEmptyPath()
|
||||
{
|
||||
// Arrange
|
||||
CombinePathCommand command = _fixture.Create<CombinePathCommand>();
|
||||
CombinePathCommand command = _combinePathCommandFixture.Create();
|
||||
_mockPathService.CombinePath(command.OriginalPath!, command.NewPath!)
|
||||
.Returns(Result.From(string.Empty));
|
||||
|
||||
+11
-9
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CombinePathCommandValidator"/> class.
|
||||
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.C
|
||||
public class CombinePathCommandValidatorTests
|
||||
{
|
||||
private readonly CombinePathCommandValidator _validator;
|
||||
private readonly CombinePathCommandFixture _combinePathCommandFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CombinePathCommandValidatorTests"/> class.
|
||||
@@ -24,13 +25,14 @@ public class CombinePathCommandValidatorTests
|
||||
public CombinePathCommandValidatorTests()
|
||||
{
|
||||
_validator = new CombinePathCommandValidator();
|
||||
_combinePathCommandFixture = new CombinePathCommandFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenOriginalPathIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand();
|
||||
CombinePathCommand command = _combinePathCommandFixture.Create();
|
||||
command = command with { OriginalPath = null! };
|
||||
|
||||
// Act
|
||||
@@ -44,7 +46,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 +60,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 +74,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 +88,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 +102,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 +116,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
|
||||
+8
-6
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SplitPathCommandHandler"/> class.
|
||||
@@ -30,6 +30,7 @@ public class SplitPathCommandHandlerTests
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly SplitPathCommandHandler _sut;
|
||||
private readonly PathSegmentFixture _pathSegmentFixture;
|
||||
private readonly SplitPathCommandFixture _splitPathCommandFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SplitPathCommandHandlerTests"/> class.
|
||||
@@ -43,13 +44,14 @@ public class SplitPathCommandHandlerTests
|
||||
.Returns([]);
|
||||
_sut = new SplitPathCommandHandler(_mockPathService, mockValidator);
|
||||
_pathSegmentFixture = new PathSegmentFixture();
|
||||
_splitPathCommandFixture = new SplitPathCommandFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalledWithValidCommand_ShouldReturnSuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
SplitPathCommand splitPathCommand = SplitPathCommandFixture.CreateSplitPathCommand();
|
||||
SplitPathCommand splitPathCommand = _splitPathCommandFixture.Create();
|
||||
|
||||
IEnumerable<PathSegment> pathSegments = _pathSegmentFixture.CreateMany();
|
||||
|
||||
@@ -76,7 +78,7 @@ public class SplitPathCommandHandlerTests
|
||||
public async Task HandleAsync_WhenPathServiceReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
SplitPathCommand command = _fixture.Create<SplitPathCommand>();
|
||||
SplitPathCommand command = _splitPathCommandFixture.Create();
|
||||
Error error = Error.Failure("PathService.Error", "An error occurred");
|
||||
_mockPathService.ParsePath(command.Path!)
|
||||
.Returns(error);
|
||||
@@ -94,7 +96,7 @@ public class SplitPathCommandHandlerTests
|
||||
public async Task HandleAsync_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
SplitPathCommand command = _fixture.Create<SplitPathCommand>();
|
||||
SplitPathCommand command = _splitPathCommandFixture.Create();
|
||||
Result<IEnumerable<PathSegment>> emptyList = Result.From(Enumerable.Empty<PathSegment>());
|
||||
_mockPathService.ParsePath(command.Path!)
|
||||
.Returns(emptyList);
|
||||
+8
-6
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SplitPathCommandValidator"/> class.
|
||||
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.S
|
||||
public class SplitPathCommandValidatorTests
|
||||
{
|
||||
private readonly SplitPathCommandValidator _validator;
|
||||
private readonly SplitPathCommandFixture _splitPathCommandFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SplitPathCommandValidatorTests"/> class.
|
||||
@@ -24,13 +25,14 @@ public class SplitPathCommandValidatorTests
|
||||
public SplitPathCommandValidatorTests()
|
||||
{
|
||||
_validator = new SplitPathCommandValidator();
|
||||
_splitPathCommandFixture = new SplitPathCommandFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand();
|
||||
SplitPathCommand command = _splitPathCommandFixture.Create();
|
||||
command = command with { Path = null! };
|
||||
|
||||
// Act
|
||||
@@ -44,7 +46,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 +60,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 +74,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
|
||||
+9
-7
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CheckPathExistsQueryHandler"/> class.
|
||||
@@ -21,6 +21,7 @@ public class CheckPathExistsQueryHandlerTests
|
||||
{
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly CheckPathExistsQueryHandler _sut;
|
||||
private readonly CheckPathExistsQueryFixture _checkPathExistsQueryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CheckPathExistsQueryHandlerTests"/> class.
|
||||
@@ -28,6 +29,7 @@ public class CheckPathExistsQueryHandlerTests
|
||||
public CheckPathExistsQueryHandlerTests()
|
||||
{
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_checkPathExistsQueryFixture = new CheckPathExistsQueryFixture();
|
||||
IValidator<CheckPathExistsQuery> mockValidator = Substitute.For<IValidator<CheckPathExistsQuery>>();
|
||||
mockValidator.Validate(Arg.Any<CheckPathExistsQuery>())
|
||||
.Returns([]);
|
||||
@@ -38,7 +40,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 +56,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 +72,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 +88,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 +120,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);
|
||||
|
||||
+8
-6
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CheckPathExistsQueryValidator"/> class.
|
||||
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.Ch
|
||||
public class CheckPathExistsQueryValidatorTests
|
||||
{
|
||||
private readonly CheckPathExistsQueryValidator _validator;
|
||||
private readonly CheckPathExistsQueryFixture _checkPathExistsQueryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CheckPathExistsQueryValidatorTests"/> class.
|
||||
@@ -24,13 +25,14 @@ public class CheckPathExistsQueryValidatorTests
|
||||
public CheckPathExistsQueryValidatorTests()
|
||||
{
|
||||
_validator = new CheckPathExistsQueryValidator();
|
||||
_checkPathExistsQueryFixture = new CheckPathExistsQueryFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery();
|
||||
CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create();
|
||||
query = query with { Path = null! };
|
||||
|
||||
// Act
|
||||
@@ -44,7 +46,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 +60,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 +74,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
|
||||
+8
-6
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPathParentQueryHandler"/> class.
|
||||
@@ -29,6 +29,7 @@ public class GetPathParentQueryHandlerTests
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly GetPathParentQueryHandler _sut;
|
||||
private readonly PathSegmentFixture _pathSegmentFixture;
|
||||
private readonly GetPathParentQueryFixture _getPathParentQueryFixture;
|
||||
|
||||
public GetPathParentQueryHandlerTests()
|
||||
{
|
||||
@@ -39,13 +40,14 @@ public class GetPathParentQueryHandlerTests
|
||||
.Returns([]);
|
||||
_sut = new GetPathParentQueryHandler(_mockPathService, mockValidator);
|
||||
_pathSegmentFixture = new PathSegmentFixture();
|
||||
_getPathParentQueryFixture = new GetPathParentQueryFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalledWithValidQuery_ShouldReturnSuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery();
|
||||
GetPathParentQuery query = _getPathParentQueryFixture.Create();
|
||||
|
||||
IEnumerable<PathSegment> pathSegments = _pathSegmentFixture.CreateMany();
|
||||
|
||||
@@ -69,7 +71,7 @@ public class GetPathParentQueryHandlerTests
|
||||
public async Task HandleAsync_WhenPathServiceReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
GetPathParentQuery query = _fixture.Create<GetPathParentQuery>();
|
||||
GetPathParentQuery query = _getPathParentQueryFixture.Create();
|
||||
Error error = Error.Failure("PathService.Error", "An error occurred");
|
||||
_mockPathService.GoUpOneLevel(query.Path!)
|
||||
.Returns(error);
|
||||
@@ -87,7 +89,7 @@ public class GetPathParentQueryHandlerTests
|
||||
public async Task HandleAsync_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetPathParentQuery query = _fixture.Create<GetPathParentQuery>();
|
||||
GetPathParentQuery query = _getPathParentQueryFixture.Create();
|
||||
Result<IEnumerable<PathSegment>> emptyList = Result.From(Enumerable.Empty<PathSegment>());
|
||||
_mockPathService.GoUpOneLevel(query.Path!)
|
||||
.Returns(emptyList);
|
||||
+8
-6
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPathParentQueryValidator"/> class.
|
||||
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.Ge
|
||||
public class GetPathParentQueryValidatorTests
|
||||
{
|
||||
private readonly GetPathParentQueryValidator _validator;
|
||||
private readonly GetPathParentQueryFixture _getPathParentQueryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPathParentQueryValidatorTests"/> class.
|
||||
@@ -24,13 +25,14 @@ public class GetPathParentQueryValidatorTests
|
||||
public GetPathParentQueryValidatorTests()
|
||||
{
|
||||
_validator = new GetPathParentQueryValidator();
|
||||
_getPathParentQueryFixture = new GetPathParentQueryFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery();
|
||||
GetPathParentQuery query = _getPathParentQueryFixture.Create();
|
||||
query = query with { Path = null! };
|
||||
|
||||
// Act
|
||||
@@ -44,7 +46,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 +60,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 +74,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
|
||||
+10
-8
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPathRootQueryHandler"/> class.
|
||||
@@ -24,6 +24,7 @@ public class GetPathRootQueryHandlerTests
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly GetPathRootQueryHandler _sut;
|
||||
private readonly PathSegmentFixture _pathSegmentFixture;
|
||||
private readonly GetPathRootQueryFixture _getPathRootQueryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPathRootQueryHandlerTests"/> class.
|
||||
@@ -31,6 +32,7 @@ public class GetPathRootQueryHandlerTests
|
||||
public GetPathRootQueryHandlerTests()
|
||||
{
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_getPathRootQueryFixture = new GetPathRootQueryFixture();
|
||||
IValidator<GetPathRootQuery> mockValidator = Substitute.For<IValidator<GetPathRootQuery>>();
|
||||
mockValidator.Validate(Arg.Any<GetPathRootQuery>())
|
||||
.Returns([]);
|
||||
@@ -42,8 +44,8 @@ public class GetPathRootQueryHandlerTests
|
||||
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 +64,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 +82,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));
|
||||
+8
-6
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPathRootQueryValidator"/> class.
|
||||
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.Ge
|
||||
public class GetPathRootQueryValidatorTests
|
||||
{
|
||||
private readonly GetPathRootQueryValidator _validator;
|
||||
private readonly GetPathRootQueryFixture _getPathRootQueryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPathRootQueryValidatorTests"/> class.
|
||||
@@ -24,13 +25,14 @@ public class GetPathRootQueryValidatorTests
|
||||
public GetPathRootQueryValidatorTests()
|
||||
{
|
||||
_validator = new GetPathRootQueryValidator();
|
||||
_getPathRootQueryFixture = new GetPathRootQueryFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery();
|
||||
GetPathRootQuery query = _getPathRootQueryFixture.Create();
|
||||
query = query with { Path = null! };
|
||||
|
||||
// Act
|
||||
@@ -44,7 +46,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 +60,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 +74,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
|
||||
+1
-1
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPathSeparatorQueryHandler"/> class.
|
||||
+7
-5
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ValidatePathQueryHandler"/> class.
|
||||
@@ -23,6 +23,7 @@ public class ValidatePathQueryHandlerTests
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly IValidator<ValidatePathQuery> _mockValidator;
|
||||
private readonly ValidatePathQueryHandler _sut;
|
||||
private readonly ValidatePathQueryFixture _validatePathQueryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ValidatePathQueryHandlerTests"/> class.
|
||||
@@ -31,6 +32,7 @@ public class ValidatePathQueryHandlerTests
|
||||
{
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_mockValidator = Substitute.For<IValidator<ValidatePathQuery>>();
|
||||
_validatePathQueryFixture = new ValidatePathQueryFixture();
|
||||
_mockValidator.Validate(Arg.Any<ValidatePathQuery>())
|
||||
.Returns([]);
|
||||
_sut = new ValidatePathQueryHandler(_mockPathService, _mockValidator);
|
||||
@@ -40,7 +42,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 +58,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 +106,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]);
|
||||
|
||||
+8
-6
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ValidatePathQueryValidator"/> class.
|
||||
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.Va
|
||||
public class ValidatePathQueryValidatorTests
|
||||
{
|
||||
private readonly ValidatePathQueryValidator _validator;
|
||||
private readonly ValidatePathQueryFixture _validatePathQueryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ValidatePathQueryValidatorTests"/> class.
|
||||
@@ -24,13 +25,14 @@ public class ValidatePathQueryValidatorTests
|
||||
public ValidatePathQueryValidatorTests()
|
||||
{
|
||||
_validator = new ValidatePathQueryValidator();
|
||||
_validatePathQueryFixture = new ValidatePathQueryFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery();
|
||||
ValidatePathQuery query = _validatePathQueryFixture.Create();
|
||||
query = query with { Path = null! };
|
||||
|
||||
// Act
|
||||
@@ -44,7 +46,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 +60,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 +74,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
|
||||
-30
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ThumbnailResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThumbnailResponseFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get a thumbnail.
|
||||
/// </summary>
|
||||
/// <returns>The created query.</returns>
|
||||
public static ThumbnailResponse CreateThumbnailResponse()
|
||||
{
|
||||
return new Faker<ThumbnailResponse>()
|
||||
.CustomInstantiator(f => new ThumbnailResponse(
|
||||
default,
|
||||
default!
|
||||
))
|
||||
.RuleFor(x => x.Type, f => f.PickRandom<ImageType>())
|
||||
.RuleFor(x => x.Bytes, f => f.Random.Bytes(20));
|
||||
}
|
||||
}
|
||||
-29
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetThumbnailQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetThumbnailQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get a thumbnail.
|
||||
/// </summary>
|
||||
/// <returns>The created query.</returns>
|
||||
public static GetThumbnailQuery CreateGetThumbnailQuery()
|
||||
{
|
||||
return new Faker<GetThumbnailQuery>()
|
||||
.CustomInstantiator(f => new GetThumbnailQuery(
|
||||
default!,
|
||||
default
|
||||
))
|
||||
.RuleFor(x => x.Path, f => f.System.FilePath())
|
||||
.RuleFor(x => x.Quality, f => f.Random.Int());
|
||||
}
|
||||
}
|
||||
+10
-4
@@ -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,11 +26,15 @@ public class GetThumbnailQueryHandlerTests
|
||||
private readonly IFixture _fixture;
|
||||
private readonly IThumbnailService _mockThumbnailService;
|
||||
private readonly GetThumbnailQueryHandler _sut;
|
||||
private readonly GetThumbnailQueryFixture _getThumbnailQueryFixture;
|
||||
private readonly ThumbnailFixture _thumbnailFixture;
|
||||
|
||||
public GetThumbnailQueryHandlerTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_mockThumbnailService = Substitute.For<IThumbnailService>();
|
||||
_getThumbnailQueryFixture = new GetThumbnailQueryFixture();
|
||||
_thumbnailFixture = new ThumbnailFixture();
|
||||
IValidator<GetThumbnailQuery> mockValidator = Substitute.For<IValidator<GetThumbnailQuery>>();
|
||||
mockValidator.Validate(Arg.Any<GetThumbnailQuery>())
|
||||
.Returns([]);
|
||||
@@ -39,8 +45,8 @@ public class GetThumbnailQueryHandlerTests
|
||||
public async Task HandleAsync_WhenCalledWithValidQuery_ShouldReturnSuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetThumbnailQuery query = _fixture.Create<GetThumbnailQuery>();
|
||||
Thumbnail thumbnail = _fixture.Create<Thumbnail>();
|
||||
GetThumbnailQuery query = _getThumbnailQueryFixture.Create();
|
||||
Thumbnail thumbnail = _thumbnailFixture.Create();
|
||||
|
||||
_mockThumbnailService.GetThumbnailAsync(query.Path!, query.Quality, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(thumbnail));
|
||||
@@ -60,7 +66,7 @@ public class GetThumbnailQueryHandlerTests
|
||||
public async Task HandleAsync_WhenThumbnailServiceReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
GetThumbnailQuery query = _fixture.Create<GetThumbnailQuery>();
|
||||
GetThumbnailQuery query = _getThumbnailQueryFixture.Create();
|
||||
Error error = Error.Failure("ThumbnailService.Error", "An error occurred");
|
||||
_mockThumbnailService.GetThumbnailAsync(query.Path!, query.Quality, Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
@@ -78,7 +84,7 @@ public class GetThumbnailQueryHandlerTests
|
||||
public async Task HandleAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetThumbnailQuery query = _fixture.Create<GetThumbnailQuery>();
|
||||
GetThumbnailQuery query = _getThumbnailQueryFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
cts.Cancel();
|
||||
|
||||
|
||||
-35
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="SetupApplicationCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetupApplicationCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command for the application setup.
|
||||
/// </summary>
|
||||
/// <returns>The created command.</returns>
|
||||
public SetupApplicationCommand CreateSetupApplicationCommand()
|
||||
{
|
||||
string password = "Abcd123$";
|
||||
return new Faker<SetupApplicationCommand>()
|
||||
.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();
|
||||
}
|
||||
}
|
||||
+14
-13
@@ -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,6 +38,7 @@ public class SetupApplicationCommandHandlerTests
|
||||
private readonly IDateTimeProvider _mockDateTimeProvider;
|
||||
private readonly IDataSeedService _mockDataSeedService;
|
||||
private readonly SetupApplicationCommandHandler _sut;
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture;
|
||||
|
||||
/// <summary>
|
||||
@@ -76,7 +77,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<CancellationToken>())
|
||||
@@ -112,7 +113,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 +158,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<CancellationToken>())
|
||||
.Returns(new[] { existingUser });
|
||||
@@ -179,7 +180,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<CancellationToken>())
|
||||
@@ -201,7 +202,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<CancellationToken>())
|
||||
@@ -225,7 +226,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<CancellationToken>())
|
||||
@@ -250,7 +251,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<CancellationToken>())
|
||||
@@ -278,7 +279,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<CancellationToken>())
|
||||
@@ -309,7 +310,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<CancellationToken>())
|
||||
@@ -342,7 +343,7 @@ public class SetupApplicationCommandHandlerTests
|
||||
public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccessResponse()
|
||||
{
|
||||
// Arrange
|
||||
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand();
|
||||
SetupApplicationCommand command = _setupApplicationCommandFixture.Create();
|
||||
|
||||
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Enumerable.Empty<UserEntity>()));
|
||||
|
||||
+14
-14
@@ -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;
|
||||
@@ -32,7 +32,7 @@ public class SetupApplicationCommandValidatorTests
|
||||
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand();
|
||||
SetupApplicationCommand command = _commandFixture.Create();
|
||||
command = command with { Username = null };
|
||||
|
||||
// Act
|
||||
@@ -46,7 +46,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 +60,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 +74,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 +88,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 +102,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 +116,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 +130,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 +144,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 +158,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 +178,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 +196,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 +210,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
|
||||
|
||||
+3
-2
@@ -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;
|
||||
@@ -25,6 +25,7 @@ public class CheckInitializationQueryHandlerTests
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IUserRepository _mockUserRepository;
|
||||
private readonly CheckInitializationQueryHandler _sut;
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CheckInitializationQueryHandlerTests"/> class.
|
||||
@@ -43,7 +44,7 @@ public class CheckInitializationQueryHandlerTests
|
||||
public async Task HandleAsync_WhenUsersExist_ShouldReturnInitialized()
|
||||
{
|
||||
// Arrange
|
||||
List<UserEntity> users = UserEntityFixture.CreateMany();
|
||||
List<UserEntity> users = _userEntityFixture.CreateMany();
|
||||
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(users.AsEnumerable()));
|
||||
|
||||
|
||||
-110
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="Library"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DomainLibraryFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
private readonly Random _random = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DomainLibraryFixture"/> class.
|
||||
/// </summary>
|
||||
public DomainLibraryFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a media library domain entity.
|
||||
/// </summary>
|
||||
/// <returns>The created media library entity.</returns>
|
||||
public Library CreateLibrary()
|
||||
{
|
||||
List<string> validPaths =
|
||||
[
|
||||
"C:/Media",
|
||||
"D:/Books",
|
||||
"E:/Digital Library",
|
||||
"F:/Content"
|
||||
];
|
||||
|
||||
Result<Library> library = Library.Create(
|
||||
UserId.CreateUnique(),
|
||||
_faker.Random.String2(_faker.Random.Number(1, 50)),
|
||||
_faker.PickRandom<LibraryType>(),
|
||||
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<string>? contentLocations = null,
|
||||
string? coverImage = null,
|
||||
bool isEnabled = true,
|
||||
bool isLocked = false,
|
||||
bool downloadMetadataFromWeb = true,
|
||||
bool shouldSaveMetadataInMediaDirectories = false,
|
||||
bool shouldSkipUnchangedDirectoriesDuringScan = false,
|
||||
IEnumerable<Guid>? scanIds = null)
|
||||
{
|
||||
Result<Library> 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;
|
||||
}
|
||||
}
|
||||
+11
-11
@@ -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;
|
||||
@@ -60,7 +60,7 @@ public class AddBookCommandHandlerTests
|
||||
public async Task HandleAsync_WhenCalledWithValidCommand_ShouldReturnSuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create();
|
||||
|
||||
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
@@ -79,7 +79,7 @@ public class AddBookCommandHandlerTests
|
||||
public async Task HandleAsync_WhenRepositoryInsertFails_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create();
|
||||
|
||||
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.WrittenContent.BookAlreadyExists);
|
||||
@@ -98,7 +98,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 +115,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 +132,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 +155,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 +178,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 +208,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 +231,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
|
||||
|
||||
+132
-132
File diff suppressed because it is too large.
Load diff
-345
@@ -1,345 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
using Lumina.Application.UnitTests.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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AddBookCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddBookCommandFixture
|
||||
{
|
||||
private readonly Fixture _fixture;
|
||||
private readonly Random _random = new();
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddBookCommandFixture"/> class.
|
||||
/// </summary>
|
||||
public AddBookCommandFixture()
|
||||
{
|
||||
_fixture = new Fixture();
|
||||
_fixture.Customizations.Add(new DateOnlySpecimenBuilder());
|
||||
_fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder());
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid command to add a book.
|
||||
/// </summary>
|
||||
/// <returns>The created command to add a book.</returns>
|
||||
public AddBookCommand CreateCommandBook()
|
||||
{
|
||||
int releaseYear = _random.Next(2000, 2010);
|
||||
int reReleaseYear = _random.Next(2010, 2020);
|
||||
|
||||
ReleaseInfoDto releaseInfo = new Faker<ReleaseInfoDto>()
|
||||
.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<GenreDto> genre = new Faker<GenreDto>()
|
||||
.CustomInstantiator(f => new GenreDto(
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
|
||||
|
||||
Faker<TagDto> tag = new Faker<TagDto>()
|
||||
.CustomInstantiator(f => new TagDto(
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
|
||||
|
||||
Faker<MediaContributorRoleDto> mediaContributorRole = new Faker<MediaContributorRoleDto>()
|
||||
.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<MediaContributorNameDto> mediaContributorName = new Faker<MediaContributorNameDto>()
|
||||
.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<MediaContributorDto> mediaContributor = new Faker<MediaContributorDto>()
|
||||
.CustomInstantiator(f => new MediaContributorDto(
|
||||
default!,
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, mediaContributorName)
|
||||
.RuleFor(e => e.Role, mediaContributorRole);
|
||||
|
||||
Faker<BookRatingDto> rating = new Faker<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<BookRatingSource>())
|
||||
.RuleFor(e => e.VoteCount, _random.Next(1, 1000));
|
||||
|
||||
Faker<LanguageInfoDto> language = new Faker<LanguageInfoDto>()
|
||||
.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<LanguageInfoDto> originalLanguage = new Faker<LanguageInfoDto>()
|
||||
.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<WrittenContentMetadataDto> metadata = new Faker<WrittenContentMetadataDto>()
|
||||
.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<IsbnDto> isbn = new Faker<IsbnDto>()
|
||||
.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<AddBookCommand>()
|
||||
.CustomInstantiator(f => new AddBookCommand(
|
||||
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<Guid>())
|
||||
.RuleFor(x => x.Path, f => f.System.FilePath())
|
||||
.RuleFor(x => x.Metadata, metadata)
|
||||
.RuleFor(x => x.Format, _fixture.Create<BookFormat>())
|
||||
.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)));
|
||||
}
|
||||
|
||||
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<string>()[2..],
|
||||
_fixture.Create<string?>()));
|
||||
|
||||
_fixture.Register(() => new GenreDto(
|
||||
_fixture.Create<string>()
|
||||
));
|
||||
_fixture.Register(() => new TagDto(
|
||||
_fixture.Create<string>()
|
||||
));
|
||||
_fixture.Register(() => new LanguageInfoDto(
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<string?>()
|
||||
));
|
||||
_fixture.Register(() => new IsbnDto(
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<IsbnFormat>()
|
||||
));
|
||||
_fixture.Register(() => new BookRatingDto(
|
||||
_fixture.Create<decimal>(),
|
||||
_fixture.Create<decimal>(),
|
||||
_fixture.Create<BookRatingSource?>(),
|
||||
_fixture.Create<int?>()
|
||||
));
|
||||
_fixture.Register(() => new WrittenContentMetadataDto(
|
||||
_fixture.Create<string>()[255..],
|
||||
LimitStringLength(_fixture.Create<string?>(), 255),
|
||||
LimitStringLength(_fixture.Create<string?>(), 2000),
|
||||
_fixture.Create<ReleaseInfoDto>(),
|
||||
_fixture.Create<List<GenreDto>>(),
|
||||
_fixture.Create<List<TagDto>>(),
|
||||
_fixture.Create<LanguageInfoDto?>(),
|
||||
_fixture.Create<LanguageInfoDto?>(),
|
||||
_fixture.Create<string?>(),
|
||||
_fixture.Create<int?>()
|
||||
));
|
||||
_fixture.Register(() => new BookSeriesDto(
|
||||
_fixture.Create<string>()
|
||||
));
|
||||
_fixture.Register(() => new MediaContributorRoleDto(
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<string>()
|
||||
));
|
||||
_fixture.Register(() => new MediaContributorNameDto(
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<string?>()
|
||||
));
|
||||
_fixture.Register(() => new MediaContributorDto(
|
||||
_fixture.Create<MediaContributorNameDto>(),
|
||||
_fixture.Create<MediaContributorRoleDto>()
|
||||
));
|
||||
}
|
||||
|
||||
private static string? LimitStringLength(string? input, int maxLength)
|
||||
{
|
||||
return input?.Length > maxLength ? input[..maxLength] : input;
|
||||
}
|
||||
}
|
||||
-278
@@ -1,278 +0,0 @@
|
||||
#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;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AddBookRequest"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddBookRequestFixture
|
||||
{
|
||||
private readonly Fixture _fixture;
|
||||
private readonly Random _random = new();
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddBookRequestFixture"/> class.
|
||||
/// </summary>
|
||||
public AddBookRequestFixture()
|
||||
{
|
||||
_fixture = new Fixture();
|
||||
_fixture.Customizations.Add(new DateOnlySpecimenBuilder());
|
||||
_fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder());
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid request to add a book.
|
||||
/// </summary>
|
||||
/// <returns>The created request to add a book.</returns>
|
||||
public AddBookRequest CreateRequestBook()
|
||||
{
|
||||
int releaseYear = _random.Next(2000, 2010);
|
||||
int reReleaseYear = _random.Next(2010, 2020);
|
||||
|
||||
ReleaseInfoDto releaseInfo = new Faker<ReleaseInfoDto>()
|
||||
.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<GenreDto> genre = new Faker<GenreDto>()
|
||||
.CustomInstantiator(f => new GenreDto(
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
|
||||
|
||||
Faker<TagDto> tag = new Faker<TagDto>()
|
||||
.CustomInstantiator(f => new TagDto(
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
|
||||
|
||||
Faker<MediaContributorRoleDto> mediaContributorRole = new Faker<MediaContributorRoleDto>()
|
||||
.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<MediaContributorNameDto> mediaContributorName = new Faker<MediaContributorNameDto>()
|
||||
.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<MediaContributorDto> mediaContributor = new Faker<MediaContributorDto>()
|
||||
.CustomInstantiator(f => new MediaContributorDto(
|
||||
default!,
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, mediaContributorName)
|
||||
.RuleFor(e => e.Role, mediaContributorRole);
|
||||
|
||||
Faker<BookRatingDto> rating = new Faker<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<BookRatingSource>())
|
||||
.RuleFor(e => e.VoteCount, _random.Next(1, 1000));
|
||||
|
||||
Faker<LanguageInfoDto> language = new Faker<LanguageInfoDto>()
|
||||
.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<LanguageInfoDto> originalLanguage = new Faker<LanguageInfoDto>()
|
||||
.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<WrittenContentMetadataDto> metadata = new Faker<WrittenContentMetadataDto>()
|
||||
.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<IsbnDto> isbn = new Faker<IsbnDto>()
|
||||
.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<AddBookRequest>()
|
||||
.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<Guid>())
|
||||
.RuleFor(x => x.Path, f => f.System.FilePath())
|
||||
.RuleFor(x => x.Metadata, metadata)
|
||||
.RuleFor(x => x.Format, _fixture.Create<BookFormat>())
|
||||
.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)));
|
||||
}
|
||||
}
|
||||
-149
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="BookEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookEntityFixture
|
||||
{
|
||||
private readonly Fixture _fixture;
|
||||
private readonly Random _random = new();
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookEntityFixture"/> class.
|
||||
/// </summary>
|
||||
public BookEntityFixture()
|
||||
{
|
||||
_fixture = new Fixture();
|
||||
_fixture.Customizations.Add(new DateOnlySpecimenBuilder());
|
||||
_fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder());
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid book entity.
|
||||
/// </summary>
|
||||
/// <returns>The created book entity.</returns>
|
||||
public BookEntity CreateBook()
|
||||
{
|
||||
int releaseYear = _random.Next(2000, 2010);
|
||||
int reReleaseYear = _random.Next(2010, 2020);
|
||||
|
||||
Faker<GenreEntity> genre = new Faker<GenreEntity>()
|
||||
.CustomInstantiator(f => new GenreEntity(
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
|
||||
|
||||
Faker<TagEntity> tag = new Faker<TagEntity>()
|
||||
.CustomInstantiator(f => new TagEntity(
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
|
||||
|
||||
Faker<BookRatingEntity> rating = new Faker<BookRatingEntity>()
|
||||
.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<BookRatingSource>())
|
||||
.RuleFor(e => e.VoteCount, _random.Next(1, 1000));
|
||||
|
||||
Faker<IsbnEntity> isbn = new Faker<IsbnEntity>()
|
||||
.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<TagEntity>(tag.Generate(_faker.Random.Number(1, 5))),
|
||||
Genres = new HashSet<GenreEntity>(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<BookFormat>(),
|
||||
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()
|
||||
};
|
||||
}
|
||||
}
|
||||
-118
@@ -1,118 +0,0 @@
|
||||
#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;
|
||||
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.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="Book"/> domain entity.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookFixture
|
||||
{
|
||||
private readonly Fixture _fixture;
|
||||
private readonly IsbnFixture _isbnFixture;
|
||||
private readonly BookRatingFixture _bookRatingFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookFixture"/> class.
|
||||
/// </summary>
|
||||
public BookFixture()
|
||||
{
|
||||
_fixture = new Fixture();
|
||||
_fixture.Customizations.Add(new DateOnlySpecimenBuilder());
|
||||
_fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder());
|
||||
_isbnFixture = new IsbnFixture();
|
||||
_bookRatingFixture = new BookRatingFixture();
|
||||
ConfigureCustomDomainTypes();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid book domain entity.
|
||||
/// </summary>
|
||||
/// <returns>The created book domain entity.</returns>
|
||||
public Book CreateDomainBook()
|
||||
{
|
||||
return Book.Create(
|
||||
LibraryId.Create(_fixture.Create<Guid>()),
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<WrittenContentMetadata>(),
|
||||
_fixture.Create<BookFormat>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<Optional<int>>(),
|
||||
_fixture.Create<Optional<BookSeries>>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<List<Isbn>>(),
|
||||
_fixture.Create<List<MediaContributorId>>(),
|
||||
_fixture.Create<List<BookRating>>()
|
||||
).Value;
|
||||
}
|
||||
|
||||
private void ConfigureCustomDomainTypes()
|
||||
{
|
||||
_fixture.Register(() => Optional<string>.Some(_fixture.Create<string>()));
|
||||
_fixture.Register(() => Optional<int>.Some(_fixture.Create<int>()));
|
||||
|
||||
_fixture.Register(() =>
|
||||
{
|
||||
int originalYear = _fixture.Create<Generator<int>>().First(y => y >= 1900 && y <= 2025);
|
||||
int reReleaseYear = _fixture.Create<Generator<int>>().First(y => y >= originalYear && y <= 2025);
|
||||
|
||||
return ReleaseInfo.Create(
|
||||
Optional<DateOnly>.Some(DateOnly.FromDateTime(new DateTime(originalYear, 1, 1))),
|
||||
Optional<int>.Some(originalYear),
|
||||
Optional<DateOnly>.Some(DateOnly.FromDateTime(new DateTime(reReleaseYear, 1, 1))),
|
||||
Optional<int>.Some(reReleaseYear),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<Optional<string>>()
|
||||
).Value;
|
||||
});
|
||||
|
||||
_fixture.Register(() => Genre.Create(
|
||||
_fixture.Create<string>()
|
||||
).Value);
|
||||
|
||||
_fixture.Register(() => Tag.Create(
|
||||
_fixture.Create<string>()
|
||||
).Value);
|
||||
|
||||
_fixture.Register(() => WrittenContentMetadata.Create(
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<ReleaseInfo>(),
|
||||
_fixture.Create<List<Genre>>(),
|
||||
_fixture.Create<List<Tag>>(),
|
||||
_fixture.Create<Optional<LanguageInfo>>(),
|
||||
_fixture.Create<Optional<LanguageInfo>>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<Optional<int>>()
|
||||
).Value);
|
||||
|
||||
_fixture.Register(() => _isbnFixture.CreateIsbn13());
|
||||
|
||||
_fixture.Register(() => _bookRatingFixture.CreateBookRating());
|
||||
}
|
||||
}
|
||||
-69
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="BookRatingDto"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookRatingDtoFixture
|
||||
{
|
||||
private readonly Fixture _fixture;
|
||||
private readonly Random _random = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookRatingDtoFixture"/> class.
|
||||
/// </summary>
|
||||
public BookRatingDtoFixture()
|
||||
{
|
||||
_fixture = new Fixture();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a complete book rating DTO with all properties.
|
||||
/// </summary>
|
||||
/// <returns>The created book rating DTO.</returns>
|
||||
public BookRatingDto CreateComplete()
|
||||
{
|
||||
return new BookRatingDto(
|
||||
_random.Next(1, 5),
|
||||
5,
|
||||
_fixture.Create<BookRatingSource>(),
|
||||
_random.Next(1, 1000)
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a minimal book rating DTO with only required properties.
|
||||
/// </summary>
|
||||
/// <returns>The created book rating DTO.</returns>
|
||||
public BookRatingDto CreateMinimal()
|
||||
{
|
||||
return new BookRatingDto(
|
||||
_random.Next(1, 5),
|
||||
5,
|
||||
null,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an invalid book rating DTO.
|
||||
/// </summary>
|
||||
/// <returns>The created invalid book rating DTO.</returns>
|
||||
public BookRatingDto CreateInvalid()
|
||||
{
|
||||
return new BookRatingDto(
|
||||
10, // invalid: value > maxValue
|
||||
5,
|
||||
_fixture.Create<BookRatingSource>(),
|
||||
_random.Next(1, 1000)
|
||||
);
|
||||
}
|
||||
}
|
||||
-55
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="BookRatingEntity"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookRatingEntityFixture
|
||||
{
|
||||
private readonly Random _random = new();
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookRatingEntityFixture"/> class.
|
||||
/// </summary>
|
||||
public BookRatingEntityFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a book rating entity.
|
||||
/// </summary>
|
||||
/// <returns>The created book rating entity.</returns>
|
||||
public BookRatingEntity CreateBookRating()
|
||||
{
|
||||
return new BookRatingEntity(
|
||||
_random.Next(1, 5),
|
||||
5,
|
||||
_faker.PickRandom<BookRatingSource>(),
|
||||
_random.Next(1, 1000)
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an invalid book rating entity.
|
||||
/// </summary>
|
||||
/// <returns>The created invalid book rating entity.</returns>
|
||||
public BookRatingEntity CreateInvalidBookRating()
|
||||
{
|
||||
return new BookRatingEntity(
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null
|
||||
);
|
||||
}
|
||||
}
|
||||
-85
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="BookRating"/> domain entity.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookRatingFixture
|
||||
{
|
||||
private readonly Fixture _fixture;
|
||||
private readonly Random _random = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookRatingFixture"/> class.
|
||||
/// </summary>
|
||||
public BookRatingFixture()
|
||||
{
|
||||
_fixture = new Fixture();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid book rating.
|
||||
/// </summary>
|
||||
/// <returns>The created book rating.</returns>
|
||||
public BookRating CreateBookRating()
|
||||
{
|
||||
decimal maxValue = _random.Next(5, 10);
|
||||
decimal value = _random.Next(1, (int)maxValue);
|
||||
Optional<BookRatingSource> source = Optional<BookRatingSource>.Some(_fixture.Create<BookRatingSource>());
|
||||
Optional<int> voteCount = Optional<int>.Some(_random.Next(1, 1000));
|
||||
|
||||
return BookRating.Create(value, maxValue, source, voteCount).Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid book rating with specific parameters.
|
||||
/// </summary>
|
||||
/// <param name="value">The rating value.</param>
|
||||
/// <param name="maxValue">The maximum possible rating value.</param>
|
||||
/// <param name="source">The rating source.</param>
|
||||
/// <param name="voteCount">The number of votes.</param>
|
||||
/// <returns>The created book rating.</returns>
|
||||
public BookRating CreateBookRating(
|
||||
decimal value,
|
||||
decimal maxValue,
|
||||
Optional<BookRatingSource> source,
|
||||
Optional<int> voteCount)
|
||||
{
|
||||
return BookRating.Create(value, maxValue, source, voteCount).Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid book rating without a source.
|
||||
/// </summary>
|
||||
/// <returns>The created book rating.</returns>
|
||||
public BookRating CreateBookRatingWithoutSource()
|
||||
{
|
||||
decimal maxValue = _random.Next(5, 10);
|
||||
decimal value = _random.Next(1, (int)maxValue);
|
||||
Optional<int> voteCount = Optional<int>.Some(_random.Next(1, 1000));
|
||||
|
||||
return BookRating.Create(value, maxValue, Optional<BookRatingSource>.None(), voteCount).Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid book rating without vote count.
|
||||
/// </summary>
|
||||
/// <returns>The created book rating.</returns>
|
||||
public BookRating CreateBookRatingWithoutVoteCount()
|
||||
{
|
||||
decimal maxValue = _random.Next(5, 10);
|
||||
decimal value = _random.Next(1, (int)maxValue);
|
||||
Optional<BookRatingSource> source = Optional<BookRatingSource>.Some(_fixture.Create<BookRatingSource>());
|
||||
|
||||
return BookRating.Create(value, maxValue, source, Optional<int>.None()).Value;
|
||||
}
|
||||
}
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="IsbnDto"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IsbnDtoFixture
|
||||
{
|
||||
private readonly Random _random = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a valid ISBN-10 DTO.
|
||||
/// </summary>
|
||||
/// <returns>The created ISBN DTO.</returns>
|
||||
public IsbnDto CreateIsbn10()
|
||||
{
|
||||
return new IsbnDto(
|
||||
GenerateValidIsbn10(),
|
||||
IsbnFormat.Isbn10
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a valid ISBN-13 DTO.
|
||||
/// </summary>
|
||||
/// <returns>The created ISBN DTO.</returns>
|
||||
public IsbnDto CreateIsbn13()
|
||||
{
|
||||
return new IsbnDto(
|
||||
GenerateValidIsbn13(),
|
||||
IsbnFormat.Isbn13
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an invalid ISBN DTO.
|
||||
/// </summary>
|
||||
/// <returns>The created invalid ISBN DTO.</returns>
|
||||
public IsbnDto CreateInvalid()
|
||||
{
|
||||
return new IsbnDto(
|
||||
"invalid-isbn",
|
||||
IsbnFormat.Isbn13
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an ISBN entity without format.
|
||||
/// </summary>
|
||||
/// <returns>The created ISBN entity.</returns>
|
||||
public IsbnDto CreateWithoutFormat()
|
||||
{
|
||||
return new IsbnDto(
|
||||
GenerateValidIsbn13(),
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
private string GenerateValidIsbn10()
|
||||
{
|
||||
int[] digits = new int[9];
|
||||
for (int i = 0; i < 9; i++)
|
||||
digits[i] = _random.Next(0, 10);
|
||||
|
||||
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}";
|
||||
}
|
||||
|
||||
private string GenerateValidIsbn13()
|
||||
{
|
||||
string prefix = _random.Next(2) == 0 ? "978" : "979";
|
||||
string group = _random.Next(0, 99999).ToString().PadLeft(5, '0');
|
||||
string publisher = _random.Next(0, 999999).ToString().PadLeft(6, '0');
|
||||
string title = _random.Next(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}";
|
||||
}
|
||||
}
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="Isbn"/> domain entity.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IsbnFixture
|
||||
{
|
||||
private readonly Random _random = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a valid ISBN-10.
|
||||
/// </summary>
|
||||
/// <returns>The created ISBN.</returns>
|
||||
public Isbn CreateIsbn10()
|
||||
{
|
||||
string isbn = GenerateValidIsbn10();
|
||||
return Isbn.Create(isbn, IsbnFormat.Isbn10).Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a valid ISBN-13.
|
||||
/// </summary>
|
||||
/// <returns>The created ISBN.</returns>
|
||||
public Isbn CreateIsbn13()
|
||||
{
|
||||
string isbn = GenerateValidIsbn13();
|
||||
return Isbn.Create(isbn, IsbnFormat.Isbn13).Value;
|
||||
}
|
||||
|
||||
private string GenerateValidIsbn10()
|
||||
{
|
||||
int[] digits = new int[9];
|
||||
for (int i = 0; i < 9; i++)
|
||||
digits[i] = _random.Next(0, 10);
|
||||
|
||||
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}";
|
||||
}
|
||||
|
||||
private string GenerateValidIsbn13()
|
||||
{
|
||||
string prefix = _random.Next(2) == 0 ? "978" : "979";
|
||||
string group = _random.Next(0, 99999).ToString().PadLeft(5, '0');
|
||||
string publisher = _random.Next(0, 999999).ToString().PadLeft(6, '0');
|
||||
string title = _random.Next(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}";
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -4,7 +4,7 @@ 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;
|
||||
@@ -44,8 +44,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<CancellationToken>())
|
||||
.Returns(new List<LibraryMetadataProviderConfigurationEntity> { firstProvider, secondProvider });
|
||||
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
|
||||
|
||||
+2
-2
@@ -3,8 +3,8 @@ 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;
|
||||
@@ -39,7 +39,7 @@ public class GetPluginsQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
PluginEntityFixture pluginFixture = new();
|
||||
List<PluginEntity> plugins = [pluginFixture.CreatePluginEntity(), pluginFixture.CreatePluginEntity()];
|
||||
List<PluginEntity> plugins = [pluginFixture.Create(), pluginFixture.Create()];
|
||||
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(plugins);
|
||||
|
||||
// Act
|
||||
|
||||
+6
-5
@@ -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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ChangePasswordCommandHandlerTests"/> 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,
|
||||
|
||||
+20
-18
@@ -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;
|
||||
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Comma
|
||||
public class ChangePasswordCommandValidatorTests
|
||||
{
|
||||
private readonly ChangePasswordCommandValidator _validator;
|
||||
private readonly ChangePasswordCommandFixture _changePasswordCommandFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ChangePasswordCommandValidatorTests"/> class.
|
||||
@@ -24,13 +25,14 @@ public class ChangePasswordCommandValidatorTests
|
||||
public ChangePasswordCommandValidatorTests()
|
||||
{
|
||||
_validator = new ChangePasswordCommandValidator();
|
||||
_changePasswordCommandFixture = new ChangePasswordCommandFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
|
||||
command = command with { Username = null! };
|
||||
|
||||
// Act
|
||||
@@ -44,7 +46,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 +60,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 +74,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 +88,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 +102,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 +116,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 +130,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 +144,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 +158,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 +172,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 +186,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 +200,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 +220,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 +240,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 +258,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 +278,7 @@ public class ChangePasswordCommandValidatorTests
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
ChangePasswordCommand command = _changePasswordCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
-35
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ChangePasswordCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command for changing a password.
|
||||
/// </summary>
|
||||
/// <returns>The created command.</returns>
|
||||
public static ChangePasswordCommand CreateChangePasswordCommand()
|
||||
{
|
||||
string currentPassword = "Abcd123$";
|
||||
string newPassword = "Wxyz789#";
|
||||
return new Faker<ChangePasswordCommand>()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
-56
@@ -1,56 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ChangePasswordRequest"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordRequestFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ChangePasswordRequestFixture"/> class.
|
||||
/// </summary>
|
||||
public ChangePasswordRequestFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ChangePasswordRequest"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="ChangePasswordRequest"/>.</returns>
|
||||
public ChangePasswordRequest CreateChangePasswordRequest(
|
||||
string? username = null,
|
||||
string? currentPassword = null,
|
||||
string? newPassword = null,
|
||||
string? newPasswordConfirm = null)
|
||||
{
|
||||
return new ChangePasswordRequest(
|
||||
username ?? _faker.Internet.UserName(),
|
||||
currentPassword ?? _faker.Internet.Password(),
|
||||
newPassword ?? _faker.Internet.Password(),
|
||||
newPasswordConfirm ?? _faker.Internet.Password()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="ChangePasswordRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<ChangePasswordRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count)
|
||||
.Select(_ => CreateChangePasswordRequest())
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
-29
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RecoverPasswordCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command for password recovery.
|
||||
/// </summary>
|
||||
/// <returns>The created command.</returns>
|
||||
public static RecoverPasswordCommand CreateRecoverPasswordCommand()
|
||||
{
|
||||
return new Faker<RecoverPasswordCommand>()
|
||||
.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
|
||||
}
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RecoverPasswordRequest"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordRequestFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RecoverPasswordRequestFixture"/> class.
|
||||
/// </summary>
|
||||
public RecoverPasswordRequestFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="RecoverPasswordRequest"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="RecoverPasswordRequest"/>.</returns>
|
||||
public RecoverPasswordRequest CreateRecoverPasswordRequest(
|
||||
string? username = null,
|
||||
string? totpCode = null)
|
||||
{
|
||||
return new RecoverPasswordRequest(
|
||||
username ?? _faker.Internet.UserName(),
|
||||
totpCode ?? _faker.Random.Number(100000, 999999).ToString()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="RecoverPasswordRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<RecoverPasswordRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count)
|
||||
.Select(_ => CreateRecoverPasswordRequest())
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
+9
-8
@@ -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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CheckInitializationQueryHandlerTests"/> 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);
|
||||
|
||||
+12
-10
@@ -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;
|
||||
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Comma
|
||||
public class RecoverPasswordCommandValidatorTests
|
||||
{
|
||||
private readonly RecoverPasswordCommandValidator _validator;
|
||||
private readonly RecoverPasswordCommandFixture _recoverPasswordCommandFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RecoverPasswordCommandValidatorTests"/> class.
|
||||
@@ -24,13 +25,14 @@ public class RecoverPasswordCommandValidatorTests
|
||||
public RecoverPasswordCommandValidatorTests()
|
||||
{
|
||||
_validator = new RecoverPasswordCommandValidator();
|
||||
_recoverPasswordCommandFixture = new RecoverPasswordCommandFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
|
||||
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
|
||||
command = command with { Username = null! };
|
||||
|
||||
// Act
|
||||
@@ -44,7 +46,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 +60,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 +74,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 +88,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 +102,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 +122,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 +139,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 +153,7 @@ public class RecoverPasswordCommandValidatorTests
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
|
||||
RecoverPasswordCommand command = _recoverPasswordCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
-33
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RegisterUserCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegisterUserCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command for a new account registration.
|
||||
/// </summary>
|
||||
/// <returns>The created command.</returns>
|
||||
public static RegisterUserCommand CreateRegisterCommand()
|
||||
{
|
||||
string password = "Abcd123$";
|
||||
return new Faker<RegisterUserCommand>()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RegistrationRequest"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegistrationRequestFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RegistrationRequestFixture"/> class.
|
||||
/// </summary>
|
||||
public RegistrationRequestFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="RegistrationRequest"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="RegistrationRequest"/>.</returns>
|
||||
public RegistrationRequest CreateRegistrationRequest(
|
||||
string? username = null,
|
||||
string? password = null,
|
||||
string? passwordConfirm = null,
|
||||
bool? use2fa = null)
|
||||
{
|
||||
password ??= _faker.Internet.Password();
|
||||
|
||||
return new RegistrationRequest(
|
||||
username ?? _faker.Internet.UserName(),
|
||||
password,
|
||||
passwordConfirm ?? password,
|
||||
use2fa ?? _faker.Random.Bool()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="RegistrationRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<RegistrationRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count)
|
||||
.Select(_ => CreateRegistrationRequest())
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
+10
-8
@@ -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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RegisterUserCommandHandlerTests"/> 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<CancellationToken>())
|
||||
@@ -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<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(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<CancellationToken>())
|
||||
@@ -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<CancellationToken>())
|
||||
|
||||
+19
-17
@@ -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;
|
||||
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Comma
|
||||
public class RegisterUserCommandValidatorTests
|
||||
{
|
||||
private readonly RegisterUserCommandValidator _validator;
|
||||
private readonly RegisterUserCommandFixture _registerUserCommandFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RegisterUserCommandValidatorTests"/> class.
|
||||
@@ -24,13 +25,14 @@ public class RegisterUserCommandValidatorTests
|
||||
public RegisterUserCommandValidatorTests()
|
||||
{
|
||||
_validator = new RegisterUserCommandValidator();
|
||||
_registerUserCommandFixture = new RegisterUserCommandFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
RegisterUserCommand command = _registerUserCommandFixture.Create();
|
||||
command = command with { Username = null! };
|
||||
|
||||
// Act
|
||||
@@ -44,7 +46,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 +60,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 +74,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 +88,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 +102,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 +116,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 +130,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 +144,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 +158,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 +178,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 +196,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 +210,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 +234,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 +258,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 +279,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
|
||||
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUsers;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.GetUsers.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetUsersQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUsersQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get users.
|
||||
/// </summary>
|
||||
/// <returns>The created query.</returns>
|
||||
public GetUsersQuery CreateQuery()
|
||||
{
|
||||
return new GetUsersQuery();
|
||||
}
|
||||
}
|
||||
+7
-6
@@ -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,6 +32,7 @@ public class GetUsersQueryHandlerTests
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IUserRepository _mockUserRepository;
|
||||
private readonly GetUsersQueryHandler _sut;
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly GetUsersQueryFixture _getUsersQueryFixture;
|
||||
private readonly Guid _userId;
|
||||
|
||||
@@ -60,7 +61,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<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
@@ -77,7 +78,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<CancellationToken>())
|
||||
@@ -97,8 +98,8 @@ public class GetUsersQueryHandlerTests
|
||||
public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnUsers()
|
||||
{
|
||||
// Arrange
|
||||
GetUsersQuery query = _getUsersQueryFixture.CreateQuery();
|
||||
IEnumerable<UserEntity> users = UserEntityFixture.CreateMany(2);
|
||||
GetUsersQuery query = _getUsersQueryFixture.Create();
|
||||
IEnumerable<UserEntity> users = _userEntityFixture.CreateMany(2);
|
||||
|
||||
|
||||
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
|
||||
|
||||
-54
@@ -1,54 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="LoginRequest"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginRequestFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginRequestFixture"/> class.
|
||||
/// </summary>
|
||||
public LoginRequestFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="LoginRequest"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="LoginRequest"/>.</returns>
|
||||
public LoginRequest CreateLoginRequest(
|
||||
string? username = null,
|
||||
string? password = null,
|
||||
string? totpCode = null)
|
||||
{
|
||||
return new LoginRequest(
|
||||
username ?? _faker.Internet.UserName(),
|
||||
password ?? _faker.Internet.Password(),
|
||||
totpCode ?? _faker.Random.Number(100000, 999999).ToString()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="LoginRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<LoginRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count)
|
||||
.Select(_ => CreateLoginRequest())
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="LoginUserQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginUserQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query for user login.
|
||||
/// </summary>
|
||||
/// <param name="includeTotpCode">Whether to include a TOTP code in the query.</param>
|
||||
/// <returns>The created query.</returns>
|
||||
public static LoginUserQuery CreateLoginQuery(bool includeTotpCode = false)
|
||||
{
|
||||
string password = "Abcd123$";
|
||||
Faker<LoginUserQuery> faker = new Faker<LoginUserQuery>()
|
||||
.CustomInstantiator(f => new LoginUserQuery(
|
||||
default!,
|
||||
default!,
|
||||
default
|
||||
))
|
||||
.RuleFor(x => x.Username, f => f.Person.UserName)
|
||||
.RuleFor(x => x.Password, password);
|
||||
|
||||
if (includeTotpCode)
|
||||
faker.RuleFor(x => x.TotpCode, f => f.Random.Replace("######")); // generates 6 random digits
|
||||
return faker;
|
||||
}
|
||||
}
|
||||
+10
-9
@@ -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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginUserQueryHandlerTests"/> 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
|
||||
|
||||
+15
-13
@@ -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;
|
||||
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queri
|
||||
public class LoginUserQueryValidatorTests
|
||||
{
|
||||
private readonly LoginUserQueryValidator _validator;
|
||||
private readonly LoginUserQueryFixture _loginUserQueryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginUserQueryValidatorTests"/> class.
|
||||
@@ -24,13 +25,14 @@ public class LoginUserQueryValidatorTests
|
||||
public LoginUserQueryValidatorTests()
|
||||
{
|
||||
_validator = new LoginUserQueryValidator();
|
||||
_loginUserQueryFixture = new LoginUserQueryFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
|
||||
LoginUserQuery query = _loginUserQueryFixture.Create();
|
||||
query = query with { Username = null! };
|
||||
|
||||
// Act
|
||||
@@ -44,7 +46,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 +60,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 +74,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 +88,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 +102,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 +122,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 +140,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 +160,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 +177,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 +191,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 +205,7 @@ public class LoginUserQueryValidatorTests
|
||||
public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(true);
|
||||
LoginUserQuery query = _loginUserQueryFixture.Create(includeTotpCode: true);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
-36
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateUserRoleAndPermissionsCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserRoleAndPermissionsCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command to update user role and permissions.
|
||||
/// </summary>
|
||||
/// <param name="roleId">Optional role ID to assign. If null, no role will be assigned.</param>
|
||||
/// <param name="permissionCount">The number of permissions to generate.</param>
|
||||
/// <returns>The created command.</returns>
|
||||
public UpdateUserRoleAndPermissionsCommand CreateCommand(Guid? roleId = null, int permissionCount = 3)
|
||||
{
|
||||
return new Faker<UpdateUserRoleAndPermissionsCommand>()
|
||||
.CustomInstantiator(f => new UpdateUserRoleAndPermissionsCommand(
|
||||
Guid.NewGuid(),
|
||||
roleId,
|
||||
default!))
|
||||
.RuleFor(x => x.Permissions, f => Enumerable.Range(0, permissionCount)
|
||||
.Select(_ => Guid.NewGuid())
|
||||
.ToList())
|
||||
.Generate();
|
||||
}
|
||||
}
|
||||
|
||||
+13
-12
@@ -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,6 +39,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
|
||||
private readonly IRoleRepository _mockRoleRepository;
|
||||
private readonly IPermissionRepository _mockPermissionRepository;
|
||||
private readonly UpdateUserRoleAndPermissionsCommandHandler _sut;
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly UpdateUserRoleAndPermissionsCommandFixture _updateUserRoleAndPermissionsCommandFixture;
|
||||
private readonly Guid _userId;
|
||||
|
||||
@@ -75,7 +76,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<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
@@ -92,7 +93,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<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockUserRepository.GetByIdAsync(command.UserId, Arg.Any<CancellationToken>())
|
||||
@@ -110,8 +111,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<CancellationToken>())
|
||||
.Returns(true);
|
||||
@@ -132,7 +133,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 +179,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<PermissionEntity> permissions = command.Permissions.Select(p =>
|
||||
new PermissionEntity { Id = p, PermissionName = AuthorizationPermission.CanViewUsers });
|
||||
@@ -209,7 +210,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 +262,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 +303,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,
|
||||
|
||||
-54
@@ -1,54 +0,0 @@
|
||||
#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;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetAuthorization.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetAuthorizationQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAuthorizationQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get authorization details.
|
||||
/// </summary>
|
||||
/// <param name="userId">Optional user Id to use. If null, a random GUID will be generated.</param>
|
||||
/// <returns>The created query.</returns>
|
||||
public static GetAuthorizationQuery CreateGetAuthorizationQuery(Guid? userId = null)
|
||||
{
|
||||
return new Faker<GetAuthorizationQuery>()
|
||||
.CustomInstantiator(f => new GetAuthorizationQuery(
|
||||
userId ?? f.Random.Guid()
|
||||
))
|
||||
.Generate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid authorization entity.
|
||||
/// </summary>
|
||||
/// <param name="userId">Optional user Id to use. If null, a random GUID will be generated.</param>
|
||||
/// <param name="isAdmin">Whether the user should have admin role.</param>
|
||||
/// <returns>The created entity.</returns>
|
||||
public static UserAuthorizationEntity CreateUserAuthorizationEntity(Guid? userId = null, bool isAdmin = false)
|
||||
{
|
||||
string role = isAdmin ? "Admin" : string.Empty;
|
||||
|
||||
return new UserAuthorizationEntity
|
||||
{
|
||||
UserId = userId ?? Guid.NewGuid(),
|
||||
Role = role,
|
||||
Permissions = new HashSet<AuthorizationPermission>
|
||||
{
|
||||
AuthorizationPermission.CanViewUsers,
|
||||
AuthorizationPermission.CanRegisterUsers
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+16
-11
@@ -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;
|
||||
private readonly UserAuthorizationEntityFixture _userAuthorizationEntityFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAuthorizationQueryHandlerTests"/> class.
|
||||
@@ -34,6 +37,8 @@ public class GetAuthorizationQueryHandlerTests
|
||||
{
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_getAuthorizationQueryFixture = new GetAuthorizationQueryFixture();
|
||||
_userAuthorizationEntityFixture = new UserAuthorizationEntityFixture();
|
||||
IValidator<GetAuthorizationQuery> mockValidator = Substitute.For<IValidator<GetAuthorizationQuery>>();
|
||||
mockValidator.Validate(Arg.Any<GetAuthorizationQuery>())
|
||||
.Returns([]);
|
||||
@@ -45,8 +50,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<CancellationToken>())
|
||||
@@ -68,9 +73,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<CancellationToken>())
|
||||
@@ -94,8 +99,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<CancellationToken>())
|
||||
@@ -115,7 +120,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 +141,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);
|
||||
|
||||
+6
-4
@@ -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;
|
||||
@@ -18,6 +18,7 @@ namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Querie
|
||||
public class GetAuthorizationQueryValidatorTests
|
||||
{
|
||||
private readonly GetAuthorizationQueryValidator _validator;
|
||||
private readonly GetAuthorizationQueryFixture _getAuthorizationQueryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAuthorizationQueryValidatorTests"/> class.
|
||||
@@ -25,13 +26,14 @@ public class GetAuthorizationQueryValidatorTests
|
||||
public GetAuthorizationQueryValidatorTests()
|
||||
{
|
||||
_validator = new GetAuthorizationQueryValidator();
|
||||
_getAuthorizationQueryFixture = new GetAuthorizationQueryFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUserIdIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery();
|
||||
GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create();
|
||||
query = query with { UserId = null };
|
||||
|
||||
// Act
|
||||
@@ -45,7 +47,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 +61,7 @@ public class GetAuthorizationQueryValidatorTests
|
||||
public void Validate_WhenUserIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetAuthorizationQuery query = GetAuthorizationQueryFixture.CreateGetAuthorizationQuery();
|
||||
GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.UsersManagement.Authorization.Queries.GetUserPermissions.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetUserPermissionsQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserPermissionsQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get user permissions.
|
||||
/// </summary>
|
||||
/// <returns>The created query.</returns>
|
||||
public GetUserPermissionsQuery CreateQuery()
|
||||
{
|
||||
return new Faker<GetUserPermissionsQuery>()
|
||||
.CustomInstantiator(f => new GetUserPermissionsQuery(
|
||||
Guid.NewGuid()))
|
||||
.Generate();
|
||||
}
|
||||
}
|
||||
Loaded 100 of 294 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user