diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index b3ea67d4..905573aa 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -3,6 +3,7 @@ using FluentValidation; using Lumina.Application.Common.Behaviors; using Mediator; using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Application.Common.DependencyInjection; @@ -10,6 +11,7 @@ namespace Lumina.Application.Common.DependencyInjection; /// /// Contains all services of the Application layer. /// +[ExcludeFromCodeCoverage] public static class ApplicationLayerServices { /// diff --git a/src/Lumina.Application/Common/Mapping/Authentication/RegistrationRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Authentication/RegistrationRequestMapping.cs index 9cef13b5..49cdc0c9 100644 --- a/src/Lumina.Application/Common/Mapping/Authentication/RegistrationRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Authentication/RegistrationRequestMapping.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; using Lumina.Contracts.Requests.Authentication; #endregion diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommand.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommand.cs similarity index 89% rename from src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommand.cs rename to src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommand.cs index b31989d5..8d9c161a 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommand.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommand.cs @@ -4,7 +4,7 @@ using Lumina.Contracts.Responses.Authentication; using Mediator; #endregion -namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands; +namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; /// /// Command for the initial application setup. @@ -14,8 +14,8 @@ namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands; /// Confirmation of the password. /// Indicates whether to enable two-factor authentication for the Admin account. public record SetupApplicationCommand( - string? Username, - string? Password, - string? PasswordConfirm, + string? Username, + string? Password, + string? PasswordConfirm, bool Use2fa ) : IRequest>; diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs similarity index 97% rename from src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandHandler.cs rename to src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs index 64e2688e..5f2ce8b7 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs @@ -15,7 +15,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands; +namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; /// /// Handler for the command to perform the initial application setup. @@ -37,9 +37,9 @@ public class SetupApplicationCommandHandler : IRequestHandlerInjected service for generating and validating TOTP tokens. /// Injected service for generating QR codes. public SetupApplicationCommandHandler( - IUnitOfWork unitOfWork, - IHashService hashService, - ICryptographyService cryptographyService, + IUnitOfWork unitOfWork, + IHashService hashService, + ICryptographyService cryptographyService, ITotpTokenGenerator totpTokenGenerator, IQRCodeGenerator qRCodeGenerator) { diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandValidator.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidator.cs similarity index 98% rename from src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandValidator.cs rename to src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidator.cs index d1def565..b7d75b24 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandValidator.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidator.cs @@ -3,7 +3,7 @@ using FluentValidation; using Lumina.Application.Common.Errors; #endregion -namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands; +namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; /// /// Validates the needed validation rules for . diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitializationQuery.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQuery.cs similarity index 94% rename from src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitializationQuery.cs rename to src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQuery.cs index d2ef6026..3400a137 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitializationQuery.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQuery.cs @@ -3,7 +3,7 @@ using Lumina.Contracts.Responses.UsersManagement; using Mediator; #endregion -namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries; +namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; /// /// Query for checking the initialization of the application. diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitializationQueryHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs similarity index 93% rename from src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitializationQueryHandler.cs rename to src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs index 01b554d6..690c99d8 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitializationQueryHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs @@ -13,7 +13,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries; +namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; /// /// Handler for the query to check the initialization of the application. @@ -22,6 +22,9 @@ public class CheckInitializationQueryHandler : IRequestHandler + /// Initializes a new instance of the class. + /// public CheckInitializationQueryHandler(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs index af17ae55..9db2c4c4 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs @@ -48,6 +48,14 @@ public class RegisterUserCommandHandler : IRequestHandler + /// Handles the command to register an account. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// public async ValueTask> Handle(RegisterUserCommand request, CancellationToken cancellationToken) { // check if any users already exists (admin account is only set once!) diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs index 7f05d206..5ea0c600 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs @@ -72,7 +72,7 @@ public class LoginUserQueryHandler : IRequestHandler DateTime.UtcNow) + if (resultSelectUser.Value.TempPasswordCreated!.Value.AddMinutes(15) < DateTime.UtcNow) { resultSelectUser.Value.TempPassword = null; resultSelectUser.Value.TempPasswordCreated = null; diff --git a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs index bc5fd532..53050eeb 100644 --- a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs +++ b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs @@ -7,6 +7,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; @@ -17,6 +18,7 @@ namespace Lumina.DataAccess.Common.DependencyInjection; /// /// Contains all services of the DataAccess layer. /// +[ExcludeFromCodeCoverage] public static class DataAccessLayerServices { /// diff --git a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs index 14ff1d88..c81e80d0 100644 --- a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs +++ b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs @@ -4,6 +4,7 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; using System.IO.Abstractions; #endregion @@ -12,6 +13,7 @@ namespace Lumina.Domain.Common.DependencyInjection; /// /// Contains all services of the Domain layer. /// +[ExcludeFromCodeCoverage] public static class DomainLayerServices { /// diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 5de680f6..13c0096f 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -7,6 +7,7 @@ using Lumina.Infrastructure.Core.Authentication; using Lumina.Infrastructure.Core.Security; using Lumina.Infrastructure.Core.Time; using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; using System.Reflection; #endregion @@ -15,6 +16,7 @@ namespace Lumina.Infrastructure.Common.DependencyInjection; /// /// Contains all services of the Infrastructure layer. /// +[ExcludeFromCodeCoverage] public static class InfrastructureLayerServices { /// diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs index 877c375b..430d8cfe 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs @@ -3,6 +3,7 @@ using Lumina.Infrastructure.Common.Models.Configuration; using Lumina.Infrastructure.Common.Utilities; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; #endregion @@ -12,6 +13,7 @@ namespace Lumina.Infrastructure.Common.DependencyInjection; /// /// Class containing the shared configuration bindings of the application. /// +[ExcludeFromCodeCoverage] public static class SharedConfiguration { /// diff --git a/src/Lumina.Infrastructure/Core/Time/DateTimeProvider.cs b/src/Lumina.Infrastructure/Core/Time/DateTimeProvider.cs index d6d5a211..2334c5aa 100644 --- a/src/Lumina.Infrastructure/Core/Time/DateTimeProvider.cs +++ b/src/Lumina.Infrastructure/Core/Time/DateTimeProvider.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Time; using System; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Infrastructure.Core.Time; @@ -8,6 +9,7 @@ namespace Lumina.Infrastructure.Core.Time; /// /// Service for time related concerns /// +[ExcludeFromCodeCoverage] public class DateTimeProvider : IDateTimeProvider { /// diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs index b0853263..148e42f4 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; #endregion @@ -10,6 +11,7 @@ namespace Lumina.Presentation.Api.Common.DependencyInjection; /// /// Class containing the configuration bindings of the Presentation API layer. /// +[ExcludeFromCodeCoverage] internal static class PresentationApiLayerConfiguration { /// diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index 346ea65a..a62f62fc 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -11,6 +11,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using System; +using System.Diagnostics.CodeAnalysis; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; @@ -22,6 +23,7 @@ namespace Lumina.Presentation.Api.Common.DependencyInjection; /// /// Contains all services of the Presentation API layer. /// +[ExcludeFromCodeCoverage] public static class PresentationApiLayerServices { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs index 254e1cb1..23c84f93 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Contracts.Requests.FileSystemManagement.Directories; using Lumina.Contracts.Responses.FileSystemManagement.Directories; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; @@ -10,6 +11,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directorie /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class GetDirectoriesEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpointSummary.cs index d8954ec5..da5e6175 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpointSummary.cs @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Contracts.Requests.FileSystemManagement.Directories; using Lumina.Contracts.Responses.FileSystemManagement.Common; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectoryTree; @@ -10,6 +11,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directorie /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class GetDirectoryTreeEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpointSummary.cs index 107a5e3f..434d3740 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpointSummary.cs @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Contracts.Requests.FileSystemManagement.Directories; using Lumina.Contracts.Responses.FileSystemManagement.Common; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetTreeDirectories; @@ -10,6 +11,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directorie /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class GetTreeDirectoriesEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs index 7c4a876d..d6b5ddbc 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Contracts.Responses.FileSystemManagement.Common; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.GetDrives; @@ -9,6 +10,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.Get /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class GetDrivesEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs index be0c69d3..7aaf65bb 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem.GetType; @@ -8,6 +9,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class GetTypeEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs index c247e725..831d31c8 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Contracts.Requests.FileSystemManagement.Files; using Lumina.Contracts.Responses.FileSystemManagement.Common; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetFiles; @@ -10,6 +11,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetF /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class GetFilesEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs index 1a227c34..49be978e 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Contracts.Requests.FileSystemManagement.Files; using Lumina.Contracts.Responses.FileSystemManagement.Common; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; @@ -10,6 +11,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetT /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class GetTreeFilesEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs index f75d6371..c8a159e1 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs @@ -3,6 +3,7 @@ using FastEndpoints; using FastEndpoints.Swagger; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; @@ -10,6 +11,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.Check /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class CheckPathExistsEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpointSummary.cs index a027c023..3babebc1 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CombinePath/CombinePathEndpointSummary.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CombinePath; @@ -9,6 +10,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.Combi /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class CombinePathEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs index 67611bf2..44e2d177 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathParent; @@ -10,6 +11,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPa /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class GetPathParentEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs index 03c63e27..57e558b4 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; @@ -9,6 +10,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPa /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class GetPathRootEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs index 845c462f..28aa7765 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; @@ -8,6 +9,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPa /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class GetPathSeparatorEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs index 4344a365..f0df92ec 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.SplitPath; @@ -10,6 +11,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.Split /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class SplitPathEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs index 1a19a34f..011ccc4c 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.ValidatePath; @@ -9,6 +10,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.Valid /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class ValidatePathEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointSummary.cs index 9de7f5a8..cbaad9ef 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointSummary.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail; @@ -8,6 +9,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class GetThumbnailEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs index 3e6756f4..3df13595 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System.Diagnostics.CodeAnalysis; #endregion @@ -10,6 +11,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class AddLibraryEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs index e4a78069..49a7af53 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks; @@ -9,6 +10,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class GetBooksEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/Management/AddLibrary/AddLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/Management/AddLibrary/AddLibraryEndpointSummary.cs index d7388b32..b5519fe2 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/Management/AddLibrary/AddLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/Management/AddLibrary/AddLibraryEndpointSummary.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; +using System.Diagnostics.CodeAnalysis; #endregion @@ -11,6 +12,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.M /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class AddLibraryEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs index 97228c65..0ac46c2d 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpoint.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; -using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; using Lumina.Contracts.Responses.UsersManagement; using Lumina.Presentation.Api.Common.Routes.Maintenance; using Lumina.Presentation.Api.Core.Endpoints.Common; diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointSummary.cs index e0287981..56ffe275 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointSummary.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.Responses.UsersManagement; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; @@ -8,6 +9,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class CheckInitializationEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs index dfe83f21..1c08943b 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; @@ -8,6 +9,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class SetupApplicationEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs index 6b340e79..24a4eb2f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.ChangePassword; @@ -8,6 +9,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication. /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class ChangePasswordEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointSummary.cs index c211da62..8ba72585 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointSummary.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Login; @@ -8,6 +9,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication. /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class LoginEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointSummary.cs index 9488321d..af3f3afe 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointSummary.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; @@ -8,6 +9,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication. /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class RecoverPasswordEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointSummary.cs index cb239aee..04f87c13 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointSummary.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register; @@ -8,6 +9,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication. /// /// Class used for providing a textual description for the API endpoint, for Swagger. /// +[ExcludeFromCodeCoverage] public class RegisterEndpointSummary : Summary { /// diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index 6bfc0cf3..72ba4875 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -15,6 +15,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Serilog; using System; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading.Tasks; #endregion @@ -24,6 +25,7 @@ namespace Lumina.Presentation.Api; /// /// Application entry point, contains the composition root module, wires up all dependencies of the application. /// +[ExcludeFromCodeCoverage] public class Program { /// diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs index 513b0223..e949c91d 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs @@ -3,6 +3,7 @@ using Lumina.Presentation.Web.Common.Models.Configuration; using Lumina.Presentation.Web.Common.Utilities; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Web.Common.DependencyInjection; @@ -10,6 +11,7 @@ namespace Lumina.Presentation.Web.Common.DependencyInjection; /// /// Class containing the configuration bindings of the Lumina.Presentation.Web project. /// +[ExcludeFromCodeCoverage] internal static class PresentationWebLayerConfiguration { /// diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index fb394a97..f21ac11c 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -17,6 +17,7 @@ using Polly.CircuitBreaker; using Polly.Retry; using Polly.Wrap; using System; +using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http; using System.Text.Json.Serialization; @@ -28,6 +29,7 @@ namespace Lumina.Presentation.Web.Common.DependencyInjection; /// /// Contains all services of the Presentation Web layer. /// +[ExcludeFromCodeCoverage] public static class PresentationWebLayerServices { /// diff --git a/src/Lumina.Presentation.Web/Program.cs b/src/Lumina.Presentation.Web/Program.cs index 7d4bf1a8..109a3e6e 100644 --- a/src/Lumina.Presentation.Web/Program.cs +++ b/src/Lumina.Presentation.Web/Program.cs @@ -7,6 +7,7 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Primitives; using Serilog; using System; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading.Tasks; #endregion @@ -16,6 +17,7 @@ namespace Lumina.Presentation.Web; /// /// Application entry point, contains the composition root module, wires up all dependencies of the application. /// +[ExcludeFromCodeCoverage] public class Program { /// diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/ChangePasswordRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/ChangePasswordRequestMappingTests.cs new file mode 100644 index 00000000..baa0a82c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/ChangePasswordRequestMappingTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +using Lumina.Application.Common.Mapping.Authentication; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordRequestMappingTests +{ + private readonly ChangePasswordRequestFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordRequestMappingTests() + { + _fixture = new(); + } + + [Fact] + public void ToCommand_WhenMappingRequest_ShouldMapCorrectly() + { + // Arrange + ChangePasswordRequest request = _fixture.CreateChangePasswordRequest(); + + // Act + ChangePasswordCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(request.Username); + result.CurrentPassword.Should().Be(request.CurrentPassword); + result.NewPassword.Should().Be(request.NewPassword); + result.NewPasswordConfirm.Should().Be(request.NewPasswordConfirm); + } + + [Fact] + public void ToCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly() + { + // Arrange + ChangePasswordRequest request = new(null, null, null, null); + + // Act + ChangePasswordCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().BeNull(); + result.CurrentPassword.Should().BeNull(); + result.NewPassword.Should().BeNull(); + result.NewPasswordConfirm.Should().BeNull(); + } + + [Theory] + [InlineData("user1", "oldPass", "newPass", "newPass")] + [InlineData("", "", "", "")] + [InlineData("testUser", null, "pass123", "pass123")] + public void ToCommand_WhenMappingRequestWithSpecificValues_ShouldMapCorrectly( + string? username, + string? currentPassword, + string? newPassword, + string? newPasswordConfirm) + { + // Arrange + ChangePasswordRequest request = new(username, currentPassword, newPassword, newPasswordConfirm); + + // Act + ChangePasswordCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(username); + result.CurrentPassword.Should().Be(currentPassword); + result.NewPassword.Should().Be(newPassword); + result.NewPasswordConfirm.Should().Be(newPasswordConfirm); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/LoginRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/LoginRequestMappingTests.cs new file mode 100644 index 00000000..bfe307f4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/LoginRequestMappingTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginRequestMappingTests +{ + private readonly LoginRequestFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public LoginRequestMappingTests() + { + _fixture = new(); + } + + [Fact] + public void ToQuery_WhenMappingRequest_ShouldMapCorrectly() + { + // Arrange + LoginRequest request = _fixture.CreateLoginRequest(); + + // Act + LoginUserQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(request.Username); + result.Password.Should().Be(request.Password); + result.TotpCode.Should().Be(request.TotpCode); + } + + [Fact] + public void ToQuery_WhenMappingRequestWithNullValues_ShouldMapCorrectly() + { + // Arrange + LoginRequest request = new(null, null); + + // Act + LoginUserQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().BeNull(); + result.Password.Should().BeNull(); + result.TotpCode.Should().BeNull(); + } + + [Theory] + [InlineData("user1", "pass123", "123456")] + [InlineData("", "", "")] + [InlineData("testUser", null, null)] + [InlineData("admin", "admin123", null)] + public void ToQuery_WhenMappingRequestWithSpecificValues_ShouldMapCorrectly( + string? username, + string? password, + string? totpCode) + { + // Arrange + LoginRequest request = new(username, password, totpCode); + + // Act + LoginUserQuery result = request.ToQuery(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(username); + result.Password.Should().Be(password); + result.TotpCode.Should().Be(totpCode); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RecoverPasswordRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RecoverPasswordRequestMappingTests.cs new file mode 100644 index 00000000..23b09457 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RecoverPasswordRequestMappingTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordRequestMappingTests +{ + private readonly RecoverPasswordRequestFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordRequestMappingTests() + { + _fixture = new(); + } + + [Fact] + public void ToCommand_WhenMappingRequest_ShouldMapCorrectly() + { + // Arrange + RecoverPasswordRequest request = _fixture.CreateRecoverPasswordRequest(); + + // Act + RecoverPasswordCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(request.Username); + result.TotpCode.Should().Be(request.TotpCode); + } + + [Fact] + public void ToCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly() + { + // Arrange + RecoverPasswordRequest request = new(null, null); + + // Act + RecoverPasswordCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().BeNull(); + result.TotpCode.Should().BeNull(); + } + + [Theory] + [InlineData("user1", "123456")] + [InlineData("", "")] + [InlineData("testUser", null)] + [InlineData(null, "654321")] + public void ToCommand_WhenMappingRequestWithSpecificValues_ShouldMapCorrectly( + string? username, + string? totpCode) + { + // Arrange + RecoverPasswordRequest request = new(username, totpCode); + + // Act + RecoverPasswordCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(username); + result.TotpCode.Should().Be(totpCode); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RegistrationRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RegistrationRequestMappingTests.cs new file mode 100644 index 00000000..155d6df4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authentication/RegistrationRequestMappingTests.cs @@ -0,0 +1,146 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.Authentication; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RegistrationRequestMappingTests +{ + private readonly RegistrationRequestFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public RegistrationRequestMappingTests() + { + _fixture = new(); + } + + [Fact] + public void ToSetupCommand_WhenMappingRequest_ShouldMapCorrectly() + { + // Arrange + RegistrationRequest request = _fixture.CreateRegistrationRequest(); + + // Act + SetupApplicationCommand result = request.ToSetupCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(request.Username); + result.Password.Should().Be(request.Password); + result.PasswordConfirm.Should().Be(request.PasswordConfirm); + result.Use2fa.Should().Be(request.Use2fa); + } + + [Fact] + public void ToCommand_WhenMappingRequest_ShouldMapCorrectly() + { + // Arrange + RegistrationRequest request = _fixture.CreateRegistrationRequest(); + + // Act + RegisterUserCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(request.Username); + result.Password.Should().Be(request.Password); + result.PasswordConfirm.Should().Be(request.PasswordConfirm); + result.Use2fa.Should().Be(request.Use2fa); + } + + [Fact] + public void ToSetupCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly() + { + // Arrange + RegistrationRequest request = new(); + + // Act + SetupApplicationCommand result = request.ToSetupCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().BeNull(); + result.Password.Should().BeNull(); + result.PasswordConfirm.Should().BeNull(); + result.Use2fa.Should().BeTrue(); + } + + [Fact] + public void ToCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly() + { + // Arrange + RegistrationRequest request = new(); + + // Act + RegisterUserCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().BeNull(); + result.Password.Should().BeNull(); + result.PasswordConfirm.Should().BeNull(); + result.Use2fa.Should().BeTrue(); + } + + [Theory] + [InlineData("user1", "pass123", "pass123", true)] + [InlineData("", "", "", false)] + [InlineData("testUser", null, null, true)] + [InlineData(null, "pass123", "pass123", false)] + public void ToSetupCommand_WhenMappingRequestWithSpecificValues_ShouldMapCorrectly( + string? username, + string? password, + string? passwordConfirm, + bool use2fa) + { + // Arrange + RegistrationRequest request = new(username, password, passwordConfirm, use2fa); + + // Act + SetupApplicationCommand result = request.ToSetupCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(username); + result.Password.Should().Be(password); + result.PasswordConfirm.Should().Be(passwordConfirm); + result.Use2fa.Should().Be(use2fa); + } + + [Theory] + [InlineData("user1", "pass123", "pass123", true)] + [InlineData("", "", "", false)] + [InlineData("testUser", null, null, true)] + [InlineData(null, "pass123", "pass123", false)] + public void ToCommand_WhenMappingRequestWithSpecificValues_ShouldMapCorrectly( + string? username, + string? password, + string? passwordConfirm, + bool use2fa) + { + // Arrange + RegistrationRequest request = new(username, password, passwordConfirm, use2fa); + + // Act + RegisterUserCommand result = request.ToCommand(); + + // Assert + result.Should().NotBeNull(); + result.Username.Should().Be(username); + result.Password.Should().Be(password); + result.PasswordConfirm.Should().Be(passwordConfirm); + result.Use2fa.Should().Be(use2fa); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/Fixtures/UserEntityFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/Fixtures/UserEntityFixture.cs new file mode 100644 index 00000000..7b999cf2 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/Fixtures/UserEntityFixture.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Domain.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class UserEntityFixture +{ + /// + /// Creates a random valid user entity. + /// + /// Number of libraries to generate. Default is 0. + /// The created user entity. + public static UserEntity CreateUserEntity(int libraryCount = 0) + { + Guid userId = Guid.NewGuid(); + List libraries = [.. new Faker() + .CustomInstantiator(f => new LibraryEntity + { + Id = Guid.NewGuid(), + UserId = userId, + Title = f.Commerce.ProductName(), + LibraryType = f.PickRandom(), + ContentLocations = [], + Created = f.Date.Past(), + Updated = null + }) + .Generate(libraryCount)]; + + return new Faker() + .CustomInstantiator(f => new UserEntity + { + Id = userId, + Username = default!, + Password = default!, + Created = default, + TotpSecret = default, + Libraries = libraries + }) + .RuleFor(x => x.Username, f => f.Internet.UserName()) + .RuleFor(x => x.Password, f => Uri.EscapeDataString(f.Internet.Password())) + .RuleFor(x => x.Created, f => f.Date.Past()) + .RuleFor(x => x.TotpSecret, f => f.Random.Bool() ? f.Random.String2(32) : null) + .Generate(); + } + + /// + /// Creates a list of user entities. + /// + /// The number of entities to create. + /// The created list. + public static List CreateMany(int count = 3) + { + return Enumerable.Range(0, count) + .Select(_ => CreateUserEntity()) + .ToList(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserEntityMappingTests.cs index fa4785c7..c9a5e2c2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserEntityMappingTests.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; using Lumina.Application.Common.Mapping.UsersManagement.Users; +using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; using Lumina.Contracts.Responses.UsersManagement.Users; using Lumina.Domain.Common.Enums.MediaLibrary; using System; @@ -18,19 +19,21 @@ namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users; [ExcludeFromCodeCoverage] public class UserEntityMappingTests { + private readonly UserEntityFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public UserEntityMappingTests() + { + _fixture = new UserEntityFixture(); + } + [Fact] public void ToResponse_WhenMappingValidUserEntity_ShouldMapCorrectly() { // Arrange - UserEntity entity = new() - { - Id = Guid.NewGuid(), - Username = "testuser", - Password = "hashedpassword", - Libraries = [], - Created = DateTime.UtcNow, - Updated = null - }; + UserEntity entity = UserEntityFixture.CreateUserEntity(); // Act UserResponse result = entity.ToResponse(); @@ -51,15 +54,8 @@ public class UserEntityMappingTests public void ToResponse_WhenMappingDifferentUsernames_ShouldMapCorrectly(string username) { // Arrange - UserEntity entity = new() - { - Id = Guid.NewGuid(), - Username = username, - Password = "hashedpassword", - Libraries = [], - Created = DateTime.UtcNow, - Updated = null - }; + UserEntity entity = UserEntityFixture.CreateUserEntity(); + entity.Username = username; // Act UserResponse result = entity.ToResponse(); @@ -73,60 +69,22 @@ public class UserEntityMappingTests public void ToResponse_WhenMappingWithUpdatedDateTime_ShouldMapCorrectly() { // Arrange - DateTime updated = DateTime.UtcNow.AddDays(-1); - UserEntity entity = new() - { - Id = Guid.NewGuid(), - Username = "testuser", - Password = "hashedpassword", - Libraries = [], - Created = DateTime.UtcNow, - Updated = updated - }; + UserEntity entity = UserEntityFixture.CreateUserEntity(); + entity.Updated = DateTime.UtcNow.AddDays(-1); // Act UserResponse result = entity.ToResponse(); // Assert result.Should().NotBeNull(); - result.Updated.Should().Be(updated); + result.Updated.Should().Be(entity.Updated); } [Fact] public void ToResponse_WhenMappingWithLibraries_ShouldNotAffectMapping() { // Arrange - UserEntity entity = new() - { - Id = Guid.NewGuid(), - Username = "testuser", - Password = "hashedpassword", - Libraries = - [ - new() - { - Id = Guid.NewGuid(), - UserId = Guid.NewGuid(), - Title = "Library 1", - LibraryType = LibraryType.Book, - ContentLocations = [], - Created = DateTime.UtcNow, - Updated = null - }, - new() - { - Id = Guid.NewGuid(), - UserId = Guid.NewGuid(), - Title = "Library 2", - LibraryType = LibraryType.Movie, - ContentLocations = [], - Created = DateTime.UtcNow, - Updated = null - } - ], - Created = DateTime.UtcNow, - Updated = null - }; + UserEntity entity = UserEntityFixture.CreateUserEntity(2); // Act UserResponse result = entity.ToResponse(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs index 3ee980e4..c3db6f95 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs @@ -20,7 +20,6 @@ using System.Threading.Tasks; namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles; - /// /// Contains unit tests for the class. /// diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/Fixtures/SetupApplicationCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/Fixtures/SetupApplicationCommandFixture.cs similarity index 75% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/Fixtures/SetupApplicationCommandFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/Fixtures/SetupApplicationCommandFixture.cs index 2a5f1892..c4449632 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/Fixtures/SetupApplicationCommandFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/Fixtures/SetupApplicationCommandFixture.cs @@ -1,10 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.Fixtures; +namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures; /// /// Fixture class for the class. @@ -16,7 +16,7 @@ public class SetupApplicationCommandFixture /// Creates a random valid command for the application setup. /// /// The created command. - public static SetupApplicationCommand CreateSetupApplicationCommand() + public SetupApplicationCommand CreateSetupApplicationCommand() { string password = "Abcd123$"; return new Faker() @@ -26,8 +26,10 @@ public class SetupApplicationCommandFixture default!, true )) - .RuleFor(x => x.Username, f => f.Person.UserName) + .RuleFor(x => x.Username, f => f.Internet.UserName()) .RuleFor(x => x.Password, password) - .RuleFor(x => x.PasswordConfirm, password); + .RuleFor(x => x.PasswordConfirm, password) + .RuleFor(x => x.Use2fa, f => f.Random.Bool()) + .Generate(); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs new file mode 100644 index 00000000..276d67b1 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs @@ -0,0 +1,194 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Security; +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.Contracts.Responses.Authentication; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetupApplicationCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IHashService _mockHashService; + private readonly ICryptographyService _mockCryptographyService; + private readonly ITotpTokenGenerator _mockTotpTokenGenerator; + private readonly IQRCodeGenerator _mockQRCodeGenerator; + private readonly IUserRepository _mockUserRepository; + private readonly SetupApplicationCommandHandler _sut; + private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture; + + /// + /// Initializes a new instance of the class. + /// + public SetupApplicationCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockHashService = Substitute.For(); + _mockCryptographyService = Substitute.For(); + _mockTotpTokenGenerator = Substitute.For(); + _mockQRCodeGenerator = Substitute.For(); + _mockUserRepository = Substitute.For(); + _setupApplicationCommandFixture = new SetupApplicationCommandFixture(); + + _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + + _sut = new SetupApplicationCommandHandler( + _mockUnitOfWork, + _mockHashService, + _mockCryptographyService, + _mockTotpTokenGenerator, + _mockQRCodeGenerator); + } + + [Fact] + public async Task Handle_WhenNoExistingUsers_ShouldCreateAdminUserWithout2FA() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand() with { Use2fa = false }; + string hashedPassword = Uri.EscapeDataString("hashedPassword"); + + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + _mockHashService.HashString(command.Password!) + .Returns(hashedPassword); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Username.Should().Be(command.Username); + result.Value.TotpSecret.Should().BeNull(); + + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenNoExistingUsersAndWith2FA_ShouldCreateAdminUserWithTOTP() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand() with { Use2fa = true }; + string hashedPassword = Uri.EscapeDataString("hashedPassword"); + byte[] totpSecret = [1, 2, 3]; + string qrCodeUri = "data:image/png;base64,test"; + string encryptedSecret = "encryptedSecret"; + + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + _mockHashService.HashString(command.Password!) + .Returns(hashedPassword); + _mockTotpTokenGenerator.GenerateSecret() + .Returns(totpSecret); + _mockQRCodeGenerator.GenerateQrCodeDataUri(command.Username!, totpSecret) + .Returns(qrCodeUri); + _mockCryptographyService.Encrypt(Arg.Any()) + .Returns(encryptedSecret); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Username.Should().Be(command.Username); + result.Value.TotpSecret.Should().Be(qrCodeUri); + + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUserAlreadyExists_ShouldReturnError() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); + UserEntity existingUser = UserEntityFixture.CreateUserEntity(); + + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(new[] { existingUser }); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authorization.AdminAccountAlreadyCreated); + + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenGetAllUsersReturnsError_ShouldReturnError() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); + Error error = Error.Failure("Database.Error", "Failed to retrieve users"); + + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenInsertUserReturnsError_ShouldReturnError() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand(); + Error error = Error.Failure("Database.Error", "Failed to insert user"); + + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs similarity index 82% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs index be30ec52..d0752370 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplicationCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandValidatorTests.cs @@ -1,14 +1,12 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation.TestHelper; -using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath; -using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures; -using Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.Fixtures; using Lumina.Application.Common.Errors; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands; +namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; /// /// Contains unit tests for the class. @@ -17,6 +15,7 @@ namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Command public class SetupApplicationCommandValidatorTests { private readonly SetupApplicationCommandValidator _validator; + private readonly SetupApplicationCommandFixture _commandFixture; /// /// Initializes a new instance of the class. @@ -24,14 +23,15 @@ public class SetupApplicationCommandValidatorTests public SetupApplicationCommandValidatorTests() { _validator = new SetupApplicationCommandValidator(); + _commandFixture = new SetupApplicationCommandFixture(); } [Fact] public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand(); - command = command with { Username = null! }; + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); + command = command with { Username = null }; // Act TestValidationResult result = _validator.TestValidate(command); @@ -45,7 +45,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); command = command with { Username = string.Empty }; // Act @@ -60,7 +60,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); command = command with { Username = " " }; // Act @@ -75,7 +75,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordIsNull_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); command = command with { Password = null! }; // Act @@ -90,7 +90,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); command = command with { Password = string.Empty }; // Act @@ -105,7 +105,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); command = command with { Password = " " }; // Act @@ -120,7 +120,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordConfirmIsNull_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); command = command with { PasswordConfirm = null! }; // Act @@ -135,7 +135,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordConfirmIsEmpty_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); command = command with { PasswordConfirm = string.Empty }; // Act @@ -150,7 +150,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordConfirmIsWhiteSpace_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); command = command with { PasswordConfirm = " " }; // Act @@ -165,7 +165,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordAndPasswordConfirmDontMatch_ShouldHaveValidationError() { // Arrange - SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); command = command with { PasswordConfirm = "$321Bcda" }; // Act @@ -186,7 +186,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) { // Arrange - SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); command = command with { Password = password, PasswordConfirm = password }; // Act @@ -205,7 +205,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password) { // Arrange - SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); command = command with { Password = password, PasswordConfirm = password }; // Act @@ -219,7 +219,7 @@ public class SetupApplicationCommandValidatorTests public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { // Arrange - SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand(); + SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand(); command = command with { Password = "$321Bcda", PasswordConfirm = "$321Bcda" }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs new file mode 100644 index 00000000..06801841 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +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.Contracts.Responses.UsersManagement; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Queries.CheckInitiliazation; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CheckInitializationQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IUserRepository _mockUserRepository; + private readonly CheckInitializationQueryHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public CheckInitializationQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockUserRepository = Substitute.For(); + + _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + + _sut = new CheckInitializationQueryHandler(_mockUnitOfWork); + } + + [Fact] + public async Task Handle_WhenUsersExist_ShouldReturnInitialized() + { + // Arrange + List users = UserEntityFixture.CreateMany(); + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(ErrorOrFactory.From(users.AsEnumerable())); + + // Act + InitializationResponse result = await _sut.Handle(new CheckInitializationQuery(), CancellationToken.None); + + // Assert + result.IsInitialized.Should().BeTrue(); + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenNoUsersExist_ShouldReturnNotInitialized() + { + // Arrange + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + + // Act + InitializationResponse result = await _sut.Handle(new CheckInitializationQuery(), CancellationToken.None); + + // Assert + result.IsInitialized.Should().BeFalse(); + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenRepositoryReturnsError_ShouldReturnNotInitialized() + { + // Arrange + Error error = Error.Failure("Database.Error", "Failed to retrieve users"); + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(error); + + // Act + InitializationResponse result = await _sut.Handle(new CheckInitializationQuery(), CancellationToken.None); + + // Assert + result.IsInitialized.Should().BeFalse(); + await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs new file mode 100644 index 00000000..e2e7c9b2 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs @@ -0,0 +1,207 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +using Lumina.Contracts.Responses.Authentication; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IHashService _mockHashService; + private readonly IUserRepository _mockUserRepository; + private readonly ChangePasswordCommandHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockHashService = Substitute.For(); + _mockUserRepository = Substitute.For(); + + _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + + _sut = new ChangePasswordCommandHandler( + _mockUnitOfWork, + _mockHashService); + } + + [Fact] + public async Task Handle_WhenPasswordChangeIsSuccessful_ShouldUpdateUserAndReturnSuccess() + { + // Arrange + string currentPassword = "currentPassword"; + string newPassword = "newPassword"; + string hashedNewPassword = "hashedNewPassword"; + string escapedHashedCurrentPassword = Uri.EscapeDataString("hashedCurrentPassword"); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = escapedHashedCurrentPassword; + + ChangePasswordCommand command = new( + user.Username, + currentPassword, + newPassword, + newPassword); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(currentPassword, "hashedCurrentPassword") + .Returns(true); + _mockHashService.HashString(newPassword) + .Returns(hashedNewPassword); + _mockUserRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.IsPasswordChanged.Should().BeTrue(); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + _mockHashService.Received(1).CheckStringAgainstHash(currentPassword, "hashedCurrentPassword"); + _mockHashService.Received(1).HashString(newPassword); + await _mockUserRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUserDoesNotExist_ShouldReturnError() + { + // Arrange + ChangePasswordCommand command = new("nonexistentUser", "oldPass", "newPass", "newPass"); + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(ErrorOrFactory.From(null)); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.UsernameDoesNotExist); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenCurrentPasswordIsIncorrect_ShouldReturnError() + { + // Arrange + UserEntity user = UserEntityFixture.CreateUserEntity(); + string incorrectPassword = "wrongPassword"; + + ChangePasswordCommand command = new( + user.Username, + incorrectPassword, + "newPass", + "newPass"); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(incorrectPassword, Uri.UnescapeDataString(user.Password)) + .Returns(false); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidCurrentPassword); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + _mockHashService.Received(1).CheckStringAgainstHash(incorrectPassword, Uri.UnescapeDataString(user.Password)); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUpdateFails_ShouldReturnError() + { + // Arrange + string currentPassword = "currentPassword"; + string newPassword = "newPassword"; + string escapedHashedCurrentPassword = Uri.EscapeDataString("hashedCurrentPassword"); + Error error = Error.Failure("Database.Error", "Failed to update user"); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = escapedHashedCurrentPassword; + + ChangePasswordCommand command = new( + user.Username, + currentPassword, + newPassword, + newPassword); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(currentPassword, "hashedCurrentPassword") + .Returns(true); + _mockUserRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + _mockHashService.Received(1).CheckStringAgainstHash(currentPassword, "hashedCurrentPassword"); + await _mockUserRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenGetByUsernameReturnsError_ShouldReturnError() + { + // Arrange + string currentPassword = "currentPassword"; + string newPassword = "newPassword"; + UserEntity user = UserEntityFixture.CreateUserEntity(); + ChangePasswordCommand command = new( + user.Username, + currentPassword, + newPassword, + newPassword); + Error error = Error.Failure("Database.Error", "Failed to check username"); + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs new file mode 100644 index 00000000..2c272751 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandValidatorTests.cs @@ -0,0 +1,303 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Common.Errors; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordCommandValidatorTests +{ + private readonly ChangePasswordCommandValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordCommandValidatorTests() + { + _validator = new ChangePasswordCommandValidator(); + } + + [Fact] + public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { Username = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { Username = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { Username = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenCurrentPasswordIsNull_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { CurrentPassword = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.CurrentPassword) + .WithErrorMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenCurrentPasswordIsEmpty_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { CurrentPassword = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.CurrentPassword) + .WithErrorMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenCurrentPasswordIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { CurrentPassword = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.CurrentPassword) + .WithErrorMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenNewPasswordIsNull_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPassword = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPassword) + .WithErrorMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenNewPasswordIsEmpty_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPassword = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPassword) + .WithErrorMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenNewPasswordIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPassword = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPassword) + .WithErrorMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenNewPasswordConfirmIsNull_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPasswordConfirm = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPasswordConfirm) + .WithErrorMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenNewPasswordConfirmIsEmpty_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPasswordConfirm = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPasswordConfirm) + .WithErrorMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenNewPasswordConfirmIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPasswordConfirm = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPasswordConfirm) + .WithErrorMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenNewPasswordAndNewPasswordConfirmDontMatch_ShouldHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPasswordConfirm = "$321Bcda" }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPassword) + .WithErrorMessage(Errors.Authentication.PasswordsNotMatch.Description); + } + + [Theory] + [InlineData("password123")] // Missing uppercase and special character + [InlineData("PASSWORD123")] // Missing special character + [InlineData("Password123")] // Missing special character + [InlineData("Password!@#")] // Missing number + [InlineData("Pass1!")] // Too short + [InlineData("password")] // Missing uppercase, number, and special character + public void Validate_WhenCurrentPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { CurrentPassword = password }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.CurrentPassword) + .WithErrorMessage(Errors.Authentication.InvalidPassword.Description); + } + + [Theory] + [InlineData("password123")] // Missing uppercase and special character + [InlineData("PASSWORD123")] // Missing special character + [InlineData("Password123")] // Missing special character + [InlineData("Password!@#")] // Missing number + [InlineData("Pass1!")] // Too short + [InlineData("password")] // Missing uppercase, number, and special character + public void Validate_WhenNewPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with { NewPassword = password, NewPasswordConfirm = password }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPassword) + .WithErrorMessage(Errors.Authentication.InvalidPassword.Description); + } + + [Theory] + [InlineData("Password1!")] // Valid password + [InlineData("Complex1@Password")] // Valid password + [InlineData("MyP@ssw0rd")] // Valid password + [InlineData("Abcd123!@#")] // Valid password + public void Validate_WhenPasswordsMatchPattern_ShouldNotHaveValidationError(string password) + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + command = command with + { + CurrentPassword = password, + NewPassword = password, + NewPasswordConfirm = password + }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.CurrentPassword); + result.ShouldNotHaveValidationErrorFor(x => x.NewPassword); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() + { + // Arrange + ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand(); + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Username); + result.ShouldNotHaveValidationErrorFor(x => x.CurrentPassword); + result.ShouldNotHaveValidationErrorFor(x => x.NewPassword); + result.ShouldNotHaveValidationErrorFor(x => x.NewPasswordConfirm); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordCommandFixture.cs new file mode 100644 index 00000000..49ca6c5b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordCommandFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordCommandFixture +{ + /// + /// Creates a random valid command for changing a password. + /// + /// The created command. + public static ChangePasswordCommand CreateChangePasswordCommand() + { + string currentPassword = "Abcd123$"; + string newPassword = "Wxyz789#"; + return new Faker() + .CustomInstantiator(f => new ChangePasswordCommand( + default!, + default!, + default!, + default! + )) + .RuleFor(x => x.Username, f => f.Person.UserName) + .RuleFor(x => x.CurrentPassword, currentPassword) + .RuleFor(x => x.NewPassword, newPassword) + .RuleFor(x => x.NewPasswordConfirm, newPassword); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs new file mode 100644 index 00000000..28141e51 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs @@ -0,0 +1,56 @@ +#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; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordRequestFixture +{ + private readonly Faker _faker; + + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordRequestFixture() + { + _faker = new Faker(); + } + + /// + /// Creates a random valid . + /// + /// The created . + 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() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count) + .Select(_ => CreateChangePasswordRequest()) + .ToList(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordCommandFixture.cs new file mode 100644 index 00000000..ec608ab4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordCommandFixture.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordCommandFixture +{ + /// + /// Creates a random valid command for password recovery. + /// + /// The created command. + public static RecoverPasswordCommand CreateRecoverPasswordCommand() + { + return new Faker() + .CustomInstantiator(f => new RecoverPasswordCommand( + default!, + default! + )) + .RuleFor(x => x.Username, f => f.Person.UserName) + .RuleFor(x => x.TotpCode, f => f.Random.Replace("######")); // generates 6 random digits + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs new file mode 100644 index 00000000..b5d1c413 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs @@ -0,0 +1,52 @@ +#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; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordRequestFixture +{ + private readonly Faker _faker; + + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordRequestFixture() + { + _faker = new Faker(); + } + + /// + /// Creates a random valid . + /// + /// The created . + public RecoverPasswordRequest CreateRecoverPasswordRequest( + string? username = null, + string? totpCode = null) + { + return new RecoverPasswordRequest( + username ?? _faker.Internet.UserName(), + totpCode ?? _faker.Random.Number(100000, 999999).ToString() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count) + .Select(_ => CreateRecoverPasswordRequest()) + .ToList(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs new file mode 100644 index 00000000..2e54a568 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs @@ -0,0 +1,288 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +using Lumina.Contracts.Responses.Authentication; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IHashService _mockHashService; + private readonly ITotpTokenGenerator _mockTotpTokenGenerator; + private readonly ICryptographyService _mockCryptographyService; + private readonly IUserRepository _mockUserRepository; + private readonly RecoverPasswordCommandHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockHashService = Substitute.For(); + _mockTotpTokenGenerator = Substitute.For(); + _mockCryptographyService = Substitute.For(); + _mockUserRepository = Substitute.For(); + + _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + + _sut = new RecoverPasswordCommandHandler( + _mockUnitOfWork, + _mockHashService, + _mockTotpTokenGenerator, + _mockCryptographyService); + } + + [Fact] + public async Task Handle_WhenUserExistsAndTotpIsValid_ShouldResetPassword() + { + // Arrange + string totpCode = "123456"; + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 }); + string hashedTempPassword = "hashedTempPassword"; + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.TotpSecret = encryptedTotpSecret; + user.TempPassword = null; + + RecoverPasswordCommand command = new(user.Username, totpCode); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockCryptographyService.Decrypt(encryptedTotpSecret) + .Returns(decryptedTotpSecret); + _mockTotpTokenGenerator.ValidateToken(Arg.Any(), totpCode) + .Returns(true); + _mockHashService.HashString("Abcd123$") + .Returns(hashedTempPassword); + _mockUserRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.IsPasswordReset.Should().BeTrue(); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + _mockTotpTokenGenerator.Received(1).ValidateToken(Arg.Any(), totpCode); + _mockHashService.Received(1).HashString("Abcd123$"); + await _mockUserRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUserDoesNotExist_ShouldReturnError() + { + // Arrange + RecoverPasswordCommand command = new("nonexistentUser", "123456"); + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(ErrorOrFactory.From(null)); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.UsernameDoesNotExist); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenTempPasswordExists_ShouldReturnError() + { + // Arrange + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.TempPassword = "existingTempPassword"; + user.TempPasswordCreated = DateTime.UtcNow; + + RecoverPasswordCommand command = new(user.Username, "123456"); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.PasswordResetAlreadyRequested); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUserDoesNotUseTOTP_ShouldReturnError() + { + // Arrange + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.TotpSecret = null; + + RecoverPasswordCommand command = new(user.Username, "123456"); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidTotpCode); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenTotpCodeIsInvalid_ShouldReturnError() + { + // Arrange + string totpCode = "123456"; + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 }); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.TotpSecret = encryptedTotpSecret; + + RecoverPasswordCommand command = new(user.Username, totpCode); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockCryptographyService.Decrypt(encryptedTotpSecret) + .Returns(decryptedTotpSecret); + _mockTotpTokenGenerator.ValidateToken(Arg.Any(), totpCode) + .Returns(false); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidTotpCode); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + _mockTotpTokenGenerator.Received(1).ValidateToken(Arg.Any(), totpCode); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUpdateFails_ShouldReturnError() + { + // Arrange + string totpCode = "123456"; + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 }); + Error error = Error.Failure("Database.Error", "Failed to update user"); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.TotpSecret = encryptedTotpSecret; + + RecoverPasswordCommand command = new(user.Username, totpCode); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockCryptographyService.Decrypt(encryptedTotpSecret) + .Returns(decryptedTotpSecret); + _mockTotpTokenGenerator.ValidateToken(Arg.Any(), totpCode) + .Returns(true); + _mockUserRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + _mockTotpTokenGenerator.Received(1).ValidateToken(Arg.Any(), totpCode); + await _mockUserRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenGetByUsernameReturnsError_ShouldReturnError() + { + // Arrange + string totpCode = "123456"; + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.TotpSecret = encryptedTotpSecret; + + RecoverPasswordCommand command = new(user.Username, totpCode); + Error error = Error.Failure("Database.Error", "Failed to check username"); + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUserUsesTOTPButNoCodeProvided_ShouldReturnError() + { + // Arrange + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.TotpSecret = encryptedTotpSecret; + + RecoverPasswordCommand command = new(user.Username, null); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidTotpCode); + + await _mockUserRepository.Received(1).GetByUsernameAsync(user.Username, Arg.Any()); + _mockTotpTokenGenerator.DidNotReceive().ValidateToken(Arg.Any(), Arg.Any()); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs new file mode 100644 index 00000000..1459a1ac --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandValidatorTests.cs @@ -0,0 +1,168 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Common.Errors; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordCommandValidatorTests +{ + private readonly RecoverPasswordCommandValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordCommandValidatorTests() + { + _validator = new RecoverPasswordCommandValidator(); + } + + [Fact] + public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { Username = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { Username = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { Username = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenTotpCodeIsNull_ShouldHaveValidationError() + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { TotpCode = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.TotpCode) + .WithErrorMessage(Errors.Authentication.TotpCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenTotpCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { TotpCode = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.TotpCode) + .WithErrorMessage(Errors.Authentication.TotpCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenTotpCodeIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { TotpCode = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.TotpCode) + .WithErrorMessage(Errors.Authentication.TotpCannotBeEmpty.Description); + } + + [Theory] + [InlineData("12345")] // Too short + [InlineData("1234567")] // Too long + [InlineData("abcdef")] // Contains letters + [InlineData("12345a")] // Contains letters + [InlineData("12.345")] // Contains special characters + [InlineData("12 345")] // Contains whitespace + public void Validate_WhenTotpCodeIsInvalid_ShouldHaveValidationError(string totpCode) + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { TotpCode = totpCode }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.TotpCode) + .WithErrorMessage(Errors.Authentication.InvalidTotpCode.Description); + } + + [Theory] + [InlineData("123456")] + [InlineData("000000")] + [InlineData("999999")] + public void Validate_WhenTotpCodeIsValid_ShouldNotHaveValidationError(string totpCode) + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + command = command with { TotpCode = totpCode }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.TotpCode); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() + { + // Arrange + RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand(); + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Username); + result.ShouldNotHaveValidationErrorFor(x => x.TotpCode); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/Fixture/RegisterCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegisterUserCommandFixture.cs similarity index 88% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/Fixture/RegisterCommandFixture.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegisterUserCommandFixture.cs index d1044068..8f8f7aba 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/Fixture/RegisterCommandFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegisterUserCommandFixture.cs @@ -4,13 +4,13 @@ using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUs using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.UsersManagement.Register.Fixture; +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; /// /// Fixture class for the class. /// [ExcludeFromCodeCoverage] -public class RegisterCommandFixture +public class RegisterUserCommandFixture { /// /// Creates a random valid command for a new account registration. diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegistrationRequestFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegistrationRequestFixture.cs new file mode 100644 index 00000000..daa0679f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/Fixture/RegistrationRequestFixture.cs @@ -0,0 +1,58 @@ +#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; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class RegistrationRequestFixture +{ + private readonly Faker _faker; + + /// + /// Initializes a new instance of the class. + /// + public RegistrationRequestFixture() + { + _faker = new Faker(); + } + + /// + /// Creates a random valid . + /// + /// The created . + 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() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count) + .Select(_ => CreateRegistrationRequest()) + .ToList(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs new file mode 100644 index 00000000..f3c42fb8 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs @@ -0,0 +1,197 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Security; +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.Contracts.Responses.Authentication; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterUserCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IHashService _mockHashService; + private readonly ICryptographyService _mockCryptographyService; + private readonly ITotpTokenGenerator _mockTotpTokenGenerator; + private readonly IQRCodeGenerator _mockQRCodeGenerator; + private readonly IUserRepository _mockUserRepository; + private readonly RegisterUserCommandHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public RegisterUserCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockHashService = Substitute.For(); + _mockCryptographyService = Substitute.For(); + _mockTotpTokenGenerator = Substitute.For(); + _mockQRCodeGenerator = Substitute.For(); + _mockUserRepository = Substitute.For(); + + _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + + _sut = new RegisterUserCommandHandler( + _mockUnitOfWork, + _mockHashService, + _mockCryptographyService, + _mockTotpTokenGenerator, + _mockQRCodeGenerator); + } + + [Fact] + public async Task Handle_WhenUserDoesNotExistAndWith2FA_ShouldRegisterUser() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + byte[] totpSecret = [1, 2, 3]; + string qrCodeUri = "data:image/png;base64,test"; + string encryptedSecret = "encryptedSecret"; + string hashedPassword = "hashedPassword"; + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(ErrorOrFactory.From(null)); + _mockHashService.HashString(command.Password!) + .Returns(hashedPassword); + _mockTotpTokenGenerator.GenerateSecret() + .Returns(totpSecret); + _mockQRCodeGenerator.GenerateQrCodeDataUri(command.Username!, totpSecret) + .Returns(qrCodeUri); + _mockCryptographyService.Encrypt(Convert.ToBase64String(totpSecret)) + .Returns(encryptedSecret); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Username.Should().Be(command.Username); + result.Value.TotpSecret.Should().Be(qrCodeUri); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + _mockHashService.Received(1).HashString(command.Password!); + _mockTotpTokenGenerator.Received(1).GenerateSecret(); + _mockQRCodeGenerator.Received(1).GenerateQrCodeDataUri(command.Username!, totpSecret); + _mockCryptographyService.Received(1).Encrypt(Convert.ToBase64String(totpSecret)); + await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUserDoesNotExistAndWithout2FA_ShouldRegisterUser() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand() with { Use2fa = false }; + string hashedPassword = "hashedPassword"; + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(ErrorOrFactory.From(null)); + _mockHashService.HashString(command.Password!) + .Returns(hashedPassword); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Username.Should().Be(command.Username); + result.Value.TotpSecret.Should().BeNull(); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + _mockHashService.Received(1).HashString(command.Password!); + _mockTotpTokenGenerator.DidNotReceive().GenerateSecret(); + _mockQRCodeGenerator.DidNotReceive().GenerateQrCodeDataUri(Arg.Any(), Arg.Any()); + _mockCryptographyService.DidNotReceive().Encrypt(Arg.Any()); + await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenUserAlreadyExists_ShouldReturnError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + UserEntity existingUser = UserEntityFixture.CreateUserEntity(); + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(ErrorOrFactory.From(existingUser)); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.UsernameAlreadyExists); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenInsertFails_ShouldReturnError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + Error error = Error.Failure("Database.Error", "Failed to insert user"); + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(ErrorOrFactory.From(null)); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenGetByUsernameReturnsError_ShouldReturnError() + { + // Arrange + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); + Error error = Error.Failure("Database.Error", "Failed to check username"); + + _mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + + await _mockUserRepository.Received(1).GetByUsernameAsync(command.Username!, Arg.Any()); + await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/RegisterCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs similarity index 82% rename from tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/RegisterCommandValidatorTests.cs rename to tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs index 7c262421..e39d0c41 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Register/RegisterCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandValidatorTests.cs @@ -2,24 +2,24 @@ using FluentValidation.TestHelper; using Lumina.Application.Common.Errors; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; -using Lumina.Application.UnitTests.Core.UsersManagement.Register.Fixture; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Application.UnitTests.Core.UsersManagement.Register; +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser; /// /// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] -public class RegisterCommandValidatorTests +public class RegisterUserCommandValidatorTests { private readonly RegisterUserCommandValidator _validator; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public RegisterCommandValidatorTests() + public RegisterUserCommandValidatorTests() { _validator = new RegisterUserCommandValidator(); } @@ -28,7 +28,7 @@ public class RegisterCommandValidatorTests public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); command = command with { Username = null! }; // Act @@ -43,7 +43,7 @@ public class RegisterCommandValidatorTests public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); command = command with { Username = string.Empty }; // Act @@ -58,7 +58,7 @@ public class RegisterCommandValidatorTests public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); command = command with { Username = " " }; // Act @@ -73,7 +73,7 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordIsNull_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); command = command with { Password = null! }; // Act @@ -88,7 +88,7 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); command = command with { Password = string.Empty }; // Act @@ -103,7 +103,7 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); command = command with { Password = " " }; // Act @@ -118,7 +118,7 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordConfirmIsNull_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); command = command with { PasswordConfirm = null! }; // Act @@ -133,7 +133,7 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordConfirmIsEmpty_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); command = command with { PasswordConfirm = string.Empty }; // Act @@ -148,7 +148,7 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordConfirmIsWhiteSpace_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); command = command with { PasswordConfirm = " " }; // Act @@ -163,7 +163,7 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordAndPasswordConfirmDontMatch_ShouldHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); command = command with { PasswordConfirm = "$321Bcda" }; // Act @@ -184,7 +184,7 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) { // Arrange - RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); command = command with { Password = password, PasswordConfirm = password }; // Act @@ -203,7 +203,7 @@ public class RegisterCommandValidatorTests public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password) { // Arrange - RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); command = command with { Password = password, PasswordConfirm = password }; // Act @@ -217,7 +217,7 @@ public class RegisterCommandValidatorTests public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { // Arrange - RegisterUserCommand command = RegisterCommandFixture.CreateRegisterCommand(); + RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand(); command = command with { Password = "$321Bcda", PasswordConfirm = "$321Bcda" }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginRequestFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginRequestFixture.cs new file mode 100644 index 00000000..2d46f9cb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginRequestFixture.cs @@ -0,0 +1,54 @@ +#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; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginRequestFixture +{ + private readonly Faker _faker; + + /// + /// Initializes a new instance of the class. + /// + public LoginRequestFixture() + { + _faker = new Faker(); + } + + /// + /// Creates a random valid . + /// + /// The created . + 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() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count) + .Select(_ => CreateLoginRequest()) + .ToList(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginUserQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginUserQueryFixture.cs new file mode 100644 index 00000000..c3773353 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/Fixtures/LoginUserQueryFixture.cs @@ -0,0 +1,36 @@ +#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; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginUserQueryFixture +{ + /// + /// Creates a random valid query for user login. + /// + /// Whether to include a TOTP code in the query. + /// The created query. + public static LoginUserQuery CreateLoginQuery(bool includeTotpCode = false) + { + string password = "Abcd123$"; + Faker faker = new Faker() + .CustomInstantiator(f => new LoginUserQuery( + default!, + default!, + default + )) + .RuleFor(x => x.Username, f => f.Person.UserName) + .RuleFor(x => x.Password, password); + + if (includeTotpCode) + faker.RuleFor(x => x.TotpCode, f => f.Random.Replace("######")); // generates 6 random digits + return faker; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs new file mode 100644 index 00000000..27df63bb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs @@ -0,0 +1,357 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; +using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures; +using Lumina.Contracts.Responses.Authentication; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginUserQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IHashService _mockHashService; + private readonly IJwtTokenGenerator _mockJwtTokenGenerator; + private readonly ITotpTokenGenerator _mockTotpTokenGenerator; + private readonly ICryptographyService _mockCryptographyService; + private readonly IUserRepository _mockUserRepository; + private readonly LoginUserQueryHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public LoginUserQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockHashService = Substitute.For(); + _mockJwtTokenGenerator = Substitute.For(); + _mockTotpTokenGenerator = Substitute.For(); + _mockCryptographyService = Substitute.For(); + _mockUserRepository = Substitute.For(); + + _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + + _sut = new LoginUserQueryHandler( + _mockUnitOfWork, + _mockHashService, + _mockJwtTokenGenerator, + _mockTotpTokenGenerator, + _mockCryptographyService); + } + + [Fact] + public async Task Handle_WhenValidCredentialsWithoutTOTP_ShouldReturnLoginResponse() + { + // Arrange + string password = "password123"; + string hashedPassword = "hashedPassword"; + string jwtToken = "jwtToken"; + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TotpSecret = null; + + LoginUserQuery query = new(user.Username, password); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(true); + _mockJwtTokenGenerator.GenerateToken(user.Id.ToString(), user.Username) + .Returns(jwtToken); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Id.Should().Be(user.Id); + result.Value.Username.Should().Be(user.Username); + result.Value.Token.Should().Be(jwtToken); + result.Value.UsesTotp.Should().BeFalse(); + } + + [Fact] + public async Task Handle_WhenValidCredentialsWithTOTP_ShouldReturnLoginResponse() + { + // Arrange + string password = "password123"; + string hashedPassword = "hashedPassword"; + string jwtToken = "jwtToken"; + string totpCode = "123456"; + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 }); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TotpSecret = encryptedTotpSecret; + + LoginUserQuery query = new(user.Username, password, totpCode); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(true); + _mockJwtTokenGenerator.GenerateToken(user.Id.ToString(), user.Username) + .Returns(jwtToken); + _mockCryptographyService.Decrypt(encryptedTotpSecret) + .Returns(decryptedTotpSecret); + _mockTotpTokenGenerator.ValidateToken(Arg.Any(), totpCode) + .Returns(true); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Id.Should().Be(user.Id); + result.Value.Username.Should().Be(user.Username); + result.Value.Token.Should().Be(jwtToken); + result.Value.UsesTotp.Should().BeTrue(); + } + + [Fact] + public async Task Handle_WhenUserDoesNotExist_ShouldReturnError() + { + // Arrange + LoginUserQuery query = new("nonexistentUser", "password"); + + _mockUserRepository.GetByUsernameAsync(query.Username!, Arg.Any()) + .Returns(ErrorOrFactory.From(null)); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidUsernameOrPassword); + } + + [Fact] + public async Task Handle_WhenPasswordIsIncorrect_ShouldReturnError() + { + // Arrange + string password = "wrongPassword"; + string hashedPassword = "hashedPassword"; + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TempPassword = null; + + LoginUserQuery query = new(user.Username, password); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(false); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidUsernameOrPassword); + } + + [Fact] + public async Task Handle_WhenTempPasswordIsExpired_ShouldReturnError() + { + // Arrange + string password = "tempPassword"; + string hashedPassword = "hashedPassword"; + string hashedTempPassword = "hashedTempPassword"; + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TempPassword = Uri.EscapeDataString(hashedTempPassword); + user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16); // Expired (more than 15 minutes old) + + LoginUserQuery query = new(user.Username, password); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(false); + _mockHashService.CheckStringAgainstHash(password, hashedTempPassword) + .Returns(true); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.TempPasswordExpired); + + await _mockUserRepository.Received(1).UpdateAsync(Arg.Is(u => + u.TempPassword == null && u.TempPasswordCreated == null), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenValidTempPassword_ShouldReturnLoginResponse() + { + // Arrange + string password = "tempPassword"; + string hashedPassword = "hashedPassword"; + string hashedTempPassword = "hashedTempPassword"; + string jwtToken = "jwtToken"; + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TempPassword = Uri.EscapeDataString(hashedTempPassword); + // Set temp password created time to 10 minutes ago (still valid) + user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-10); + user.TotpSecret = null; // Ensure no TOTP validation is needed + + LoginUserQuery query = new(user.Username, password); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(false); // Regular password check fails + _mockHashService.CheckStringAgainstHash(password, hashedTempPassword) + .Returns(true); // Temp password check succeeds + _mockJwtTokenGenerator.GenerateToken(user.Id.ToString(), user.Username) + .Returns(jwtToken); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Id.Should().Be(user.Id); + result.Value.Username.Should().Be(user.Username); + result.Value.Token.Should().Be(jwtToken); + result.Value.UsesTotp.Should().BeFalse(); + } + + [Fact] + public async Task Handle_WhenUserHasTOTPButNoCodeProvided_ShouldReturnError() + { + // Arrange + string password = "password123"; + string hashedPassword = "hashedPassword"; + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TotpSecret = encryptedTotpSecret; + + LoginUserQuery query = new(user.Username, password); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(true); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidTotpCode); + } + + [Fact] + public async Task Handle_WhenTOTPCodeIsInvalid_ShouldReturnError() + { + // Arrange + string password = "password123"; + string hashedPassword = "hashedPassword"; + string totpCode = "123456"; + string encryptedTotpSecret = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + string decryptedTotpSecret = Convert.ToBase64String(new byte[] { 4, 5, 6 }); + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TotpSecret = encryptedTotpSecret; + + LoginUserQuery query = new(user.Username, password, totpCode); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(true); + _mockCryptographyService.Decrypt(encryptedTotpSecret) + .Returns(decryptedTotpSecret); + _mockTotpTokenGenerator.ValidateToken(Arg.Any(), totpCode) + .Returns(false); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidTotpCode); + } + + [Fact] + public async Task Handle_WhenGetByUsernameReturnsError_ShouldReturnError() + { + // Arrange + LoginUserQuery query = new("username", "password"); + Error error = Error.Failure("Database.Error", "Failed to retrieve user"); + + _mockUserRepository.GetByUsernameAsync(query.Username!, Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + } + + [Fact] + public async Task Handle_WhenBothRegularAndTempPasswordsAreIncorrect_ShouldReturnError() + { + // Arrange + string password = "wrongPassword"; + string hashedPassword = "hashedPassword"; + string hashedTempPassword = "hashedTempPassword"; + + UserEntity user = UserEntityFixture.CreateUserEntity(); + user.Password = Uri.EscapeDataString(hashedPassword); + user.TempPassword = Uri.EscapeDataString(hashedTempPassword); + user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-10); // Valid timeframe + + LoginUserQuery query = new(user.Username, password); + + _mockUserRepository.GetByUsernameAsync(user.Username, Arg.Any()) + .Returns(ErrorOrFactory.From(user)); + _mockHashService.CheckStringAgainstHash(password, hashedPassword) + .Returns(false); // Regular password check fails + _mockHashService.CheckStringAgainstHash(password, hashedTempPassword) + .Returns(false); // Temp password check also fails + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Authentication.InvalidUsernameOrPassword); + + _mockHashService.Received(1).CheckStringAgainstHash(password, hashedPassword); + _mockHashService.Received(1).CheckStringAgainstHash(password, hashedTempPassword); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs new file mode 100644 index 00000000..3bae7a22 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryValidatorTests.cs @@ -0,0 +1,222 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Common.Errors; +using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; +using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginUserQueryValidatorTests +{ + private readonly LoginUserQueryValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + public LoginUserQueryValidatorTests() + { + _validator = new LoginUserQueryValidator(); + } + + [Fact] + public void Validate_WhenUsernameIsNull_ShouldHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Username = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Username = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Username = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Username) + .WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordIsNull_ShouldHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Password = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Password = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + } + + [Fact] + public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Password = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description); + } + + [Theory] + [InlineData("password123")] // Missing uppercase and special character + [InlineData("PASSWORD123")] // Missing special character + [InlineData("Password123")] // Missing special character + [InlineData("Password!@#")] // Missing number + [InlineData("Pass1!")] // Too short + [InlineData("password")] // Missing uppercase, number, and special character + public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password) + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Password = password }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Password) + .WithErrorMessage(Errors.Authentication.InvalidPassword.Description); + } + + [Theory] + [InlineData("Password1!")] // Valid password + [InlineData("Complex1@Password")] // Valid password + [InlineData("MyP@ssw0rd")] // Valid password + [InlineData("Abcd123!@#")] // Valid password + public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password) + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { Password = password }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Password); + } + + [Theory] + [InlineData("12345")] // Too short + [InlineData("1234567")] // Too long + [InlineData("abcdef")] // Contains letters + [InlineData("12345a")] // Contains letters + [InlineData("12.345")] // Contains special characters + [InlineData("12 345")] // Contains whitespace + public void Validate_WhenTotpCodeIsInvalid_ShouldHaveValidationError(string totpCode) + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { TotpCode = totpCode }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.TotpCode) + .WithErrorMessage(Errors.Authentication.InvalidTotpCode.Description); + } + + [Theory] + [InlineData("123456")] + [InlineData("000000")] + [InlineData("999999")] + public void Validate_WhenTotpCodeIsValid_ShouldNotHaveValidationError(string totpCode) + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { TotpCode = totpCode }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.TotpCode); + } + + [Fact] + public void Validate_WhenTotpCodeIsNull_ShouldNotHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(); + query = query with { TotpCode = null }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.TotpCode); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError() + { + // Arrange + LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(true); + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Username); + result.ShouldNotHaveValidationErrorFor(x => x.Password); + result.ShouldNotHaveValidationErrorFor(x => x.TotpCode); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs index 4936bdda..4a2c2588 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -28,7 +28,7 @@ public class BookRepositoryTests { private readonly LuminaDbContext _mockContext; private readonly BookRepository _sut; - private readonly BookModelFixture _bookModelFixture; + private readonly BookEntityFixture _bookEntityFixture; /// /// Initializes a new instance of the class. @@ -37,14 +37,14 @@ public class BookRepositoryTests { _mockContext = Create.MockedDbContextFor(); _sut = new BookRepository(_mockContext); - _bookModelFixture = new BookModelFixture(); + _bookEntityFixture = new BookEntityFixture(); } [Fact] public async Task InsertAsync_WhenBookDoesNotExist_ShouldAddBookToContextAndReturnCreated() { // Arrange - BookEntity bookModel = _bookModelFixture.CreateBookModel(); + BookEntity bookModel = _bookEntityFixture.CreateBookModel(); // Act ErrorOr result = await _sut.InsertAsync(bookModel, CancellationToken.None); @@ -63,7 +63,7 @@ public class BookRepositoryTests public async Task InsertAsync_WhenBookAlreadyExists_ShouldReturnError() { // Arrange - BookEntity bookModel = _bookModelFixture.CreateBookModel(); + BookEntity bookModel = _bookEntityFixture.CreateBookModel(); _mockContext.Books.Add(bookModel); await _mockContext.SaveChangesAsync(); @@ -85,7 +85,7 @@ public class BookRepositoryTests _mockContext.Set().Add(existingTag); await _mockContext.SaveChangesAsync(); - BookEntity bookModel = _bookModelFixture.CreateBookModel(); + BookEntity bookModel = _bookEntityFixture.CreateBookModel(); bookModel.Tags = [new("Existing"), new("New")]; // Act @@ -112,7 +112,7 @@ public class BookRepositoryTests _mockContext.Set().Add(existingGenre); await _mockContext.SaveChangesAsync(); - BookEntity bookModel = _bookModelFixture.CreateBookModel(); + BookEntity bookModel = _bookEntityFixture.CreateBookModel(); bookModel.Genres = [new("Existing"), new("New")]; // Act @@ -137,9 +137,9 @@ public class BookRepositoryTests // Arrange List books = [ - _bookModelFixture.CreateBookModel(), - _bookModelFixture.CreateBookModel(), - _bookModelFixture.CreateBookModel() + _bookEntityFixture.CreateBookModel(), + _bookEntityFixture.CreateBookModel(), + _bookEntityFixture.CreateBookModel() ]; _mockContext.Books.AddRange(books); await _mockContext.SaveChangesAsync(); @@ -170,7 +170,7 @@ public class BookRepositoryTests public async Task GetAllAsync_WhenCalled_ShouldIncludeRelatedEntities() { // Arrange - BookEntity book = _bookModelFixture.CreateBookModel(); + BookEntity book = _bookEntityFixture.CreateBookModel(); book.Tags = [new TagEntity("Tag1"), new TagEntity("Tag2")]; book.Genres = [new GenreEntity("Genre1"), new GenreEntity("Genre2")]; book.ISBNs = [new IsbnEntity("1234567890", IsbnFormat.Isbn10), new IsbnEntity("1234567890123", IsbnFormat.Isbn13)]; diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookEntityFixture.cs similarity index 77% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs rename to tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookEntityFixture.cs index 33833fc9..29dc1e0b 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookModelFixture.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookEntityFixture.cs @@ -19,16 +19,16 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures; /// Fixture class for the class. /// [ExcludeFromCodeCoverage] -public class BookModelFixture +public class BookEntityFixture { private readonly Fixture _fixture; private readonly Random _random = new(); private readonly Faker _faker; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public BookModelFixture() + public BookEntityFixture() { _fixture = new Fixture(); _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); @@ -38,9 +38,9 @@ public class BookModelFixture } /// - /// Creates a random valid BookModel. + /// Creates a random valid . /// - /// The created BookModel. + /// The created . public BookEntity CreateBookModel() { int releaseYear = _random.Next(2000, 2010); @@ -86,6 +86,11 @@ public class BookModelFixture .Generate(); } + /// + /// Creates a list of tag entities with random data. + /// + /// The number of tags to create. + /// A list of randomly generated tag entities. private static List CreateTags(int count) { return new Faker() @@ -93,6 +98,11 @@ public class BookModelFixture .Generate(count); } + /// + /// Creates a list of genre entities with random data. + /// + /// The number of genres to create. + /// A list of randomly generated genre entities. private static List CreateGenres(int count) { return new Faker() @@ -100,6 +110,11 @@ public class BookModelFixture .Generate(count); } + /// + /// Creates a valid Library of Congress Control Number (LCCN). + /// + /// The Faker instance used for generating random data. + /// A properly formatted LCCN string. private string CreateLCCN(Faker f) { string letters = new(Enumerable.Range(0, f.Random.Number(0, 3)) @@ -109,6 +124,11 @@ public class BookModelFixture return letters + digits; } + /// + /// Creates a valid OCLC (Online Computer Library Center) number. + /// + /// The Faker instance used for generating random data. + /// A properly formatted OCLC number string with valid prefix. private string CreateOCLCNumber(Faker f) { string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"]; @@ -124,6 +144,11 @@ public class BookModelFixture return prefix + number; } + /// + /// Creates a valid Open Library ID. + /// + /// The Faker instance used for generating random data. + /// A properly formatted Open Library ID string. private string CreateOpenLibraryId(Faker f) { int firstDigit = f.Random.Number(1, 9); @@ -132,6 +157,11 @@ public class BookModelFixture return $"OL{firstDigit}{remainingDigits}{suffix}"; } + /// + /// Creates a valid Google Books ID. + /// + /// The Faker instance used for generating random data. + /// A properly formatted Google Books ID string. private string CreateGoogleBooksId(Faker f) { const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; @@ -140,6 +170,11 @@ public class BookModelFixture .ToArray()); } + /// + /// Creates a list of ISBN entities with random data. + /// + /// The number of ISBNs to create. + /// A list of randomly generated ISBN entities. private static List CreateIsbns(int count) { return new Faker() @@ -147,6 +182,11 @@ public class BookModelFixture .Generate(count); } + /// + /// Creates a valid ISBN (International Standard Book Number). + /// + /// The Faker instance used for generating random data. + /// A properly formatted ISBN-10 or ISBN-13 string with valid checksum. private static string CreateIsbn(Faker f) { bool isIsbn13 = f.Random.Bool(); @@ -177,6 +217,11 @@ public class BookModelFixture } } + // + /// Creates a list of book rating entities with random data. + /// + /// The number of ratings to create. + /// A list of randomly generated book rating entities. private static List CreateBookRatings(int count) { return new Faker() @@ -189,6 +234,9 @@ public class BookModelFixture .Generate(count); } + /// + /// Configures custom type generation rules for the AutoFixture instance. + /// private void ConfigureCustomTypes() { _fixture.Register(() => new TagEntity(_fixture.Create())); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/Fixtures/UserEntityFixture.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/Fixtures/UserEntityFixture.cs new file mode 100644 index 00000000..e2c5e194 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/Fixtures/UserEntityFixture.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Domain.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Users.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class UserEntityFixture +{ + private readonly Fixture _fixture; + private readonly Faker _faker; + + /// + /// Initializes a new instance of the class. + /// + public UserEntityFixture() + { + _fixture = new Fixture(); + _faker = new Faker(); + ConfigureCustomTypes(); + } + + /// + /// Creates a random valid . + /// + /// The created . + public UserEntity CreateUserModel() + { + Guid userId = _faker.Random.Guid(); + + return new Faker() + .RuleFor(x => x.Id, _ => userId) + .RuleFor(x => x.Username, f => f.Internet.UserName()) + .RuleFor(x => x.Password, f => f.Internet.Password(12)) + .RuleFor(x => x.TempPassword, f => f.Random.Bool() ? f.Internet.Password(8) : null) + .RuleFor(x => x.TotpSecret, f => f.Random.Bool() ? f.Random.String2(32, "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567") : null) + .RuleFor(x => x.VerificationToken, f => f.Random.Bool() ? f.Random.Guid().ToString() : null) + .RuleFor(x => x.VerificationTokenCreated, (f, u) => u.VerificationToken != null ? f.Date.Past() : null) + .RuleFor(x => x.TempPasswordCreated, (f, u) => u.TempPassword != null ? f.Date.Past() : null) + .RuleFor(x => x.Libraries, _ => CreateLibraries(_faker.Random.Number(1, 3), userId)) + .RuleFor(x => x.Created, f => f.Date.Past()) + .RuleFor(x => x.Updated, f => f.Random.Bool() ? f.Date.Recent() : null) + .Generate(); + } + + /// + /// Creates a valid collection of user libraries. + /// + /// The number of user libraries to create. + /// The Id of the user for whom to create the libraries. + /// A collection of . + private static List CreateLibraries(int count, Guid userId) + { + return new Faker() + .CustomInstantiator(f => new LibraryEntity + { + Id = f.Random.Guid(), + UserId = userId, + Title = f.Random.String2(f.Random.Number(1, 50)), + LibraryType = f.PickRandom(), + ContentLocations = CreateContentLocations(f.Random.Number(1, 3)), + Created = f.Date.Past(), + Updated = f.Random.Bool() ? f.Date.Recent() : null + }) + .Generate(count); + } + + /// + /// Creates a valid collection of media paths for a library. + /// + /// The number of media library contents to create. + /// A collection of . + private static List CreateContentLocations(int count) + { + return new Faker() + .CustomInstantiator(f => new LibraryContentLocationEntity + { + Path = f.System.FilePath() + }) + .Generate(count); + } + + /// + /// Configures custom type generation rules for the AutoFixture instance. + /// + private void ConfigureCustomTypes() + { + _fixture.Register(() => new LibraryEntity + { + Id = _fixture.Create(), + UserId = _fixture.Create(), + Title = _fixture.Create(), + LibraryType = _fixture.Create(), + ContentLocations = new List(), + Created = _fixture.Create(), + Updated = _fixture.Create() + }); + + _fixture.Register(() => new LibraryContentLocationEntity + { + Path = _fixture.Create() + }); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs new file mode 100644 index 00000000..4a346657 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs @@ -0,0 +1,189 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.Repositories.Users; +using Lumina.DataAccess.Core.UoW; +using Lumina.DataAccess.UnitTests.Core.Repositories.Users.Fixtures; +using Lumina.Domain.Common.Errors; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Users; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly UserRepository _sut; + private readonly UserEntityFixture _userEntityFixture; + + /// + /// Initializes a new instance of the class. + /// + public UserRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _sut = new UserRepository(_mockContext); + _userEntityFixture = new UserEntityFixture(); + } + + [Fact] + public async Task InsertAsync_WhenUserDoesNotExist_ShouldAddUserToContextAndReturnCreated() + { + // Arrange + UserEntity userModel = _userEntityFixture.CreateUserModel(); + + // Act + ErrorOr result = await _sut.InsertAsync(userModel, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(Result.Created); + + EntityEntry? addedUser = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == userModel.Id); + addedUser.Should().NotBeNull(); + } + + [Fact] + public async Task InsertAsync_WhenUserAlreadyExists_ShouldReturnError() + { + // Arrange + UserEntity userModel = _userEntityFixture.CreateUserModel(); + + _mockContext.Users.Add(userModel); + await _mockContext.SaveChangesAsync(); + + // Act + ErrorOr result = await _sut.InsertAsync(userModel, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Users.UserAlreadyExists); + _mockContext.ChangeTracker.Entries().Should().HaveCount(1); + } + + [Fact] + public async Task GetAllAsync_WhenCalled_ShouldReturnAllUsers() + { + // Arrange + List users = + [ + _userEntityFixture.CreateUserModel(), + _userEntityFixture.CreateUserModel(), + _userEntityFixture.CreateUserModel() + ]; + _mockContext.Users.AddRange(users); + await _mockContext.SaveChangesAsync(); + + // Act + ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Should().HaveCount(3); + result.Value.Should().BeEquivalentTo(users); + } + + [Fact] + public async Task GetAllAsync_WhenNoUsersExist_ShouldReturnEmptyList() + { + // Act + ErrorOr> result = await _sut.GetAllAsync(CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Should().BeEmpty(); + } + + [Fact] + public async Task GetByUsernameAsync_WhenUserExists_ShouldReturnUser() + { + // Arrange + UserEntity userModel = _userEntityFixture.CreateUserModel(); + _mockContext.Users.Add(userModel); + await _mockContext.SaveChangesAsync(); + + // Act + ErrorOr result = await _sut.GetByUsernameAsync(userModel.Username, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Should().BeEquivalentTo(userModel); + } + + [Fact] + public async Task GetByUsernameAsync_WhenUserDoesNotExist_ShouldReturnNull() + { + // Act + ErrorOr result = await _sut.GetByUsernameAsync("nonexistent", CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeNull(); + } + + [Fact] + public async Task UpdateAsync_WhenUserExists_ShouldUpdateUserAndReturnUpdated() + { + // Arrange + UserEntity existingUser = _userEntityFixture.CreateUserModel(); + _mockContext.Users.Add(existingUser); + await _mockContext.SaveChangesAsync(); + + // Create updated user with same Id but different properties + UserEntity updatedUser = new() + { + Id = existingUser.Id, + Username = existingUser.Username, // Keep username as it's used for lookup + Password = "NewPassword123", + TempPassword = "TempPass456", + TotpSecret = "NewSecret", + Libraries = [], + Created = existingUser.Created, + Updated = DateTime.UtcNow + }; + + // Act + ErrorOr result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(Result.Updated); + + UserEntity? modifiedUser = await _mockContext.Users.FirstOrDefaultAsync(u => u.Username == existingUser.Username); + modifiedUser.Should().NotBeNull(); + modifiedUser!.Password.Should().Be(updatedUser.Password); + modifiedUser.TempPassword.Should().Be(updatedUser.TempPassword); + modifiedUser.TotpSecret.Should().Be(updatedUser.TotpSecret); + } + + [Fact] + public async Task UpdateAsync_WhenUserDoesNotExist_ShouldReturnError() + { + // Arrange + UserEntity userModel = _userEntityFixture.CreateUserModel(); + + // Act + ErrorOr result = await _sut.UpdateAsync(userModel, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Users.UserDoesNotExist); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsModelValidatorTests.cs index 9ac065ef..d1345b66 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsModelValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsModelValidatorTests.cs @@ -60,4 +60,4 @@ public class DatabaseSettingsModelValidatorTests result.Errors.Should().ContainSingle() .Which.ErrorMessage.Should().Be(Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Description); } -} \ No newline at end of file +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs new file mode 100644 index 00000000..4161fb7d --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Infrastructure.Common.Errors; +using Lumina.Infrastructure.Common.Models.Configuration; +using Lumina.Infrastructure.Common.Validators; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Validators; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EncryptionSettingsModelValidatorTests +{ + private readonly EncryptionSettingsModelValidator _validator; + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public EncryptionSettingsModelValidatorTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _validator = new(); + } + + [Fact] + public void EncryptionSettingsModelValidator_WhenValidBase64SecretKeyProvided_ShouldNotHaveValidationError() + { + // Arrange + EncryptionSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, "dGhpcyBpcyBhIHZhbGlkIGJhc2U2NCBzdHJpbmc=") // "this is a valid base64 string" in base64 + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeTrue(); + result.Errors.Should().BeEmpty(); + } + + [Fact] + public void EncryptionSettingsModelValidator_WhenSecretKeyIsEmpty_ShouldHaveValidationError() + { + // Arrange + EncryptionSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, string.Empty) + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.EncryptionSecretKeyCannotBeEmpty.Description); + } + + [Theory] + [InlineData("not-a-base64-string")] + [InlineData("invalid!base64")] + [InlineData("123")] + public void EncryptionSettingsModelValidator_WhenSecretKeyIsNotBase64_ShouldHaveValidationError(string invalidBase64) + { + // Arrange + EncryptionSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, invalidBase64) + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.EncryptionSecretKeyMustBeABase64String.Description); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsModelValidatorTests.cs new file mode 100644 index 00000000..d12653c4 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/JwtSettingsModelValidatorTests.cs @@ -0,0 +1,157 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Infrastructure.Common.Errors; +using Lumina.Infrastructure.Common.Models.Configuration; +using Lumina.Infrastructure.Common.Validators; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Validators; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class JwtSettingsModelValidatorTests +{ + private readonly JwtSettingsModelValidator _validator; + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public JwtSettingsModelValidatorTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _validator = new(); + } + + [Fact] + public void JwtSettingsModelValidator_WhenAllPropertiesValid_ShouldNotHaveValidationError() + { + // Arrange + JwtSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing") + .With(x => x.ExpiryMinutes, 30) + .With(x => x.Issuer, "test-issuer") + .With(x => x.Audience, "test-audience") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeTrue(); + result.Errors.Should().BeEmpty(); + } + + [Fact] + public void JwtSettingsModelValidator_WhenSecretKeyIsEmpty_ShouldHaveValidationErrors() + { + // Arrange + JwtSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, string.Empty) + .With(x => x.ExpiryMinutes, 30) + .With(x => x.Issuer, "test-issuer") + .With(x => x.Audience, "test-audience") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().HaveCount(2); + result.Errors.Select(e => e.ErrorMessage).Should().Contain(new[] + { + Errors.Configuration.JwtSecretKeyCannotBeEmpty.Description, + Errors.Configuration.JwtSecretKeyTooShort.Description + }); + } + + [Fact] + public void JwtSettingsModelValidator_WhenSecretKeyTooShort_ShouldHaveValidationError() + { + // Arrange + JwtSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, "short-key") + .With(x => x.ExpiryMinutes, 30) + .With(x => x.Issuer, "test-issuer") + .With(x => x.Audience, "test-audience") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.JwtSecretKeyTooShort.Description); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(-60)] + public void JwtSettingsModelValidator_WhenExpiryMinutesNotPositive_ShouldHaveValidationError(int minutes) + { + // Arrange + JwtSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing") + .With(x => x.ExpiryMinutes, minutes) + .With(x => x.Issuer, "test-issuer") + .With(x => x.Audience, "test-audience") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.JwtExpiryMinutesMustBePositive.Description); + } + + [Fact] + public void JwtSettingsModelValidator_WhenIssuerIsEmpty_ShouldHaveValidationError() + { + // Arrange + JwtSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing") + .With(x => x.ExpiryMinutes, 30) + .With(x => x.Issuer, string.Empty) + .With(x => x.Audience, "test-audience") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.JwtIssuerCannotBeEmpty.Description); + } + + [Fact] + public void JwtSettingsModelValidator_WhenAudienceIsEmpty_ShouldHaveValidationError() + { + // Arrange + JwtSettingsModel model = _fixture.Build() + .With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing") + .With(x => x.ExpiryMinutes, 30) + .With(x => x.Issuer, "test-issuer") + .With(x => x.Audience, string.Empty) + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.JwtAudienceCannotBeEmpty.Description); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsModelValidatorTests.cs new file mode 100644 index 00000000..d44b6a43 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsModelValidatorTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Infrastructure.Common.Errors; +using Lumina.Infrastructure.Common.Models.Configuration; +using Lumina.Infrastructure.Common.Validators; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Validators; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaSettingsModelValidatorTests +{ + private readonly MediaSettingsModelValidator _validator; + private readonly IFixture _fixture; + + /// + /// Initializes a new instance of the class. + /// + public MediaSettingsModelValidatorTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _validator = new(); + } + + [Fact] + public void MediaSettingsModelValidator_WhenRootDirectoryProvided_ShouldNotHaveValidationError() + { + // Arrange + MediaSettingsModel model = _fixture.Build() + .With(x => x.RootDirectory, "/path/to/media") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeTrue(); + result.Errors.Should().BeEmpty(); + } + + [Fact] + public void MediaSettingsModelValidator_WhenRootDirectoryIsEmpty_ShouldHaveValidationError() + { + // Arrange + MediaSettingsModel model = _fixture.Build() + .With(x => x.RootDirectory, string.Empty) + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description); + } + + [Fact] + public void MediaSettingsModelValidator_WhenRootDirectoryIsWhitespace_ShouldHaveValidationError() + { + // Arrange + MediaSettingsModel model = _fixture.Build() + .With(x => x.RootDirectory, " ") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/JwtTokenGeneratorFixture.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/JwtTokenGeneratorFixture.cs new file mode 100644 index 00000000..3695aa84 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/JwtTokenGeneratorFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Infrastructure.Common.Models.Configuration; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures; + +/// +/// Fixture class for JWT token generation tests. +/// +[ExcludeFromCodeCoverage] +public class JwtTokenGeneratorFixture +{ + /// + /// Creates a valid JWT settings model for testing. + /// + /// The created settings model. + public static JwtSettingsModel CreateJwtSettings() + { + return new Faker() + .CustomInstantiator(f => new JwtSettingsModel + { + SecretKey = "this-is-a-very-long-secret-key-for-testing-jwt-tokens", + ExpiryMinutes = 30, + Issuer = "test-issuer", + Audience = "test-audience" + }) + .Generate(); + } + + /// + /// Creates test user credentials. + /// + /// A tuple containing the user ID and username. + public static (string Id, string Username) CreateUserCredentials() + { + return (Guid.NewGuid().ToString(), new Faker().Person.UserName); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/QRCodeGeneratorFixture.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/QRCodeGeneratorFixture.cs new file mode 100644 index 00000000..d9a27946 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/Fixtures/QRCodeGeneratorFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures; + +/// +/// Fixture class for QR code generation tests. +/// +[ExcludeFromCodeCoverage] +public class QRCodeGeneratorFixture +{ + /// + /// Creates test data for QR code generation. + /// + /// A tuple containing username and secret bytes. + public static (string Username, byte[] Secret) CreateQrCodeTestData() + { + string username = new Faker().Person.UserName; + byte[] secret = new byte[20]; // Standard TOTP secret length + new Random().NextBytes(secret); + return (username, secret); + } + + /// + /// Gets the expected otpauth URI format for validation. + /// + /// The username to use in the URI. + /// The Base32 encoded secret. + /// The formatted otpauth URI. + public static string GetExpectedOtpauthUri(string username, string base32Secret) + { + return $"otpauth://totp/Lumina:{Uri.EscapeDataString(username)}?secret={base32Secret}&issuer=Lumina"; + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/JwtTokenGeneratorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/JwtTokenGeneratorTests.cs new file mode 100644 index 00000000..0d2f404f --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/JwtTokenGeneratorTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Infrastructure.Common.Models.Configuration; +using Lumina.Infrastructure.Core.Authentication; +using Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class JwtTokenGeneratorTests +{ + private readonly IDateTimeProvider _mockDateTimeProvider; + private readonly JwtSettingsModel _jwtSettings; + private readonly JwtTokenGenerator _sut; + private readonly DateTime _fixedUtcNow; + + /// + /// Initializes a new instance of the class. + /// + public JwtTokenGeneratorTests() + { + _mockDateTimeProvider = Substitute.For(); + _jwtSettings = JwtTokenGeneratorFixture.CreateJwtSettings(); + _fixedUtcNow = new DateTime(2024, 1, 1, 12, 0, 0, DateTimeKind.Utc); + + _mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow); + + IOptions options = Substitute.For>(); + options.Value.Returns(_jwtSettings); + + _sut = new JwtTokenGenerator(_mockDateTimeProvider, options); + } + + [Fact] + public void GenerateToken_WhenCalled_ShouldCreateValidJwtToken() + { + // Arrange + (string userId, string username) = JwtTokenGeneratorFixture.CreateUserCredentials(); + JwtSecurityTokenHandler tokenHandler = new(); + + // Act + string token = _sut.GenerateToken(userId, username); + + // Assert + token.Should().NotBeNullOrEmpty(); + + JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(token); + + // verify token properties + jwtToken.Issuer.Should().Be(_jwtSettings.Issuer); + jwtToken.Audiences.Should().ContainSingle().Which.Should().Be(_jwtSettings.Audience); + jwtToken.ValidTo.Should().Be(_fixedUtcNow.AddMinutes(_jwtSettings.ExpiryMinutes)); + + // verify claims + jwtToken.Claims.Should().Contain(c => c.Type == JwtRegisteredClaimNames.Sub && c.Value == userId); + jwtToken.Claims.Should().Contain(c => c.Type == JwtRegisteredClaimNames.UniqueName && c.Value == username); + jwtToken.Claims.Should().Contain(c => c.Type == JwtRegisteredClaimNames.Jti && c.Value == userId); + + // verify the token is actually valid + TokenValidationParameters validationParameters = new() + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey)), + ValidateIssuer = true, + ValidIssuer = _jwtSettings.Issuer, + ValidateAudience = true, + ValidAudience = _jwtSettings.Audience, + ValidateLifetime = true, + ClockSkew = TimeSpan.Zero, + // override the current time to match our fixed test time + LifetimeValidator = (notBefore, expires, token, parameters) => expires > _fixedUtcNow + }; + + ClaimsPrincipal principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken); + + principal.Should().NotBeNull(); + validatedToken.Should().NotBeNull(); + } + + [Fact] + public void GenerateToken_WhenCalled_ShouldUseProvidedDateTimeForExpiration() + { + // Arrange + (string userId, string username) = JwtTokenGeneratorFixture.CreateUserCredentials(); + JwtSecurityTokenHandler tokenHandler = new(); + + // Act + string token = _sut.GenerateToken(userId, username); + JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(token); + + // Assert + jwtToken.ValidTo.Should().Be(_fixedUtcNow.AddMinutes(_jwtSettings.ExpiryMinutes)); + _ = _mockDateTimeProvider.Received(1).UtcNow; + } + + [Fact] + public void GenerateToken_WhenCalledWithDifferentUsers_ShouldCreateUniqueTokens() + { + // Arrange + (string userId1, string username1) = JwtTokenGeneratorFixture.CreateUserCredentials(); + (string userId2, string username2) = JwtTokenGeneratorFixture.CreateUserCredentials(); + + // Act + string token1 = _sut.GenerateToken(userId1, username1); + string token2 = _sut.GenerateToken(userId2, username2); + + // Assert + token1.Should().NotBe(token2); + } + + [Fact] + public void GenerateToken_WhenCalledMultipleTimesForSameUser_ShouldCreateIdenticalTokens() + { + // Arrange + (string userId, string username) = JwtTokenGeneratorFixture.CreateUserCredentials(); + + // Act + string token1 = _sut.GenerateToken(userId, username); + string token2 = _sut.GenerateToken(userId, username); + + // Assert + token1.Should().Be(token2); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/QRCodeGeneratorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/QRCodeGeneratorTests.cs new file mode 100644 index 00000000..1a6158a5 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/QRCodeGeneratorTests.cs @@ -0,0 +1,151 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Infrastructure.Common.Errors; +using Lumina.Infrastructure.Common.Models.Configuration; +using Lumina.Infrastructure.Common.Validators; +using Lumina.Infrastructure.Core.Authentication; +using Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class QRCodeGeneratorTests +{ + private readonly QRCodeGenerator _sut; + + /// + /// Initializes a new instance of the class. + /// + public QRCodeGeneratorTests() + { + _sut = new QRCodeGenerator(); + } + + [Fact] + public void GenerateQrCodeDataUri_WhenCalled_ShouldReturnValidDataUri() + { + // Arrange + (string username, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData(); + + // Act + string result = _sut.GenerateQrCodeDataUri(username, secret); + + // Assert + result.Should().StartWith("data:image/png;base64,"); + result.Should().Match(uri => IsBase64String(uri.Substring(22))); // Skip "data:image/png;base64," + } + + [Fact] + public void GenerateQrCodeDataUri_WhenUsernameContainsSpecialCharacters_ShouldEscapeUsername() + { + // Arrange + string username = "user@example.com"; + (_, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData(); + + // Act + string result = _sut.GenerateQrCodeDataUri(username, secret); + + // Assert + result.Should().StartWith("data:image/png;base64,"); + result.Should().Match(uri => IsBase64String(uri.Substring(22))); + } + + [Fact] + public void GenerateQrCodeDataUri_WhenCalled_ShouldGenerateUniqueQrCodesForDifferentUsers() + { + // Arrange + (string username1, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData(); + string username2 = username1 + "_different"; + + // Act + string result1 = _sut.GenerateQrCodeDataUri(username1, secret); + string result2 = _sut.GenerateQrCodeDataUri(username2, secret); + + // Assert + result1.Should().NotBe(result2); + } + + [Fact] + public void GenerateQrCodeDataUri_WhenCalledWithSameInput_ShouldGenerateIdenticalQrCodes() + { + // Arrange + (string username, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData(); + + // Act + string result1 = _sut.GenerateQrCodeDataUri(username, secret); + string result2 = _sut.GenerateQrCodeDataUri(username, secret); + + // Assert + result1.Should().Be(result2); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void GenerateQrCodeDataUri_WhenUsernameIsInvalid_ShouldStillGenerateQrCode(string? invalidUsername) + { + // Arrange + (_, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData(); + + // Act + string result = _sut.GenerateQrCodeDataUri(invalidUsername!, secret); + + // Assert + result.Should().StartWith("data:image/png;base64,"); + result.Should().Match(uri => IsBase64String(uri.Substring(22))); + } + + [Theory] + [InlineData("user@example.com")] + [InlineData("user name with spaces")] + [InlineData("user+with+plus")] + [InlineData("user/with/slashes")] + public void GenerateQrCodeDataUri_WhenUsernameHasSpecialCharacters_ShouldStillGenerateQrCode(string username) + { + // Arrange + (_, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData(); + + // Act + string result = _sut.GenerateQrCodeDataUri(username, secret); + + // Assert + result.Should().StartWith("data:image/png;base64,"); + result.Should().Match(uri => IsBase64String(uri.Substring(22))); + } + + [Fact] + public void GenerateQrCodeDataUri_WhenSecretIsTooShort_ShouldStillGenerateQrCode() + { + // Arrange + (string username, _) = QRCodeGeneratorFixture.CreateQrCodeTestData(); + byte[] shortSecret = [1]; // minimum length for Base32 encoding + + // Act + string result = _sut.GenerateQrCodeDataUri(username, shortSecret); + + // Assert + result.Should().StartWith("data:image/png;base64,"); + result.Should().Match(uri => IsBase64String(uri.Substring(22))); + } + + private static bool IsBase64String(string base64) + { + try + { + Convert.FromBase64String(base64); + return true; + } + catch + { + return false; + } + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TokenGeneratorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TokenGeneratorTests.cs new file mode 100644 index 00000000..3fce0289 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TokenGeneratorTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Infrastructure.Core.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TokenGeneratorTests +{ + private readonly TokenGenerator _sut; + + /// + /// Initializes a new instance of the class. + /// + public TokenGeneratorTests() + { + _sut = new TokenGenerator(); + } + + [Fact] + public void GenerateToken_WhenCalled_ShouldGenerateNonEmptyToken() + { + // Act + string token = _sut.GenerateToken(); + + // Assert + token.Should().NotBeNullOrEmpty(); + } + + [Fact] + public void GenerateToken_WhenCalled_ShouldGenerateUrlSafeToken() + { + // Act + string token = _sut.GenerateToken(); + + // Assert + token.Should().NotContain("+", "Token should not contain '+'"); + token.Should().NotContain("/", "Token should not contain '/'"); + token.Should().NotContain("=", "Token should not contain '='"); + } + + [Fact] + public void GenerateToken_WhenCalledMultipleTimes_ShouldGenerateUniqueTokens() + { + // Act + string token1 = _sut.GenerateToken(); + string token2 = _sut.GenerateToken(); + string token3 = _sut.GenerateToken(); + + // Assert + token1.Should().NotBe(token2); + token1.Should().NotBe(token3); + token2.Should().NotBe(token3); + } + + [Fact] + public void GenerateToken_WhenCalled_ShouldGenerateTokenOfCorrectLength() + { + // Act + string token = _sut.GenerateToken(); + + // Assert + // 32 bytes in Base64 without padding should be 43 characters + token.Length.Should().Be(43); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TotpTokenGeneratorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TotpTokenGeneratorTests.cs new file mode 100644 index 00000000..143a5e98 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authentication/TotpTokenGeneratorTests.cs @@ -0,0 +1,109 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Infrastructure.Core.Authentication; +using OtpNet; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Authentication; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TotpTokenGeneratorTests +{ + private readonly TotpTokenGenerator _sut; + + /// + /// Initializes a new instance of the class. + /// + public TotpTokenGeneratorTests() + { + _sut = new TotpTokenGenerator(); + } + + [Fact] + public void GenerateSecret_WhenCalled_ShouldGenerateNonEmptySecret() + { + // Act + byte[] secret = _sut.GenerateSecret(); + + // Assert + secret.Should().NotBeEmpty(); + } + + [Fact] + public void GenerateSecret_WhenCalledMultipleTimes_ShouldGenerateUniqueSecrets() + { + // Act + byte[] secret1 = _sut.GenerateSecret(); + byte[] secret2 = _sut.GenerateSecret(); + byte[] secret3 = _sut.GenerateSecret(); + + // Assert + secret1.Should().NotBeEquivalentTo(secret2); + secret1.Should().NotBeEquivalentTo(secret3); + secret2.Should().NotBeEquivalentTo(secret3); + } + + [Fact] + public void ValidateToken_WhenTokenIsValid_ShouldReturnTrue() + { + // Arrange + byte[] secret = _sut.GenerateSecret(); + Totp totp = new(secret); + string validToken = totp.ComputeTotp(); + + // Act + bool result = _sut.ValidateToken(secret, validToken); + + // Assert + result.Should().BeTrue(); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("123456")] // Valid format but wrong token + [InlineData("abcdef")] // Invalid format + [InlineData("12345")] // Too short + [InlineData("1234567")] // Too long + public void ValidateToken_WhenTokenIsInvalid_ShouldReturnFalse(string invalidToken) + { + // Arrange + byte[] secret = _sut.GenerateSecret(); + + // Act + bool result = _sut.ValidateToken(secret, invalidToken); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void ValidateToken_WhenSecretIsWrong_ShouldReturnFalse() + { + // Arrange + byte[] secret1 = _sut.GenerateSecret(); + byte[] secret2 = _sut.GenerateSecret(); + Totp totp = new(secret1); + string token = totp.ComputeTotp(); + + // Act + bool result = _sut.ValidateToken(secret2, token); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void GenerateSecret_WhenCalled_ShouldGenerateSecretOfCorrectLength() + { + // Act + byte[] secret = _sut.GenerateSecret(); + + // Assert + secret.Length.Should().Be(20); // Standard TOTP secret length + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/CryptographyServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/CryptographyServiceTests.cs new file mode 100644 index 00000000..9c950f21 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/CryptographyServiceTests.cs @@ -0,0 +1,161 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Infrastructure.Common.Models.Configuration; +using Lumina.Infrastructure.Core.Security; +using Lumina.Infrastructure.UnitTests.Core.Security.Fixtures; +using Microsoft.Extensions.Options; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Security.Cryptography; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Security; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CryptographyServiceTests +{ + private readonly CryptographyService _sut; + private readonly IOptions _encryptionSettings; + + /// + /// Initializes a new instance of the class. + /// + public CryptographyServiceTests() + { + _encryptionSettings = CryptographyServiceFixture.CreateEncryptionSettings(); + _sut = new CryptographyService(_encryptionSettings); + } + + [Fact] + public void Encrypt_WhenCalledWithValidData_ShouldReturnNonEmptyString() + { + // Arrange + string plaintext = CryptographyServiceFixture.CreateTestData(); + + // Act + string result = _sut.Encrypt(plaintext); + + // Assert + result.Should().NotBeNullOrEmpty(); + result.Should().NotBe(plaintext); + } + + [Fact] + public void Encrypt_WhenCalledMultipleTimesWithSameInput_ShouldReturnDifferentResults() + { + // Arrange + string plaintext = CryptographyServiceFixture.CreateTestData(); + + // Act + string result1 = _sut.Encrypt(plaintext); + string result2 = _sut.Encrypt(plaintext); + + // Assert + result1.Should().NotBe(result2); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public void Encrypt_WhenInputIsNullOrEmpty_ShouldThrowArgumentException(string? invalidInput) + { + // Act + Action act = () => _sut.Encrypt(invalidInput!); + + // Assert + act.Should().Throw() + .WithParameterName("plaintext") + .WithMessage("Value cannot be null or empty*"); + } + + [Fact] + public void Decrypt_WhenCalledWithValidData_ShouldReturnOriginalText() + { + // Arrange + string originalText = CryptographyServiceFixture.CreateTestData(); + string encrypted = _sut.Encrypt(originalText); + + // Act + string decrypted = _sut.Decrypt(encrypted); + + // Assert + decrypted.Should().Be(originalText); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public void Decrypt_WhenInputIsNullOrEmpty_ShouldThrowArgumentException(string? invalidInput) + { + // Act + Action act = () => _sut.Decrypt(invalidInput!); + + // Assert + act.Should().Throw() + .WithParameterName("ciphertext") + .WithMessage("Value cannot be null or empty*"); + } + + [Theory] + [InlineData("invalid")] + [InlineData("not-base64-!@#")] + public void Decrypt_WhenInputIsNotBase64_ShouldThrowFormatException(string invalidInput) + { + // Act + Action act = () => _sut.Decrypt(invalidInput); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void Decrypt_WhenInputIsTooShort_ShouldThrowArgumentException() + { + // Arrange + string shortCiphertext = Convert.ToBase64String(new byte[8]); // less than required 16 bytes + + // Act + Action act = () => _sut.Decrypt(shortCiphertext); + + // Assert + act.Should().Throw() + .WithMessage("Invalid ciphertext"); + } + + [Fact] + public void Decrypt_WhenInputIsCorrupted_ShouldThrowCryptographicException() + { + // Arrange + string originalText = CryptographyServiceFixture.CreateTestData(); + string encrypted = _sut.Encrypt(originalText); + + // decode the Base64 string, modify one byte, then re-encode + byte[] encryptedBytes = Convert.FromBase64String(encrypted); + encryptedBytes[^1] ^= 0xFF; // flip all bits in the last byte + string corrupted = Convert.ToBase64String(encryptedBytes); + + // Act + Action act = () => _sut.Decrypt(corrupted); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void Dispose_WhenCalled_ShouldClearKey() + { + // Arrange + string plaintext = CryptographyServiceFixture.CreateTestData(); + string encrypted = _sut.Encrypt(plaintext); + + // Act + _sut.Dispose(); + + // Assert + Action act = () => _sut.Decrypt(encrypted); + act.Should().Throw(); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/Fixtures/CryptographyServiceFixture.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/Fixtures/CryptographyServiceFixture.cs new file mode 100644 index 00000000..b998aa1e --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/Fixtures/CryptographyServiceFixture.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Infrastructure.Common.Models.Configuration; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Security.Cryptography; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Security.Fixtures; + +/// +/// Fixture class for cryptography service tests. +/// +[ExcludeFromCodeCoverage] +public class CryptographyServiceFixture +{ + /// + /// Creates a valid encryption settings model for testing. + /// + /// The configured options. + public static IOptions CreateEncryptionSettings() + { + // Generate a valid 256-bit (32 byte) key for AES-256 + byte[] key = new byte[32]; + RandomNumberGenerator.Fill(key); + string base64Key = Convert.ToBase64String(key); + + EncryptionSettingsModel settings = new() + { + SecretKey = base64Key + }; + + IOptions options = Substitute.For>(); + options.Value.Returns(settings); + + return options; + } + + /// + /// Creates test data for encryption/decryption. + /// + /// A string to be encrypted/decrypted. + public static string CreateTestData() + { + return new Faker().Lorem.Sentence(); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/HashServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/HashServiceTests.cs new file mode 100644 index 00000000..5b762896 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/HashServiceTests.cs @@ -0,0 +1,165 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Infrastructure.Core.Security; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Security; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class HashServiceTests +{ + private readonly HashService _sut; + + /// + /// Initializes a new instance of the class. + /// + public HashServiceTests() + { + _sut = new HashService(); + } + + [Fact] + public void HashString_WhenCalled_ShouldReturnNonEmptyHash() + { + // Arrange + string password = "TestPassword123!"; + + // Act + string result = _sut.HashString(password); + + // Assert + result.Should().NotBeNullOrEmpty(); + result.Should().NotBe(password); + } + + [Fact] + public void HashString_WhenCalledMultipleTimesWithSameInput_ShouldReturnDifferentHashes() + { + // Arrange + string password = "TestPassword123!"; + + // Act + string hash1 = _sut.HashString(password); + string hash2 = _sut.HashString(password); + + // Assert + hash1.Should().NotBe(hash2); + } + + [Theory] + [InlineData(" ")] + [InlineData("short")] + [InlineData("verylongpasswordwithlotsofcharactersbutnostringformatting")] + [InlineData("Password123!")] + [InlineData("@#$%^&*()")] + public void HashString_WhenCalledWithDifferentInputs_ShouldGenerateValidHashes(string input) + { + // Act + string hash = _sut.HashString(input); + + // Assert + hash.Should().NotBeNullOrEmpty(); + // verify it's a valid Base64 string + Action decode = () => Convert.FromBase64String(hash); + decode.Should().NotThrow(); + } + + [Fact] + public void CheckStringAgainstHash_WhenPasswordMatches_ShouldReturnTrue() + { + // Arrange + string password = "TestPassword123!"; + string hash = _sut.HashString(password); + + // Act + bool result = _sut.CheckStringAgainstHash(password, hash); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void CheckStringAgainstHash_WhenPasswordDoesNotMatch_ShouldReturnFalse() + { + // Arrange + string password = "TestPassword123!"; + string wrongPassword = "WrongPassword123!"; + string hash = _sut.HashString(password); + + // Act + bool result = _sut.CheckStringAgainstHash(wrongPassword, hash); + + // Assert + result.Should().BeFalse(); + } + + [Theory] + [InlineData("")] + [InlineData("dGVzdA==")] // valid base64 but wrong length + [InlineData("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=")] // valid base64 but wrong length + public void CheckStringAgainstHash_WhenHashIsInvalidLength_ShouldReturnFalse(string invalidHash) + { + // Arrange + string password = "TestPassword123!"; + + // Act + bool result = _sut.CheckStringAgainstHash(password, invalidHash); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void CheckStringAgainstHash_WhenHashIsNotBase64_ShouldThrowFormatException() + { + // Arrange + string password = "TestPassword123!"; + string invalidHash = "not-base64-string"; + + // Act + Action act = () => _sut.CheckStringAgainstHash(password, invalidHash); + + // Assert + act.Should().Throw(); + } + + [Theory] + [InlineData(null)] + public void HashString_WhenPasswordIsNull_ShouldThrowArgumentNullException(string? nullPassword) + { + // Act + Action act = () => _sut.HashString(nullPassword!); + + // Assert + act.Should().Throw(); + } + + [Theory] + [InlineData(null)] + public void CheckStringAgainstHash_WhenPasswordIsNull_ShouldThrowArgumentNullException(string? nullPassword) + { + // Arrange + string hash = _sut.HashString("somepassword"); + + // Act + Action act = () => _sut.CheckStringAgainstHash(nullPassword!, hash); + + // Assert + act.Should().Throw(); + } + + [Fact] + public void CheckStringAgainstHash_WhenHashIsNull_ShouldThrowArgumentNullException() + { + // Act + Action act = () => _sut.CheckStringAgainstHash("password", null!); + + // Assert + act.Should().Throw(); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj index 383c405d..dceb58b9 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj @@ -19,6 +19,7 @@ + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs new file mode 100644 index 00000000..681c8a75 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; +using Lumina.Contracts.Responses.UsersManagement; +using Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.ApplicationSetup; + +[ExcludeFromCodeCoverage] +public class CheckInitializationEndpointTests +{ + private readonly ISender _mockSender; + private readonly CheckInitializationEndpoint _sut; + + public CheckInitializationEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithInitializationResponse() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + InitializationResponse expectedResponse = new(IsInitialized: true); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); + + // Assert + InitializationResponse actualResponse = result.Should().BeOfType>().Subject.Value!; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendCheckInitializationQueryToMediator() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(new InitializationResponse(IsInitialized: true)); + + // Act + await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Any(), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return new InitializationResponse(IsInitialized: true); + }, callInfo.Arg()))); + + // Act + Task operationTask = _sut.ExecuteAsync(new EmptyRequest(), cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/Fixtures/RegistrationRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/Fixtures/RegistrationRequestFixture.cs new file mode 100644 index 00000000..2b4bbd5a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/Fixtures/RegistrationRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.ApplicationSetup.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RegistrationRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// The username for registration. + /// The password for registration. + /// The password confirmation. + /// Whether to use two-factor authentication. + /// The created . + public RegistrationRequest Create( + string? username = null, + string? password = null, + string? passwordConfirm = null, + bool? use2fa = null) + { + string generatedPassword = password ?? _faker.Internet.Password(); + return new RegistrationRequest( + Username: username ?? _faker.Internet.UserName(), + Password: generatedPassword, + PasswordConfirm: passwordConfirm ?? generatedPassword, + Use2fa: use2fa ?? _faker.Random.Bool() + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs new file mode 100644 index 00000000..8ba0700d --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs @@ -0,0 +1,139 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Contracts.Responses.UsersManagement; +using Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.ApplicationSetup.Fixtures; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.ApplicationSetup; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetupApplicationEndpointTests +{ + private readonly ISender _mockSender; + private readonly SetupApplicationEndpoint _sut; + private readonly RegistrationRequestFixture _registrationRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public SetupApplicationEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _registrationRequestFixture = new RegistrationRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithRegistrationResponse() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + RegistrationResponse expectedResponse = new(Guid.NewGuid(), "testUser", "TOTP123"); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Created createdResult = result.Should().BeOfType>().Subject; + createdResult.Value.Should().BeEquivalentTo(expectedResponse); + createdResult.Location.Should().EndWith(expectedResponse.Id.ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Conflict("Registration.Failed", "The application is already initialized."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status409Conflict); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + + problemDetails.ProblemDetails.Title.Should().Be("Registration.Failed"); + problemDetails.ProblemDetails.Detail.Should().Be("The application is already initialized."); + problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status409Conflict); + problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.10"); + problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendSetupApplicationCommandToSender() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123"))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(cmd => + cmd.Username == request.Username && + cmd.Password == request.Password && + cmd.PasswordConfirm == request.PasswordConfirm && + cmd.Use2fa == request.Use2fa), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123")); + }, callInfo.Arg()))); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs new file mode 100644 index 00000000..3892f8fa --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs @@ -0,0 +1,140 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.ChangePassword; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword.Fixtures; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordEndpointTests +{ + private readonly ISender _mockSender; + private readonly ChangePasswordEndpoint _sut; + private readonly ChangePasswordRequestFixture _changePasswordRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public ChangePasswordEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _changePasswordRequestFixture = new ChangePasswordRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithChangePasswordResponse() + { + // Arrange + ChangePasswordRequest request = _changePasswordRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ChangePasswordResponse expectedResponse = new(IsPasswordChanged: true); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = result.Should().BeOfType>().Subject; + okResult.Value.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + ChangePasswordRequest request = _changePasswordRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Password.Invalid", "The current password is incorrect."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Password.Invalid", + Value = new[] { "The current password is incorrect." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendChangePasswordCommandToSender() + { + // Arrange + ChangePasswordRequest request = _changePasswordRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(new ChangePasswordResponse(true))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(cmd => + cmd.Username == request.Username && + cmd.CurrentPassword == request.CurrentPassword && + cmd.NewPassword == request.NewPassword && + cmd.NewPasswordConfirm == request.NewPasswordConfirm), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + ChangePasswordRequest request = _changePasswordRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(new ChangePasswordResponse(true)); + }, callInfo.Arg()))); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs new file mode 100644 index 00000000..d37b5eba --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/Fixtures/ChangePasswordRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// The username for the password change. + /// The current password. + /// The new password. + /// The new password confirmation. + /// The created . + public ChangePasswordRequest Create( + string? username = null, + string? currentPassword = null, + string? newPassword = null, + string? newPasswordConfirm = null) + { + string generatedNewPassword = newPassword ?? _faker.Internet.Password(); + return new ChangePasswordRequest( + Username: username ?? _faker.Internet.UserName(), + CurrentPassword: currentPassword ?? _faker.Internet.Password(), + NewPassword: generatedNewPassword, + NewPasswordConfirm: newPasswordConfirm ?? generatedNewPassword + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/Fixtures/LoginRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/Fixtures/LoginRequestFixture.cs new file mode 100644 index 00000000..4f706305 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/Fixtures/LoginRequestFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.Login.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LoginRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// The username for login. + /// The password for login. + /// The TOTP code for two-factor authentication. + /// The created . + public LoginRequest Create( + string? username = null, + string? password = null, + string? totpCode = null) + { + return new LoginRequest( + Username: username ?? _faker.Internet.UserName(), + Password: password ?? _faker.Internet.Password(), + TotpCode: totpCode ?? _faker.Random.Number(100000, 999999).ToString() + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs new file mode 100644 index 00000000..68938298 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs @@ -0,0 +1,139 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Login; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.Login.Fixtures; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginEndpointTests +{ + private readonly ISender _mockSender; + private readonly LoginEndpoint _sut; + private readonly LoginRequestFixture _loginRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public LoginEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _loginRequestFixture = new LoginRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithLoginResponse() + { + // Arrange + LoginRequest request = _loginRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + LoginResponse expectedResponse = new(Guid.NewGuid(), "testUser", "jwt_token", true); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = result.Should().BeOfType>().Subject; + okResult.Value.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + LoginRequest request = _loginRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Login.Failed", "Invalid username or password."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Login.Failed", + Value = new[] { "Invalid username or password." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendLoginUserQueryToSender() + { + // Arrange + LoginRequest request = _loginRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(new LoginResponse(Guid.NewGuid(), "testUser", "jwt_token", true))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(q => + q.Username == request.Username && + q.Password == request.Password && + q.TotpCode == request.TotpCode), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + LoginRequest request = _loginRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(new LoginResponse(Guid.NewGuid(), "testUser", "jwt_token", true)); + }, callInfo.Arg()))); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs new file mode 100644 index 00000000..a8cb5d73 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/Fixtures/RecoverPasswordRequestFixture.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// The username for password recovery. + /// The TOTP code for verification. + /// The created . + public RecoverPasswordRequest Create( + string? username = null, + string? totpCode = null) + { + return new RecoverPasswordRequest( + Username: username ?? _faker.Internet.UserName(), + TotpCode: totpCode ?? _faker.Random.Number(100000, 999999).ToString() + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs new file mode 100644 index 00000000..24c18032 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -0,0 +1,138 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword.Fixtures; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordEndpointTests +{ + private readonly ISender _mockSender; + private readonly RecoverPasswordEndpoint _sut; + private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public RecoverPasswordEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _recoverPasswordRequestFixture = new RecoverPasswordRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithRecoverPasswordResponse() + { + // Arrange + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + RecoverPasswordResponse expectedResponse = new(IsPasswordReset: true); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = result.Should().BeOfType>().Subject; + okResult.Value.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Recovery.Failed", "Invalid username or TOTP code."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Recovery.Failed", + Value = new[] { "Invalid username or TOTP code." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendRecoverPasswordCommandToSender() + { + // Arrange + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(new RecoverPasswordResponse(true))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(cmd => + cmd.Username == request.Username && + cmd.TotpCode == request.TotpCode), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(new RecoverPasswordResponse(true)); + }, callInfo.Arg()))); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/Fixtures/RegistrationRequestFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/Fixtures/RegistrationRequestFixture.cs new file mode 100644 index 00000000..ea6955fe --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/Fixtures/RegistrationRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.Register.Fixtures; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RegistrationRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// The username for registration. + /// The password for registration. + /// The password confirmation. + /// Whether to use two-factor authentication. + /// The created . + public RegistrationRequest Create( + string? username = null, + string? password = null, + string? passwordConfirm = null, + bool? use2fa = null) + { + string generatedPassword = password ?? _faker.Internet.Password(); + return new RegistrationRequest( + Username: username ?? _faker.Internet.UserName(), + Password: generatedPassword, + PasswordConfirm: passwordConfirm ?? generatedPassword, + Use2fa: use2fa ?? _faker.Random.Bool() + ); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs new file mode 100644 index 00000000..6bfb335f --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -0,0 +1,141 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using FluentAssertions; +using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register; +using Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance.ApplicationSetup.Fixtures; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authentication.Register; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterEndpointTests +{ + private readonly ISender _mockSender; + private readonly RegisterEndpoint _sut; + private readonly RegistrationRequestFixture _registrationRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + public RegisterEndpointTests() + { + _mockSender = Substitute.For(); + _sut = Factory.Create(_mockSender); + _registrationRequestFixture = new RegistrationRequestFixture(); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithRegistrationResponse() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + RegistrationResponse expectedResponse = new(Guid.NewGuid(), "testUser", "TOTP123"); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Created createdResult = result.Should().BeOfType>().Subject; + createdResult.Value.Should().BeEquivalentTo(expectedResponse); + createdResult.Location.Should().EndWith(expectedResponse.Id.ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Registration.Failed", "Username is already taken."); + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + result.Should().BeOfType(); + ProblemHttpResult problemDetails = (ProblemHttpResult)result; + problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails.ContentType.Should().Be("application/problem+json"); + problemDetails.ProblemDetails.Should().BeOfType(); + HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; + validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); + validationProblemDetails.Title.Should().Be("Validation Error"); + validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + validationProblemDetails.Errors.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new + { + Key = "Registration.Failed", + Value = new[] { "Username is already taken." } + }); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendRegisterUserCommandToSender() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123"))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockSender.Received(1).Send( + Arg.Is(cmd => + cmd.Username == request.Username && + cmd.Password == request.Password && + cmd.PasswordConfirm == request.PasswordConfirm && + cmd.Use2fa == request.Use2fa), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockSender.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>(Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123")); + }, callInfo.Arg()))); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +}