mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 20:01:10 +00:00
Merge pull request #58 from BinaryAlley/feature/implement-authentication-system
Adds authentication unit tests
This commit is contained in:
101 files changed
+5549
-135
No files matched your search
@@ -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;
|
||||
/// <summary>
|
||||
/// Contains all services of the Application layer.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class ApplicationLayerServices
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -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
|
||||
|
||||
+4
-4
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Command for the initial application setup.
|
||||
@@ -14,8 +14,8 @@ namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands;
|
||||
/// <param name="PasswordConfirm">Confirmation of the password.</param>
|
||||
/// <param name="Use2fa">Indicates whether to enable two-factor authentication for the Admin account.</param>
|
||||
public record SetupApplicationCommand(
|
||||
string? Username,
|
||||
string? Password,
|
||||
string? PasswordConfirm,
|
||||
string? Username,
|
||||
string? Password,
|
||||
string? PasswordConfirm,
|
||||
bool Use2fa
|
||||
) : IRequest<ErrorOr<RegistrationResponse>>;
|
||||
+4
-4
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to perform the initial application setup.
|
||||
@@ -37,9 +37,9 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
|
||||
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
|
||||
/// <param name="qRCodeGenerator">Injected service for generating QR codes.</param>
|
||||
public SetupApplicationCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
IHashService hashService,
|
||||
ICryptographyService cryptographyService,
|
||||
IUnitOfWork unitOfWork,
|
||||
IHashService hashService,
|
||||
ICryptographyService cryptographyService,
|
||||
ITotpTokenGenerator totpTokenGenerator,
|
||||
IQRCodeGenerator qRCodeGenerator)
|
||||
{
|
||||
+1
-1
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="SetupApplicationCommand"/>.
|
||||
+1
-1
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Query for checking the initialization of the application.
|
||||
+4
-1
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to check the initialization of the application.
|
||||
@@ -22,6 +22,9 @@ public class CheckInitializationQueryHandler : IRequestHandler<CheckInitializati
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CheckInitializationQueryHandler"/> class.
|
||||
/// </summary>
|
||||
public CheckInitializationQueryHandler(IUnitOfWork unitOfWork)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
+8
@@ -48,6 +48,14 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
|
||||
_qRCodeGenerator = qRCodeGenerator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to register an account.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="RegistrationResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<RegistrationResponse>> Handle(RegisterUserCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// check if any users already exists (admin account is only set once!)
|
||||
|
||||
+1
-1
@@ -72,7 +72,7 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
|
||||
if (resultSelectUser.Value.TempPassword is not null)
|
||||
{
|
||||
// the temporary password should only be valid for 15 minutes, if its obsolete, remove it and return error
|
||||
if (resultSelectUser.Value.TempPasswordCreated!.Value.AddMinutes(15) > DateTime.UtcNow)
|
||||
if (resultSelectUser.Value.TempPasswordCreated!.Value.AddMinutes(15) < DateTime.UtcNow)
|
||||
{
|
||||
resultSelectUser.Value.TempPassword = null;
|
||||
resultSelectUser.Value.TempPasswordCreated = null;
|
||||
|
||||
@@ -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;
|
||||
/// <summary>
|
||||
/// Contains all services of the DataAccess layer.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class DataAccessLayerServices
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -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;
|
||||
/// <summary>
|
||||
/// Contains all services of the Domain layer.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class DomainLayerServices
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -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;
|
||||
/// <summary>
|
||||
/// Contains all services of the Infrastructure layer.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class InfrastructureLayerServices
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -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;
|
||||
/// <summary>
|
||||
/// Class containing the shared configuration bindings of the application.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class SharedConfiguration
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -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;
|
||||
/// <summary>
|
||||
/// Service for time related concerns
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DateTimeProvider : IDateTimeProvider
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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;
|
||||
/// <summary>
|
||||
/// Class containing the configuration bindings of the Presentation API layer.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal static class PresentationApiLayerConfiguration
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -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;
|
||||
/// <summary>
|
||||
/// Contains all services of the Presentation API layer.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class PresentationApiLayerServices
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetDirectoriesEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDirectoriesEndpointSummary : Summary<GetDirectoriesEndpoint, GetDirectoriesRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetDirectoryTreeEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDirectoryTreeEndpointSummary : Summary<GetDirectoryTreeEndpoint, GetDirectoryTreeRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetTreeDirectoriesEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTreeDirectoriesEndpointSummary : Summary<GetTreeDirectoriesEndpoint, GetTreeDirectoriesRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetDrivesEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDrivesEndpointSummary : Summary<GetDrivesEndpoint>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetTypeEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTypeEndpointSummary : Summary<GetTypeEndpoint>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetFilesEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFilesEndpointSummary : Summary<GetFilesEndpoint, GetFilesRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetTreeFilesEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTreeFilesEndpointSummary : Summary<GetTreeFilesEndpoint, GetTreeFilesRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="CheckPathExistsEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CheckPathExistsEndpointSummary : Summary<CheckPathExistsEndpoint, CheckPathExistsRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="CombinePathEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CombinePathEndpointSummary : Summary<CombinePathEndpoint, CombinePathRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetPathParentEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathParentEndpointSummary : Summary<GetPathParentEndpoint, GetPathParentRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetPathRootEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathRootEndpointSummary : Summary<GetPathRootEndpoint, GetPathRootRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetPathSeparatorEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathSeparatorEndpointSummary : Summary<GetPathSeparatorEndpoint>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="SplitPathEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SplitPathEndpointSummary : Summary<SplitPathEndpoint, SplitPathRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="ValidatePathEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ValidatePathEndpointSummary : Summary<ValidatePathEndpoint, ValidatePathRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetThumbnailEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetThumbnailEndpointSummary : Summary<GetThumbnailEndpoint, GetThumbnailRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="AddBookEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddLibraryEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetBooksEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetBooksEndpointSummary : Summary<GetBooksEndpoint>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="AddLibraryEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddLibraryEndpointSummary : Summary<AddLibraryEndpoint, AddLibraryRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+1
-1
@@ -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;
|
||||
|
||||
+2
@@ -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;
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="CheckInitializationEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CheckInitializationEndpointSummary : Summary<CheckInitializationEndpoint>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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;
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="SetupApplicationEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetupApplicationEndpointSummary : Summary<SetupApplicationEndpoint, RegistrationRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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.
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="ChangePasswordEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordEndpointSummary : Summary<ChangePasswordEndpoint, ChangePasswordRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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.
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="LoginEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginEndpointSummary : Summary<LoginEndpoint, LoginRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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.
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="RecoverPasswordEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordEndpointSummary : Summary<RecoverPasswordEndpoint, RecoverPasswordRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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.
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="RegisterEndpoint"/> API endpoint, for Swagger.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegisterEndpointSummary : Summary<RegisterEndpoint, RegistrationRequest>
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -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;
|
||||
/// <summary>
|
||||
/// Application entry point, contains the composition root module, wires up all dependencies of the application.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class Program
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -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;
|
||||
/// <summary>
|
||||
/// Class containing the configuration bindings of the Lumina.Presentation.Web project.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal static class PresentationWebLayerConfiguration
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -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;
|
||||
/// <summary>
|
||||
/// Contains all services of the Presentation Web layer.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class PresentationWebLayerServices
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -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;
|
||||
/// <summary>
|
||||
/// Application entry point, contains the composition root module, wires up all dependencies of the application.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class Program
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
+85
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ChangePasswordRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordRequestMappingTests
|
||||
{
|
||||
private readonly ChangePasswordRequestFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ChangePasswordRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+82
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LoginRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginRequestMappingTests
|
||||
{
|
||||
private readonly LoginRequestFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+78
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RecoverPasswordRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordRequestMappingTests
|
||||
{
|
||||
private readonly RecoverPasswordRequestFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RecoverPasswordRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+146
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RegistrationRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegistrationRequestMappingTests
|
||||
{
|
||||
private readonly RegistrationRequestFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RegistrationRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+69
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UserEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserEntityFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid user entity.
|
||||
/// </summary>
|
||||
/// <param name="libraryCount">Number of libraries to generate. Default is 0.</param>
|
||||
/// <returns>The created user entity.</returns>
|
||||
public static UserEntity CreateUserEntity(int libraryCount = 0)
|
||||
{
|
||||
Guid userId = Guid.NewGuid();
|
||||
List<LibraryEntity> libraries = [.. new Faker<LibraryEntity>()
|
||||
.CustomInstantiator(f => new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
Title = f.Commerce.ProductName(),
|
||||
LibraryType = f.PickRandom<LibraryType>(),
|
||||
ContentLocations = [],
|
||||
Created = f.Date.Past(),
|
||||
Updated = null
|
||||
})
|
||||
.Generate(libraryCount)];
|
||||
|
||||
return new Faker<UserEntity>()
|
||||
.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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of user entities.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of entities to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public static List<UserEntity> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count)
|
||||
.Select(_ => CreateUserEntity())
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
+18
-60
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserEntityMappingTests"/> class.
|
||||
/// </summary>
|
||||
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();
|
||||
|
||||
-1
@@ -20,7 +20,6 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetFilesQueryHandler"/> class.
|
||||
/// </summary>
|
||||
|
||||
+7
-5
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="SetupApplicationCommand"/> class.
|
||||
@@ -16,7 +16,7 @@ public class SetupApplicationCommandFixture
|
||||
/// Creates a random valid command for the application setup.
|
||||
/// </summary>
|
||||
/// <returns>The created command.</returns>
|
||||
public static SetupApplicationCommand CreateSetupApplicationCommand()
|
||||
public SetupApplicationCommand CreateSetupApplicationCommand()
|
||||
{
|
||||
string password = "Abcd123$";
|
||||
return new Faker<SetupApplicationCommand>()
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
+194
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SetupApplicationCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetupApplicationCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public SetupApplicationCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockHashService = Substitute.For<IHashService>();
|
||||
_mockCryptographyService = Substitute.For<ICryptographyService>();
|
||||
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
|
||||
_mockQRCodeGenerator = Substitute.For<IQRCodeGenerator>();
|
||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||
_setupApplicationCommandFixture = new SetupApplicationCommandFixture();
|
||||
|
||||
_mockUnitOfWork.GetRepository<IUserRepository>().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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(Enumerable.Empty<UserEntity>()));
|
||||
_mockHashService.HashString(command.Password!)
|
||||
.Returns(hashedPassword);
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
ErrorOr<RegistrationResponse> 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<CancellationToken>());
|
||||
await _mockUserRepository.Received(1).InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(Enumerable.Empty<UserEntity>()));
|
||||
_mockHashService.HashString(command.Password!)
|
||||
.Returns(hashedPassword);
|
||||
_mockTotpTokenGenerator.GenerateSecret()
|
||||
.Returns(totpSecret);
|
||||
_mockQRCodeGenerator.GenerateQrCodeDataUri(command.Username!, totpSecret)
|
||||
.Returns(qrCodeUri);
|
||||
_mockCryptographyService.Encrypt(Arg.Any<string>())
|
||||
.Returns(encryptedSecret);
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
ErrorOr<RegistrationResponse> 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<CancellationToken>());
|
||||
await _mockUserRepository.Received(1).InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenUserAlreadyExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand();
|
||||
UserEntity existingUser = UserEntityFixture.CreateUserEntity();
|
||||
|
||||
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new[] { existingUser });
|
||||
|
||||
// Act
|
||||
ErrorOr<RegistrationResponse> 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<CancellationToken>());
|
||||
await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
ErrorOr<RegistrationResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(error);
|
||||
|
||||
await _mockUserRepository.Received(1).GetAllAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(Enumerable.Empty<UserEntity>()));
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
ErrorOr<RegistrationResponse> result = await _sut.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(error);
|
||||
|
||||
await _mockUserRepository.Received(1).GetAllAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUserRepository.Received(1).InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+19
-19
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SetupApplicationCommandValidator"/> class.
|
||||
@@ -17,6 +15,7 @@ namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Command
|
||||
public class SetupApplicationCommandValidatorTests
|
||||
{
|
||||
private readonly SetupApplicationCommandValidator _validator;
|
||||
private readonly SetupApplicationCommandFixture _commandFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetupApplicationCommandValidatorTests"/> 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<SetupApplicationCommand> 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
|
||||
+91
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CheckInitializationQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CheckInitializationQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IUserRepository _mockUserRepository;
|
||||
private readonly CheckInitializationQueryHandler _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CheckInitializationQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public CheckInitializationQueryHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||
|
||||
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
|
||||
|
||||
_sut = new CheckInitializationQueryHandler(_mockUnitOfWork);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenUsersExist_ShouldReturnInitialized()
|
||||
{
|
||||
// Arrange
|
||||
List<UserEntity> users = UserEntityFixture.CreateMany();
|
||||
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.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<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenNoUsersExist_ShouldReturnNotInitialized()
|
||||
{
|
||||
// Arrange
|
||||
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(Enumerable.Empty<UserEntity>()));
|
||||
|
||||
// Act
|
||||
InitializationResponse result = await _sut.Handle(new CheckInitializationQuery(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsInitialized.Should().BeFalse();
|
||||
await _mockUserRepository.Received(1).GetAllAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenRepositoryReturnsError_ShouldReturnNotInitialized()
|
||||
{
|
||||
// Arrange
|
||||
Error error = Error.Failure("Database.Error", "Failed to retrieve users");
|
||||
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
InitializationResponse result = await _sut.Handle(new CheckInitializationQuery(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsInitialized.Should().BeFalse();
|
||||
await _mockUserRepository.Received(1).GetAllAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+207
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ChangePasswordCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IHashService _mockHashService;
|
||||
private readonly IUserRepository _mockUserRepository;
|
||||
private readonly ChangePasswordCommandHandler _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ChangePasswordCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public ChangePasswordCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockHashService = Substitute.For<IHashService>();
|
||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||
|
||||
_mockUnitOfWork.GetRepository<IUserRepository>().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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(currentPassword, "hashedCurrentPassword")
|
||||
.Returns(true);
|
||||
_mockHashService.HashString(newPassword)
|
||||
.Returns(hashedNewPassword);
|
||||
_mockUserRepository.UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
|
||||
// Act
|
||||
ErrorOr<ChangePasswordResponse> 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<CancellationToken>());
|
||||
_mockHashService.Received(1).CheckStringAgainstHash(currentPassword, "hashedCurrentPassword");
|
||||
_mockHashService.Received(1).HashString(newPassword);
|
||||
await _mockUserRepository.Received(1).UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenUserDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = new("nonexistentUser", "oldPass", "newPass", "newPass");
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(null));
|
||||
|
||||
// Act
|
||||
ErrorOr<ChangePasswordResponse> 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<CancellationToken>());
|
||||
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(incorrectPassword, Uri.UnescapeDataString(user.Password))
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
ErrorOr<ChangePasswordResponse> 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<CancellationToken>());
|
||||
_mockHashService.Received(1).CheckStringAgainstHash(incorrectPassword, Uri.UnescapeDataString(user.Password));
|
||||
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(currentPassword, "hashedCurrentPassword")
|
||||
.Returns(true);
|
||||
_mockUserRepository.UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
ErrorOr<ChangePasswordResponse> 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<CancellationToken>());
|
||||
_mockHashService.Received(1).CheckStringAgainstHash(currentPassword, "hashedCurrentPassword");
|
||||
await _mockUserRepository.Received(1).UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
ErrorOr<ChangePasswordResponse> 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<CancellationToken>());
|
||||
await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+303
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ChangePasswordCommandValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordCommandValidatorTests
|
||||
{
|
||||
private readonly ChangePasswordCommandValidator _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ChangePasswordCommandValidatorTests"/> class.
|
||||
/// </summary>
|
||||
public ChangePasswordCommandValidatorTests()
|
||||
{
|
||||
_validator = new ChangePasswordCommandValidator();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordCommand command = ChangePasswordCommandFixture.CreateChangePasswordCommand();
|
||||
command = command with { Username = null! };
|
||||
|
||||
// Act
|
||||
TestValidationResult<ChangePasswordCommand> 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<ChangePasswordCommand> 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<ChangePasswordCommand> 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<ChangePasswordCommand> 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<ChangePasswordCommand> 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<ChangePasswordCommand> 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<ChangePasswordCommand> 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<ChangePasswordCommand> 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<ChangePasswordCommand> 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<ChangePasswordCommand> 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<ChangePasswordCommand> 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<ChangePasswordCommand> 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<ChangePasswordCommand> 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<ChangePasswordCommand> 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<ChangePasswordCommand> 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<ChangePasswordCommand> 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<ChangePasswordCommand> 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);
|
||||
}
|
||||
}
|
||||
+35
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ChangePasswordCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command for changing a password.
|
||||
/// </summary>
|
||||
/// <returns>The created command.</returns>
|
||||
public static ChangePasswordCommand CreateChangePasswordCommand()
|
||||
{
|
||||
string currentPassword = "Abcd123$";
|
||||
string newPassword = "Wxyz789#";
|
||||
return new Faker<ChangePasswordCommand>()
|
||||
.CustomInstantiator(f => new ChangePasswordCommand(
|
||||
default!,
|
||||
default!,
|
||||
default!,
|
||||
default!
|
||||
))
|
||||
.RuleFor(x => x.Username, f => f.Person.UserName)
|
||||
.RuleFor(x => x.CurrentPassword, currentPassword)
|
||||
.RuleFor(x => x.NewPassword, newPassword)
|
||||
.RuleFor(x => x.NewPasswordConfirm, newPassword);
|
||||
}
|
||||
}
|
||||
+56
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ChangePasswordRequest"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordRequestFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ChangePasswordRequestFixture"/> class.
|
||||
/// </summary>
|
||||
public ChangePasswordRequestFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ChangePasswordRequest"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="ChangePasswordRequest"/>.</returns>
|
||||
public ChangePasswordRequest CreateChangePasswordRequest(
|
||||
string? username = null,
|
||||
string? currentPassword = null,
|
||||
string? newPassword = null,
|
||||
string? newPasswordConfirm = null)
|
||||
{
|
||||
return new ChangePasswordRequest(
|
||||
username ?? _faker.Internet.UserName(),
|
||||
currentPassword ?? _faker.Internet.Password(),
|
||||
newPassword ?? _faker.Internet.Password(),
|
||||
newPasswordConfirm ?? _faker.Internet.Password()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="ChangePasswordRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<ChangePasswordRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count)
|
||||
.Select(_ => CreateChangePasswordRequest())
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
+29
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RecoverPasswordCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command for password recovery.
|
||||
/// </summary>
|
||||
/// <returns>The created command.</returns>
|
||||
public static RecoverPasswordCommand CreateRecoverPasswordCommand()
|
||||
{
|
||||
return new Faker<RecoverPasswordCommand>()
|
||||
.CustomInstantiator(f => new RecoverPasswordCommand(
|
||||
default!,
|
||||
default!
|
||||
))
|
||||
.RuleFor(x => x.Username, f => f.Person.UserName)
|
||||
.RuleFor(x => x.TotpCode, f => f.Random.Replace("######")); // generates 6 random digits
|
||||
}
|
||||
}
|
||||
+52
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RecoverPasswordRequest"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordRequestFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RecoverPasswordRequestFixture"/> class.
|
||||
/// </summary>
|
||||
public RecoverPasswordRequestFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="RecoverPasswordRequest"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="RecoverPasswordRequest"/>.</returns>
|
||||
public RecoverPasswordRequest CreateRecoverPasswordRequest(
|
||||
string? username = null,
|
||||
string? totpCode = null)
|
||||
{
|
||||
return new RecoverPasswordRequest(
|
||||
username ?? _faker.Internet.UserName(),
|
||||
totpCode ?? _faker.Random.Number(100000, 999999).ToString()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="RecoverPasswordRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<RecoverPasswordRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count)
|
||||
.Select(_ => CreateRecoverPasswordRequest())
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
+288
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RecoverPasswordCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CheckInitializationQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public RecoverPasswordCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockHashService = Substitute.For<IHashService>();
|
||||
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
|
||||
_mockCryptographyService = Substitute.For<ICryptographyService>();
|
||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||
|
||||
_mockUnitOfWork.GetRepository<IUserRepository>().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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockCryptographyService.Decrypt(encryptedTotpSecret)
|
||||
.Returns(decryptedTotpSecret);
|
||||
_mockTotpTokenGenerator.ValidateToken(Arg.Any<byte[]>(), totpCode)
|
||||
.Returns(true);
|
||||
_mockHashService.HashString("Abcd123$")
|
||||
.Returns(hashedTempPassword);
|
||||
_mockUserRepository.UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
|
||||
// Act
|
||||
ErrorOr<RecoverPasswordResponse> 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<CancellationToken>());
|
||||
_mockTotpTokenGenerator.Received(1).ValidateToken(Arg.Any<byte[]>(), totpCode);
|
||||
_mockHashService.Received(1).HashString("Abcd123$");
|
||||
await _mockUserRepository.Received(1).UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenUserDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordCommand command = new("nonexistentUser", "123456");
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(null));
|
||||
|
||||
// Act
|
||||
ErrorOr<RecoverPasswordResponse> 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<CancellationToken>());
|
||||
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
|
||||
// Act
|
||||
ErrorOr<RecoverPasswordResponse> 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<CancellationToken>());
|
||||
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
|
||||
// Act
|
||||
ErrorOr<RecoverPasswordResponse> 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<CancellationToken>());
|
||||
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockCryptographyService.Decrypt(encryptedTotpSecret)
|
||||
.Returns(decryptedTotpSecret);
|
||||
_mockTotpTokenGenerator.ValidateToken(Arg.Any<byte[]>(), totpCode)
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
ErrorOr<RecoverPasswordResponse> 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<CancellationToken>());
|
||||
_mockTotpTokenGenerator.Received(1).ValidateToken(Arg.Any<byte[]>(), totpCode);
|
||||
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockCryptographyService.Decrypt(encryptedTotpSecret)
|
||||
.Returns(decryptedTotpSecret);
|
||||
_mockTotpTokenGenerator.ValidateToken(Arg.Any<byte[]>(), totpCode)
|
||||
.Returns(true);
|
||||
_mockUserRepository.UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
ErrorOr<RecoverPasswordResponse> 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<CancellationToken>());
|
||||
_mockTotpTokenGenerator.Received(1).ValidateToken(Arg.Any<byte[]>(), totpCode);
|
||||
await _mockUserRepository.Received(1).UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
ErrorOr<RecoverPasswordResponse> 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<CancellationToken>());
|
||||
await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
|
||||
// Act
|
||||
ErrorOr<RecoverPasswordResponse> 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<CancellationToken>());
|
||||
_mockTotpTokenGenerator.DidNotReceive().ValidateToken(Arg.Any<byte[]>(), Arg.Any<string>());
|
||||
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+168
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RecoverPasswordCommandValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordCommandValidatorTests
|
||||
{
|
||||
private readonly RecoverPasswordCommandValidator _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RecoverPasswordCommandValidatorTests"/> class.
|
||||
/// </summary>
|
||||
public RecoverPasswordCommandValidatorTests()
|
||||
{
|
||||
_validator = new RecoverPasswordCommandValidator();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
|
||||
command = command with { Username = null! };
|
||||
|
||||
// Act
|
||||
TestValidationResult<RecoverPasswordCommand> 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<RecoverPasswordCommand> 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<RecoverPasswordCommand> 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<RecoverPasswordCommand> 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<RecoverPasswordCommand> 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<RecoverPasswordCommand> 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<RecoverPasswordCommand> 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<RecoverPasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.TotpCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordCommand command = RecoverPasswordCommandFixture.CreateRecoverPasswordCommand();
|
||||
|
||||
// Act
|
||||
TestValidationResult<RecoverPasswordCommand> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.Username);
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.TotpCode);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RegisterUserCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegisterCommandFixture
|
||||
public class RegisterUserCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command for a new account registration.
|
||||
+58
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RegistrationRequest"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegistrationRequestFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RegistrationRequestFixture"/> class.
|
||||
/// </summary>
|
||||
public RegistrationRequestFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="RegistrationRequest"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="RegistrationRequest"/>.</returns>
|
||||
public RegistrationRequest CreateRegistrationRequest(
|
||||
string? username = null,
|
||||
string? password = null,
|
||||
string? passwordConfirm = null,
|
||||
bool? use2fa = null)
|
||||
{
|
||||
password ??= _faker.Internet.Password();
|
||||
|
||||
return new RegistrationRequest(
|
||||
username ?? _faker.Internet.UserName(),
|
||||
password,
|
||||
passwordConfirm ?? password,
|
||||
use2fa ?? _faker.Random.Bool()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="RegistrationRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<RegistrationRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count)
|
||||
.Select(_ => CreateRegistrationRequest())
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
+197
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RegisterUserCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RegisterUserCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public RegisterUserCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockHashService = Substitute.For<IHashService>();
|
||||
_mockCryptographyService = Substitute.For<ICryptographyService>();
|
||||
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
|
||||
_mockQRCodeGenerator = Substitute.For<IQRCodeGenerator>();
|
||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||
|
||||
_mockUnitOfWork.GetRepository<IUserRepository>().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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(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<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
ErrorOr<RegistrationResponse> 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<CancellationToken>());
|
||||
_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<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenUserDoesNotExistAndWithout2FA_ShouldRegisterUser()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand() with { Use2fa = false };
|
||||
string hashedPassword = "hashedPassword";
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(null));
|
||||
_mockHashService.HashString(command.Password!)
|
||||
.Returns(hashedPassword);
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
ErrorOr<RegistrationResponse> 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<CancellationToken>());
|
||||
_mockHashService.Received(1).HashString(command.Password!);
|
||||
_mockTotpTokenGenerator.DidNotReceive().GenerateSecret();
|
||||
_mockQRCodeGenerator.DidNotReceive().GenerateQrCodeDataUri(Arg.Any<string>(), Arg.Any<byte[]>());
|
||||
_mockCryptographyService.DidNotReceive().Encrypt(Arg.Any<string>());
|
||||
await _mockUserRepository.Received(1).InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenUserAlreadyExists_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
RegisterUserCommand command = RegisterUserCommandFixture.CreateRegisterCommand();
|
||||
UserEntity existingUser = UserEntityFixture.CreateUserEntity();
|
||||
|
||||
_mockUserRepository.GetByUsernameAsync(command.Username!, Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(existingUser));
|
||||
|
||||
// Act
|
||||
ErrorOr<RegistrationResponse> 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<CancellationToken>());
|
||||
await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(null));
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
ErrorOr<RegistrationResponse> 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<CancellationToken>());
|
||||
await _mockUserRepository.Received(1).InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
ErrorOr<RegistrationResponse> 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<CancellationToken>());
|
||||
await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+18
-18
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RegisterUserCommandValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegisterCommandValidatorTests
|
||||
public class RegisterUserCommandValidatorTests
|
||||
{
|
||||
private readonly RegisterUserCommandValidator _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RegisterCommandValidatorTests"/> class.
|
||||
/// Initializes a new instance of the <see cref="RegisterUserCommandValidatorTests"/> class.
|
||||
/// </summary>
|
||||
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
|
||||
+54
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="LoginRequest"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginRequestFixture
|
||||
{
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginRequestFixture"/> class.
|
||||
/// </summary>
|
||||
public LoginRequestFixture()
|
||||
{
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="LoginRequest"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="LoginRequest"/>.</returns>
|
||||
public LoginRequest CreateLoginRequest(
|
||||
string? username = null,
|
||||
string? password = null,
|
||||
string? totpCode = null)
|
||||
{
|
||||
return new LoginRequest(
|
||||
username ?? _faker.Internet.UserName(),
|
||||
password ?? _faker.Internet.Password(),
|
||||
totpCode ?? _faker.Random.Number(100000, 999999).ToString()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="LoginRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<LoginRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count)
|
||||
.Select(_ => CreateLoginRequest())
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
+36
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="LoginUserQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginUserQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query for user login.
|
||||
/// </summary>
|
||||
/// <param name="includeTotpCode">Whether to include a TOTP code in the query.</param>
|
||||
/// <returns>The created query.</returns>
|
||||
public static LoginUserQuery CreateLoginQuery(bool includeTotpCode = false)
|
||||
{
|
||||
string password = "Abcd123$";
|
||||
Faker<LoginUserQuery> faker = new Faker<LoginUserQuery>()
|
||||
.CustomInstantiator(f => new LoginUserQuery(
|
||||
default!,
|
||||
default!,
|
||||
default
|
||||
))
|
||||
.RuleFor(x => x.Username, f => f.Person.UserName)
|
||||
.RuleFor(x => x.Password, password);
|
||||
|
||||
if (includeTotpCode)
|
||||
faker.RuleFor(x => x.TotpCode, f => f.Random.Replace("######")); // generates 6 random digits
|
||||
return faker;
|
||||
}
|
||||
}
|
||||
+357
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LoginUserQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginUserQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public LoginUserQueryHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockHashService = Substitute.For<IHashService>();
|
||||
_mockJwtTokenGenerator = Substitute.For<IJwtTokenGenerator>();
|
||||
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
|
||||
_mockCryptographyService = Substitute.For<ICryptographyService>();
|
||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||
|
||||
_mockUnitOfWork.GetRepository<IUserRepository>().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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
|
||||
.Returns(true);
|
||||
_mockJwtTokenGenerator.GenerateToken(user.Id.ToString(), user.Username)
|
||||
.Returns(jwtToken);
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> 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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(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<byte[]>(), totpCode)
|
||||
.Returns(true);
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> 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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(null));
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> 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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> 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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
|
||||
.Returns(false);
|
||||
_mockHashService.CheckStringAgainstHash(password, hashedTempPassword)
|
||||
.Returns(true);
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> 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<UserEntity>(u =>
|
||||
u.TempPassword == null && u.TempPasswordCreated == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(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<LoginResponse> 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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
|
||||
.Returns(true);
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> 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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
|
||||
.Returns(true);
|
||||
_mockCryptographyService.Decrypt(encryptedTotpSecret)
|
||||
.Returns(decryptedTotpSecret);
|
||||
_mockTotpTokenGenerator.ValidateToken(Arg.Any<byte[]>(), totpCode)
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> 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<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> 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<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From<UserEntity?>(user));
|
||||
_mockHashService.CheckStringAgainstHash(password, hashedPassword)
|
||||
.Returns(false); // Regular password check fails
|
||||
_mockHashService.CheckStringAgainstHash(password, hashedTempPassword)
|
||||
.Returns(false); // Temp password check also fails
|
||||
|
||||
// Act
|
||||
ErrorOr<LoginResponse> 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<UserEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+222
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LoginUserQueryValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginUserQueryValidatorTests
|
||||
{
|
||||
private readonly LoginUserQueryValidator _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginUserQueryValidatorTests"/> class.
|
||||
/// </summary>
|
||||
public LoginUserQueryValidatorTests()
|
||||
{
|
||||
_validator = new LoginUserQueryValidator();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery();
|
||||
query = query with { Username = null! };
|
||||
|
||||
// Act
|
||||
TestValidationResult<LoginUserQuery> 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<LoginUserQuery> 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<LoginUserQuery> 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<LoginUserQuery> 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<LoginUserQuery> 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<LoginUserQuery> 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<LoginUserQuery> 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<LoginUserQuery> 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<LoginUserQuery> 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<LoginUserQuery> 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<LoginUserQuery> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.TotpCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
LoginUserQuery query = LoginUserQueryFixture.CreateLoginQuery(true);
|
||||
|
||||
// Act
|
||||
TestValidationResult<LoginUserQuery> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.Username);
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.Password);
|
||||
result.ShouldNotHaveValidationErrorFor(x => x.TotpCode);
|
||||
}
|
||||
}
|
||||
+10
-10
@@ -28,7 +28,7 @@ public class BookRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly BookRepository _sut;
|
||||
private readonly BookModelFixture _bookModelFixture;
|
||||
private readonly BookEntityFixture _bookEntityFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookRepositoryTests"/> class.
|
||||
@@ -37,14 +37,14 @@ public class BookRepositoryTests
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_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<Created> 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<TagEntity>().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<GenreEntity>().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<BookEntity> 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)];
|
||||
|
||||
+53
-5
@@ -19,16 +19,16 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures;
|
||||
/// Fixture class for the <see cref="BookEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookModelFixture
|
||||
public class BookEntityFixture
|
||||
{
|
||||
private readonly Fixture _fixture;
|
||||
private readonly Random _random = new();
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookModelFixture"/> class.
|
||||
/// Initializes a new instance of the <see cref="BookEntityFixture"/> class.
|
||||
/// </summary>
|
||||
public BookModelFixture()
|
||||
public BookEntityFixture()
|
||||
{
|
||||
_fixture = new Fixture();
|
||||
_fixture.Customizations.Add(new DateOnlySpecimenBuilder());
|
||||
@@ -38,9 +38,9 @@ public class BookModelFixture
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid BookModel.
|
||||
/// Creates a random valid <see cref="BookEntity"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created BookModel.</returns>
|
||||
/// <returns>The created <see cref="BookEntity"/>.</returns>
|
||||
public BookEntity CreateBookModel()
|
||||
{
|
||||
int releaseYear = _random.Next(2000, 2010);
|
||||
@@ -86,6 +86,11 @@ public class BookModelFixture
|
||||
.Generate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of tag entities with random data.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of tags to create.</param>
|
||||
/// <returns>A list of randomly generated tag entities.</returns>
|
||||
private static List<TagEntity> CreateTags(int count)
|
||||
{
|
||||
return new Faker<TagEntity>()
|
||||
@@ -93,6 +98,11 @@ public class BookModelFixture
|
||||
.Generate(count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of genre entities with random data.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of genres to create.</param>
|
||||
/// <returns>A list of randomly generated genre entities.</returns>
|
||||
private static List<GenreEntity> CreateGenres(int count)
|
||||
{
|
||||
return new Faker<GenreEntity>()
|
||||
@@ -100,6 +110,11 @@ public class BookModelFixture
|
||||
.Generate(count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a valid Library of Congress Control Number (LCCN).
|
||||
/// </summary>
|
||||
/// <param name="f">The Faker instance used for generating random data.</param>
|
||||
/// <returns>A properly formatted LCCN string.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a valid OCLC (Online Computer Library Center) number.
|
||||
/// </summary>
|
||||
/// <param name="f">The Faker instance used for generating random data.</param>
|
||||
/// <returns>A properly formatted OCLC number string with valid prefix.</returns>
|
||||
private string CreateOCLCNumber(Faker f)
|
||||
{
|
||||
string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"];
|
||||
@@ -124,6 +144,11 @@ public class BookModelFixture
|
||||
return prefix + number;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a valid Open Library ID.
|
||||
/// </summary>
|
||||
/// <param name="f">The Faker instance used for generating random data.</param>
|
||||
/// <returns>A properly formatted Open Library ID string.</returns>
|
||||
private string CreateOpenLibraryId(Faker f)
|
||||
{
|
||||
int firstDigit = f.Random.Number(1, 9);
|
||||
@@ -132,6 +157,11 @@ public class BookModelFixture
|
||||
return $"OL{firstDigit}{remainingDigits}{suffix}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a valid Google Books ID.
|
||||
/// </summary>
|
||||
/// <param name="f">The Faker instance used for generating random data.</param>
|
||||
/// <returns>A properly formatted Google Books ID string.</returns>
|
||||
private string CreateGoogleBooksId(Faker f)
|
||||
{
|
||||
const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
@@ -140,6 +170,11 @@ public class BookModelFixture
|
||||
.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of ISBN entities with random data.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of ISBNs to create.</param>
|
||||
/// <returns>A list of randomly generated ISBN entities.</returns>
|
||||
private static List<IsbnEntity> CreateIsbns(int count)
|
||||
{
|
||||
return new Faker<IsbnEntity>()
|
||||
@@ -147,6 +182,11 @@ public class BookModelFixture
|
||||
.Generate(count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a valid ISBN (International Standard Book Number).
|
||||
/// </summary>
|
||||
/// <param name="f">The Faker instance used for generating random data.</param>
|
||||
/// <returns>A properly formatted ISBN-10 or ISBN-13 string with valid checksum.</returns>
|
||||
private static string CreateIsbn(Faker f)
|
||||
{
|
||||
bool isIsbn13 = f.Random.Bool();
|
||||
@@ -177,6 +217,11 @@ public class BookModelFixture
|
||||
}
|
||||
}
|
||||
|
||||
// <summary>
|
||||
/// Creates a list of book rating entities with random data.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of ratings to create.</param>
|
||||
/// <returns>A list of randomly generated book rating entities.</returns>
|
||||
private static List<BookRatingEntity> CreateBookRatings(int count)
|
||||
{
|
||||
return new Faker<BookRatingEntity>()
|
||||
@@ -189,6 +234,9 @@ public class BookModelFixture
|
||||
.Generate(count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures custom type generation rules for the AutoFixture instance.
|
||||
/// </summary>
|
||||
private void ConfigureCustomTypes()
|
||||
{
|
||||
_fixture.Register(() => new TagEntity(_fixture.Create<string>()));
|
||||
+114
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UserEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserEntityFixture
|
||||
{
|
||||
private readonly Fixture _fixture;
|
||||
private readonly Faker _faker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserEntityFixture"/> class.
|
||||
/// </summary>
|
||||
public UserEntityFixture()
|
||||
{
|
||||
_fixture = new Fixture();
|
||||
_faker = new Faker();
|
||||
ConfigureCustomTypes();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="UserEntity"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="UserEntity"/>.</returns>
|
||||
public UserEntity CreateUserModel()
|
||||
{
|
||||
Guid userId = _faker.Random.Guid();
|
||||
|
||||
return new Faker<UserEntity>()
|
||||
.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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a valid collection of user libraries.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of user libraries to create.</param>
|
||||
/// <param name="userId">The Id of the user for whom to create the libraries.</param>
|
||||
/// <returns>A collection of <see cref="LibraryEntity"/>.</returns>
|
||||
private static List<LibraryEntity> CreateLibraries(int count, Guid userId)
|
||||
{
|
||||
return new Faker<LibraryEntity>()
|
||||
.CustomInstantiator(f => new LibraryEntity
|
||||
{
|
||||
Id = f.Random.Guid(),
|
||||
UserId = userId,
|
||||
Title = f.Random.String2(f.Random.Number(1, 50)),
|
||||
LibraryType = f.PickRandom<LibraryType>(),
|
||||
ContentLocations = CreateContentLocations(f.Random.Number(1, 3)),
|
||||
Created = f.Date.Past(),
|
||||
Updated = f.Random.Bool() ? f.Date.Recent() : null
|
||||
})
|
||||
.Generate(count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a valid collection of media paths for a library.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of media library contents to create.</param>
|
||||
/// <returns>A collection of <see cref="LibraryContentLocationEntity"/>.</returns>
|
||||
private static List<LibraryContentLocationEntity> CreateContentLocations(int count)
|
||||
{
|
||||
return new Faker<LibraryContentLocationEntity>()
|
||||
.CustomInstantiator(f => new LibraryContentLocationEntity
|
||||
{
|
||||
Path = f.System.FilePath()
|
||||
})
|
||||
.Generate(count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures custom type generation rules for the AutoFixture instance.
|
||||
/// </summary>
|
||||
private void ConfigureCustomTypes()
|
||||
{
|
||||
_fixture.Register(() => new LibraryEntity
|
||||
{
|
||||
Id = _fixture.Create<Guid>(),
|
||||
UserId = _fixture.Create<Guid>(),
|
||||
Title = _fixture.Create<string>(),
|
||||
LibraryType = _fixture.Create<LibraryType>(),
|
||||
ContentLocations = new List<LibraryContentLocationEntity>(),
|
||||
Created = _fixture.Create<DateTime>(),
|
||||
Updated = _fixture.Create<DateTime>()
|
||||
});
|
||||
|
||||
_fixture.Register(() => new LibraryContentLocationEntity
|
||||
{
|
||||
Path = _fixture.Create<string>()
|
||||
});
|
||||
}
|
||||
}
|
||||
+189
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UserRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly UserRepository _sut;
|
||||
private readonly UserEntityFixture _userEntityFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public UserRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new UserRepository(_mockContext);
|
||||
_userEntityFixture = new UserEntityFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenUserDoesNotExist_ShouldAddUserToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity userModel = _userEntityFixture.CreateUserModel();
|
||||
|
||||
// Act
|
||||
ErrorOr<Created> result = await _sut.InsertAsync(userModel, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().Be(Result.Created);
|
||||
|
||||
EntityEntry<UserEntity>? addedUser = _mockContext.ChangeTracker.Entries<UserEntity>()
|
||||
.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<Created> result = await _sut.InsertAsync(userModel, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Users.UserAlreadyExists);
|
||||
_mockContext.ChangeTracker.Entries<UserEntity>().Should().HaveCount(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenCalled_ShouldReturnAllUsers()
|
||||
{
|
||||
// Arrange
|
||||
List<UserEntity> users =
|
||||
[
|
||||
_userEntityFixture.CreateUserModel(),
|
||||
_userEntityFixture.CreateUserModel(),
|
||||
_userEntityFixture.CreateUserModel()
|
||||
];
|
||||
_mockContext.Users.AddRange(users);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
ErrorOr<IEnumerable<UserEntity>> 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<IEnumerable<UserEntity>> 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<UserEntity?> 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<UserEntity?> 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<Updated> 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<Updated> result = await _sut.UpdateAsync(userModel, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Users.UserDoesNotExist);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -60,4 +60,4 @@ public class DatabaseSettingsModelValidatorTests
|
||||
result.Errors.Should().ContainSingle()
|
||||
.Which.ErrorMessage.Should().Be(Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
}
|
||||
+83
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="EncryptionSettingsModelValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EncryptionSettingsModelValidatorTests
|
||||
{
|
||||
private readonly EncryptionSettingsModelValidator _validator;
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EncryptionSettingsModelValidatorTests"/> class.
|
||||
/// </summary>
|
||||
public EncryptionSettingsModelValidatorTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_validator = new();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EncryptionSettingsModelValidator_WhenValidBase64SecretKeyProvided_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
EncryptionSettingsModel model = _fixture.Build<EncryptionSettingsModel>()
|
||||
.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<EncryptionSettingsModel>()
|
||||
.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<EncryptionSettingsModel>()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
+157
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="JwtSettingsModelValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class JwtSettingsModelValidatorTests
|
||||
{
|
||||
private readonly JwtSettingsModelValidator _validator;
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JwtSettingsModelValidatorTests"/> class.
|
||||
/// </summary>
|
||||
public JwtSettingsModelValidatorTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_validator = new();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JwtSettingsModelValidator_WhenAllPropertiesValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
JwtSettingsModel model = _fixture.Build<JwtSettingsModel>()
|
||||
.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<JwtSettingsModel>()
|
||||
.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<JwtSettingsModel>()
|
||||
.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<JwtSettingsModel>()
|
||||
.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<JwtSettingsModel>()
|
||||
.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<JwtSettingsModel>()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
+80
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaSettingsModelValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaSettingsModelValidatorTests
|
||||
{
|
||||
private readonly MediaSettingsModelValidator _validator;
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaSettingsModelValidatorTests"/> class.
|
||||
/// </summary>
|
||||
public MediaSettingsModelValidatorTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_validator = new();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MediaSettingsModelValidator_WhenRootDirectoryProvided_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
MediaSettingsModel model = _fixture.Build<MediaSettingsModel>()
|
||||
.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<MediaSettingsModel>()
|
||||
.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<MediaSettingsModel>()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
+41
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for JWT token generation tests.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class JwtTokenGeneratorFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a valid JWT settings model for testing.
|
||||
/// </summary>
|
||||
/// <returns>The created settings model.</returns>
|
||||
public static JwtSettingsModel CreateJwtSettings()
|
||||
{
|
||||
return new Faker<JwtSettingsModel>()
|
||||
.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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates test user credentials.
|
||||
/// </summary>
|
||||
/// <returns>A tuple containing the user ID and username.</returns>
|
||||
public static (string Id, string Username) CreateUserCredentials()
|
||||
{
|
||||
return (Guid.NewGuid().ToString(), new Faker().Person.UserName);
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for QR code generation tests.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class QRCodeGeneratorFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates test data for QR code generation.
|
||||
/// </summary>
|
||||
/// <returns>A tuple containing username and secret bytes.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the expected otpauth URI format for validation.
|
||||
/// </summary>
|
||||
/// <param name="username">The username to use in the URI.</param>
|
||||
/// <param name="base32Secret">The Base32 encoded secret.</param>
|
||||
/// <returns>The formatted otpauth URI.</returns>
|
||||
public static string GetExpectedOtpauthUri(string username, string base32Secret)
|
||||
{
|
||||
return $"otpauth://totp/Lumina:{Uri.EscapeDataString(username)}?secret={base32Secret}&issuer=Lumina";
|
||||
}
|
||||
}
|
||||
+137
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="JwtTokenGenerator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class JwtTokenGeneratorTests
|
||||
{
|
||||
private readonly IDateTimeProvider _mockDateTimeProvider;
|
||||
private readonly JwtSettingsModel _jwtSettings;
|
||||
private readonly JwtTokenGenerator _sut;
|
||||
private readonly DateTime _fixedUtcNow;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JwtTokenGeneratorTests"/> class.
|
||||
/// </summary>
|
||||
public JwtTokenGeneratorTests()
|
||||
{
|
||||
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||
_jwtSettings = JwtTokenGeneratorFixture.CreateJwtSettings();
|
||||
_fixedUtcNow = new DateTime(2024, 1, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
|
||||
|
||||
IOptions<JwtSettingsModel> options = Substitute.For<IOptions<JwtSettingsModel>>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
+151
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="QRCodeGenerator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class QRCodeGeneratorTests
|
||||
{
|
||||
private readonly QRCodeGenerator _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="QRCodeGeneratorTests"/> class.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Infrastructure.Core.Authentication;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TokenGenerator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TokenGeneratorTests
|
||||
{
|
||||
private readonly TokenGenerator _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TokenGeneratorTests"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+109
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TotpTokenGenerator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TotpTokenGeneratorTests
|
||||
{
|
||||
private readonly TotpTokenGenerator _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TotpTokenGeneratorTests"/> class.
|
||||
/// </summary>
|
||||
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
|
||||
}
|
||||
}
|
||||
+161
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CryptographyService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CryptographyServiceTests
|
||||
{
|
||||
private readonly CryptographyService _sut;
|
||||
private readonly IOptions<EncryptionSettingsModel> _encryptionSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CryptographyServiceTests"/> class.
|
||||
/// </summary>
|
||||
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<ArgumentException>()
|
||||
.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<ArgumentException>()
|
||||
.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<FormatException>();
|
||||
}
|
||||
|
||||
[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<ArgumentException>()
|
||||
.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<CryptographicException>();
|
||||
}
|
||||
|
||||
[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<CryptographicException>();
|
||||
}
|
||||
}
|
||||
+49
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for cryptography service tests.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CryptographyServiceFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a valid encryption settings model for testing.
|
||||
/// </summary>
|
||||
/// <returns>The configured options.</returns>
|
||||
public static IOptions<EncryptionSettingsModel> 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<EncryptionSettingsModel> options = Substitute.For<IOptions<EncryptionSettingsModel>>();
|
||||
options.Value.Returns(settings);
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates test data for encryption/decryption.
|
||||
/// </summary>
|
||||
/// <returns>A string to be encrypted/decrypted.</returns>
|
||||
public static string CreateTestData()
|
||||
{
|
||||
return new Faker().Lorem.Sentence();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="HashService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class HashServiceTests
|
||||
{
|
||||
private readonly HashService _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HashServiceTests"/> class.
|
||||
/// </summary>
|
||||
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<FormatException>();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
public void HashString_WhenPasswordIsNull_ShouldThrowArgumentNullException(string? nullPassword)
|
||||
{
|
||||
// Act
|
||||
Action act = () => _sut.HashString(nullPassword!);
|
||||
|
||||
// Assert
|
||||
act.Should().Throw<ArgumentNullException>();
|
||||
}
|
||||
|
||||
[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<ArgumentNullException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CheckStringAgainstHash_WhenHashIsNull_ShouldThrowArgumentNullException()
|
||||
{
|
||||
// Act
|
||||
Action act = () => _sut.CheckStringAgainstHash("password", null!);
|
||||
|
||||
// Assert
|
||||
act.Should().Throw<ArgumentNullException>();
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" Version="4.18.1" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" Version="4.18.1" />
|
||||
<PackageReference Include="Bogus" Version="35.6.0" />
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.2">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
|
||||
+91
@@ -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<ISender>();
|
||||
_sut = Factory.Create<CheckInitializationEndpoint>(_mockSender);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithInitializationResponse()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
InitializationResponse expectedResponse = new(IsInitialized: true);
|
||||
_mockSender.Send(Arg.Any<CheckInitializationQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
InitializationResponse actualResponse = result.Should().BeOfType<Ok<InitializationResponse>>().Subject.Value!;
|
||||
actualResponse.Should().BeEquivalentTo(expectedResponse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendCheckInitializationQueryToMediator()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<CheckInitializationQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new InitializationResponse(IsInitialized: true));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(
|
||||
Arg.Any<CheckInitializationQuery>(),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<CheckInitializationQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<InitializationResponse>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return new InitializationResponse(IsInitialized: true);
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(new EmptyRequest(), cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+39
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RegistrationRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegistrationRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="RegistrationRequest"/> with default or random values.
|
||||
/// </summary>
|
||||
/// <param name="username">The username for registration.</param>
|
||||
/// <param name="password">The password for registration.</param>
|
||||
/// <param name="passwordConfirm">The password confirmation.</param>
|
||||
/// <param name="use2fa">Whether to use two-factor authentication.</param>
|
||||
/// <returns>The created <see cref="RegistrationRequest"/>.</returns>
|
||||
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()
|
||||
);
|
||||
}
|
||||
}
|
||||
+139
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SetupApplicationEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetupApplicationEndpointTests
|
||||
{
|
||||
private readonly ISender _mockSender;
|
||||
private readonly SetupApplicationEndpoint _sut;
|
||||
private readonly RegistrationRequestFixture _registrationRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetupApplicationEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public SetupApplicationEndpointTests()
|
||||
{
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<SetupApplicationEndpoint>(_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<SetupApplicationCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Created<RegistrationResponse> createdResult = result.Should().BeOfType<Created<RegistrationResponse>>().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<SetupApplicationCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status409Conflict);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<Microsoft.AspNetCore.Mvc.ProblemDetails>();
|
||||
|
||||
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<SetupApplicationCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123")));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(
|
||||
Arg.Is<SetupApplicationCommand>(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<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<SetupApplicationCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<RegistrationResponse>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123"));
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+140
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ChangePasswordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordEndpointTests
|
||||
{
|
||||
private readonly ISender _mockSender;
|
||||
private readonly ChangePasswordEndpoint _sut;
|
||||
private readonly ChangePasswordRequestFixture _changePasswordRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ChangePasswordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ChangePasswordEndpointTests()
|
||||
{
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<ChangePasswordEndpoint>(_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<ChangePasswordCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<ChangePasswordResponse> okResult = result.Should().BeOfType<Ok<ChangePasswordResponse>>().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<ChangePasswordCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
|
||||
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<ChangePasswordCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(new ChangePasswordResponse(true)));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(
|
||||
Arg.Is<ChangePasswordCommand>(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<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<ChangePasswordCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<ChangePasswordResponse>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(new ChangePasswordResponse(true));
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+39
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ChangePasswordRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="ChangePasswordRequest"/> with default or random values.
|
||||
/// </summary>
|
||||
/// <param name="username">The username for the password change.</param>
|
||||
/// <param name="currentPassword">The current password.</param>
|
||||
/// <param name="newPassword">The new password.</param>
|
||||
/// <param name="newPasswordConfirm">The new password confirmation.</param>
|
||||
/// <returns>The created <see cref="ChangePasswordRequest"/>.</returns>
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
+35
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="LoginRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="LoginRequest"/> with default or random values.
|
||||
/// </summary>
|
||||
/// <param name="username">The username for login.</param>
|
||||
/// <param name="password">The password for login.</param>
|
||||
/// <param name="totpCode">The TOTP code for two-factor authentication.</param>
|
||||
/// <returns>The created <see cref="LoginRequest"/>.</returns>
|
||||
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()
|
||||
);
|
||||
}
|
||||
}
|
||||
+139
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LoginEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginEndpointTests
|
||||
{
|
||||
private readonly ISender _mockSender;
|
||||
private readonly LoginEndpoint _sut;
|
||||
private readonly LoginRequestFixture _loginRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public LoginEndpointTests()
|
||||
{
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<LoginEndpoint>(_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<LoginUserQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<LoginResponse> okResult = result.Should().BeOfType<Ok<LoginResponse>>().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<LoginUserQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
|
||||
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<LoginUserQuery>(), Arg.Any<CancellationToken>())
|
||||
.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<LoginUserQuery>(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<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<LoginUserQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<LoginResponse>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(new LoginResponse(Guid.NewGuid(), "testUser", "jwt_token", true));
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+32
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RecoverPasswordRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="RecoverPasswordRequest"/> with default or random values.
|
||||
/// </summary>
|
||||
/// <param name="username">The username for password recovery.</param>
|
||||
/// <param name="totpCode">The TOTP code for verification.</param>
|
||||
/// <returns>The created <see cref="RecoverPasswordRequest"/>.</returns>
|
||||
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()
|
||||
);
|
||||
}
|
||||
}
|
||||
+138
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RecoverPasswordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordEndpointTests
|
||||
{
|
||||
private readonly ISender _mockSender;
|
||||
private readonly RecoverPasswordEndpoint _sut;
|
||||
private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RecoverPasswordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public RecoverPasswordEndpointTests()
|
||||
{
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<RecoverPasswordEndpoint>(_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<RecoverPasswordCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<RecoverPasswordResponse> okResult = result.Should().BeOfType<Ok<RecoverPasswordResponse>>().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<RecoverPasswordCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
|
||||
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<RecoverPasswordCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(new RecoverPasswordResponse(true)));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(
|
||||
Arg.Is<RecoverPasswordCommand>(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<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<RecoverPasswordCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<RecoverPasswordResponse>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(new RecoverPasswordResponse(true));
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+39
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RegistrationRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegistrationRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="RegistrationRequest"/> with default or random values.
|
||||
/// </summary>
|
||||
/// <param name="username">The username for registration.</param>
|
||||
/// <param name="password">The password for registration.</param>
|
||||
/// <param name="passwordConfirm">The password confirmation.</param>
|
||||
/// <param name="use2fa">Whether to use two-factor authentication.</param>
|
||||
/// <returns>The created <see cref="RegistrationRequest"/>.</returns>
|
||||
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()
|
||||
);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user