From 0e3e688eb793f9e07fafd457335f2ac8fc2c3fe4 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 5 Oct 2024 09:35:10 +0300 Subject: [PATCH] Adds Application layer unit tests for file system browser dialog --- .../FileManagement/DirectoryMappingConfig.cs | 6 +- .../FileSystemTreeMappingConfig.cs | 31 +- .../GetDirectoriesQueryHandler.cs | 12 +- .../GetTreeDirectoriesQueryHandler.cs | 12 +- .../GetDrives/GetDrivesQueryHandler.cs | 12 +- .../GetFileSystemQuery.cs | 6 +- .../GetFileSystemQueryHandler.cs | 6 +- .../Queries/GetFiles/GetFilesQueryHandler.cs | 12 +- .../GetTreeFiles/GetTreeFilesQueryHandler.cs | 12 +- .../SplitPath/SplitPathCommandHandler.cs | 13 +- .../GetPathParentQueryHandler.cs | 13 +- .../GetPathRoot/GetPathRootQueryHandler.cs | 13 +- .../GetThumbnail/GetThumbnailQueryHandler.cs | 9 +- .../FileManagement/SplitPathResponse.cs | 14 - .../Strategies/Path/UnixPathStrategy.cs | 13 +- .../Strategies/Path/WindowsPathStrategy.cs | 17 +- .../ValueObjects/PathSegment.cs | 24 +- .../FileManagement/FileSystemController.cs | 2 +- .../Fixtures/ValidationBehaviorFixture.cs | 16 + .../ValidationBehaviorTestResponse.cs | 13 + .../Behaviors/ValidationBehaviorTests.cs | 106 +++++ .../OptionalJsonConverterFactoryFixture.cs | 13 + .../OptionalJsonConverterFactoryTests.cs | 117 ++++++ .../Converters/OptionalJsonConverterTests.cs | 142 +++++++ .../DirectoryMappingConfigTests.cs | 119 ++++++ .../FileManagement/FileMappingConfigTests.cs | 95 +++++ .../FileSystemTreeMappingConfigTests.cs | 164 ++++++++ .../PathSegmentMappingConfigTests.cs | 94 +++++ .../ThumbnailMappingConfigTests.cs | 115 +++++ .../Directories/Fixtures/DirectoryFixture.cs | 109 +++++ .../Fixtures/DirectoryResponseFixture.cs | 50 +++ .../Fixtures/FileSystemItemModelFixture.cs | 46 ++ .../FileSystemTreeNodeResponseFixture.cs | 62 +++ .../Fixtures/GetDirectoriesQueryFixture.cs | 32 ++ .../GetDirectoriesQueryHandlerTests.cs | 153 +++++++ .../GetDirectoriesQueryValidatorTests.cs | 119 ++++++ .../Fixtures/GetDirectoryTreeQueryFixture.cs | 35 ++ .../GetDirectoryTreeQueryHandlerTests.cs | 393 ++++++++++++++++++ .../GetDirectoryTreeQueryValidatorTests.cs | 147 +++++++ .../GetTreeDirectoriesQueryFixture.cs | 32 ++ .../GetTreeDirectoriesQueryHandlerTests.cs | 174 ++++++++ .../GetTreeDirectoriesQueryValidatorTests.cs | 119 ++++++ .../Fixtures/GetDrivesQueryFixture.cs | 62 +++ .../GetDrives/GetDrivesQueryHandlerTests.cs | 123 ++++++ .../GetFileSystemQueryHandlerTests.cs | 114 +++++ .../Files/Fixtures/FileFixture.cs | 88 ++++ .../Files/Fixtures/FileResponseFixture.cs | 47 +++ .../GetFiles/Fixtures/GetFilesQueryFixture.cs | 32 ++ .../GetFiles/GetFilesQueryHandlerTests.cs | 149 +++++++ .../GetFiles/GetFilesQueryValidatorTests.cs | 119 ++++++ .../Fixtures/GetTreeFilesQueryFixture.cs | 32 ++ .../GetTreeFilesQueryHandlerTests.cs | 143 +++++++ .../GetTreeFilesQueryValidatorTests.cs | 119 ++++++ .../CombinePathCommandHandlerTests.cs | 99 +++++ .../CombinePathCommandValidatorTests.cs | 137 ++++++ .../Fixtures/CombinePathCommandFixture.cs | 31 ++ .../Fixtures/SplitPathCommandFixture.cs | 29 ++ .../SplitPath/SplitPathCommandHandlerTests.cs | 130 ++++++ .../SplitPathCommandValidatorTests.cs | 91 ++++ .../Pahs/Fixtures/PathSegmentFixture.cs | 64 +++ .../Fixtures/PathSegmentResponseFixture.cs | 41 ++ .../Fixtures/PathSeparatorResponseFixture.cs | 41 ++ .../CheckPathExistsQueryHandlerTests.cs | 99 +++++ .../CheckPathExistsQueryValidatorTests.cs | 91 ++++ .../Fixtures/CheckPathExistsQueryFixture.cs | 29 ++ .../Fixtures/GetPathParentQueryFixture.cs | 29 ++ .../GetPathParentQueryHandlerTests.cs | 118 ++++++ .../GetPathParentQueryValidatorTests.cs | 91 ++++ .../Fixtures/GetPathRootQueryFixture.cs | 29 ++ .../GetPathRootQueryHandlerTests.cs | 119 ++++++ .../GetPathRootQueryValidatorTests.cs | 91 ++++ .../GetPathSeparatorQueryHandlerTests.cs | 105 +++++ .../Fixtures/ValidatePathQueryFixure.cs | 29 ++ .../ValidatePathQueryHandlerTests.cs | 98 +++++ .../ValidatePathQueryValidatorTests.cs | 91 ++++ .../Fixtures/ThumbnailResponseFixture.cs | 32 ++ .../Fixtures/GetThumbnailQueryFixture.cs | 31 ++ .../GetThumbnailQueryHandlerTests.cs | 104 +++++ .../AddBook/AddBookCommandValidatorTests.cs | 6 +- 79 files changed, 5484 insertions(+), 91 deletions(-) rename src/Lumina.Application/Core/FileManagement/FileSystem/Queries/{GetFileSysem => GetFileSystem}/GetFileSystemQuery.cs (58%) rename src/Lumina.Application/Core/FileManagement/FileSystem/Queries/{GetFileSysem => GetFileSystem}/GetFileSystemQueryHandler.cs (91%) delete mode 100644 src/Lumina.Contracts/Responses/FileManagement/SplitPathResponse.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/Fixtures/ValidationBehaviorFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/Fixtures/ValidationBehaviorTestResponse.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/ValidationBehaviorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/Fixtures/OptionalJsonConverterFactoryFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterFactoryTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/DirectoryMappingConfigTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileMappingConfigTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileSystemTreeMappingConfigTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/PathSegmentMappingConfigTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/ThumbnailMappingConfigTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryResponseFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/FileSystemItemModelFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/FileSystemTreeNodeResponseFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/Fixtures/GetDirectoriesQueryFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/Fixtures/GetDirectoryTreeQueryFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/Fixtures/GetTreeDirectoriesQueryFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Drives/Queries/GetDrives/Fixtures/GetDrivesQueryFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Fixtures/FileFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Fixtures/FileResponseFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/Fixtures/GetFilesQueryFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/Fixtures/GetTreeFilesQueryFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/Fixtures/CombinePathCommandFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/Fixtures/SplitPathCommandFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSegmentFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSegmentResponseFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSeparatorResponseFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/Fixtures/CheckPathExistsQueryFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/Fixtures/GetPathParentQueryFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/Fixtures/GetPathRootQueryFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/Fixtures/ValidatePathQueryFixure.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Fixtures/ThumbnailResponseFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/Fixtures/GetThumbnailQueryFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs diff --git a/src/Lumina.Application/Common/Mapping/FileManagement/DirectoryMappingConfig.cs b/src/Lumina.Application/Common/Mapping/FileManagement/DirectoryMappingConfig.cs index 847bf78b..8bf54f3b 100644 --- a/src/Lumina.Application/Common/Mapping/FileManagement/DirectoryMappingConfig.cs +++ b/src/Lumina.Application/Common/Mapping/FileManagement/DirectoryMappingConfig.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Models.FileManagement; using Lumina.Contracts.Responses.FileManagement; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; @@ -28,7 +28,7 @@ public class DirectoryMappingConfig : IRegister .Map(dest => dest.ItemType, src => src.Type) .Map(dest => dest.IsExpanded, () => false) .Map(dest => dest.ChildrenLoaded, () => false) - .Map(dest => dest.Children, src => src.Items) + .Map(dest => dest.Children, src => src.Items.Adapt>()) .MapToConstructor(true); config.NewConfig() @@ -49,4 +49,4 @@ public class DirectoryMappingConfig : IRegister )); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Common/Mapping/FileManagement/FileSystemTreeMappingConfig.cs b/src/Lumina.Application/Common/Mapping/FileManagement/FileSystemTreeMappingConfig.cs index 39d715e1..f3219930 100644 --- a/src/Lumina.Application/Common/Mapping/FileManagement/FileSystemTreeMappingConfig.cs +++ b/src/Lumina.Application/Common/Mapping/FileManagement/FileSystemTreeMappingConfig.cs @@ -1,10 +1,11 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Enums.FileSystem; using Lumina.Contracts.Responses.FileManagement; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; using Mapster; using System.Collections.Generic; +using System.Linq; #endregion namespace Lumina.Application.Common.Mapping.FileManagement; @@ -38,7 +39,9 @@ public class FileSystemTreeMappingConfig : IRegister .Map(dest => dest.Path, src => src.Id.Path) .Map(dest => dest.Name, src => src.Name) .Map(dest => dest.ItemType, src => FileSystemItemType.Root) - .Map(dest => dest.IsExpanded, () => false); + .Map(dest => dest.IsExpanded, () => false) + .Map(dest => dest.ChildrenLoaded, () => false) + .Map(dest => dest.Children, src => src.Items.Select(item => item.Adapt(config)).ToList()); config.NewConfig() .MapWith(src => UnixRootItem.Create( @@ -46,15 +49,19 @@ public class FileSystemTreeMappingConfig : IRegister .Value); config.NewConfig() - .MapWith(src => new FileSystemTreeNodeResponse - { - Path = src.Id.Path, - Name = src.Name, - ItemType = src.Type, - IsExpanded = false, - ChildrenLoaded = false, - Children = new List() - }); + .Map(dest => dest.Name, src => src.Name) + .Map(dest => dest.Path, src => src.Id.Path) + .Map(dest => dest.ItemType, src => src.Type) + .Map(dest => dest.IsExpanded, _ => false) + .Map(dest => dest.ChildrenLoaded, _ => false) + .Map(dest => dest.ChildrenLoaded, _ => false) + .AfterMapping((src, dest) => + { + if (src is Directory dir) + dest.Children = dir.Items.Select(item => item.Adapt(config)).ToList(); + else + dest.Children = []; + }); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs index 4c5c3360..c78ffd6c 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs @@ -1,9 +1,10 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Contracts.Responses.FileManagement; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Mapster; +using MapsterMapper; using Mediator; using System.Collections.Generic; using System.Threading; @@ -19,6 +20,7 @@ public class GetDirectoriesQueryHandler : IRequestHandler class. /// /// Injected service for handling directories. - public GetDirectoriesQueryHandler(IDirectoryService directoryService) + /// Injected service for mapping objects. + public GetDirectoriesQueryHandler(IDirectoryService directoryService, IMapper mapper) { _directoryService = directoryService; + _mapper = mapper; } #endregion @@ -44,7 +48,7 @@ public class GetDirectoriesQueryHandler : IRequestHandler>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken) { ErrorOr> result = _directoryService.GetSubdirectories(request.Path, request.IncludeHiddenElements); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map>(values)), errors => errors)); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs index 9b63122a..029f9a58 100644 --- a/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs @@ -1,9 +1,10 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Contracts.Responses.FileManagement; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Mapster; +using MapsterMapper; using Mediator; using System.Collections.Generic; using System.Threading; @@ -19,6 +20,7 @@ public class GetTreeDirectoriesQueryHandler : IRequestHandler class. /// /// Injected service for handling directories. - public GetTreeDirectoriesQueryHandler(IDirectoryService directoryService) + /// Injected service for mapping objects. + public GetTreeDirectoriesQueryHandler(IDirectoryService directoryService, IMapper mapper) { _directoryService = directoryService; + _mapper = mapper; } #endregion @@ -44,7 +48,7 @@ public class GetTreeDirectoriesQueryHandler : IRequestHandler>> Handle(GetTreeDirectoriesQuery request, CancellationToken cancellationToken) { ErrorOr> result = _directoryService.GetSubdirectories(request.Path, request.IncludeHiddenElements); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map>(values)), errors => errors)); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs index e8b1bbdc..b7946e4e 100644 --- a/src/Lumina.Application/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandler.cs @@ -1,9 +1,10 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Contracts.Responses.FileManagement; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Mapster; +using MapsterMapper; using Mediator; using System.Collections.Generic; using System.Threading; @@ -19,6 +20,7 @@ public class GetDrivesQueryHandler : IRequestHandler class. /// /// Injected service for handling file system drives. - public GetDrivesQueryHandler(IDriveService driveService) + /// Injected service for mapping objects. + public GetDrivesQueryHandler(IDriveService driveService, IMapper mapper) { _driveService = driveService; + _mapper = mapper; } #endregion @@ -44,7 +48,7 @@ public class GetDrivesQueryHandler : IRequestHandler>> Handle(GetDrivesQuery request, CancellationToken cancellationToken) { ErrorOr> result = _driveService.GetDrives(); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.Adapt>()), errors => errors)); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map>(values)), errors => errors)); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSysem/GetFileSystemQuery.cs b/src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQuery.cs similarity index 58% rename from src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSysem/GetFileSystemQuery.cs rename to src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQuery.cs index ce0b47e7..e4356d59 100644 --- a/src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSysem/GetFileSystemQuery.cs +++ b/src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQuery.cs @@ -1,11 +1,11 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Responses.FileManagement; using Mediator; #endregion -namespace Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSysem; +namespace Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSystem; /// /// Query for retrieving the file system type. /// -public record GetFileSystemQuery() : IRequest; \ No newline at end of file +public record GetFileSystemQuery() : IRequest; diff --git a/src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSysem/GetFileSystemQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandler.cs similarity index 91% rename from src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSysem/GetFileSystemQueryHandler.cs rename to src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandler.cs index 7bbd5cb1..2b5ac815 100644 --- a/src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSysem/GetFileSystemQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandler.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Responses.FileManagement; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; using Mediator; @@ -6,7 +6,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSysem; +namespace Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSystem; /// /// Handler for the query to get the file system type. @@ -40,4 +40,4 @@ public class GetFileSystemQueryHandler : IRequestHandler class. /// /// Injected service for handling files. - public GetFilesQueryHandler(IFileService fileService) + /// Injected service for mapping objects. + public GetFilesQueryHandler(IFileService fileService, IMapper mapper) { _fileService = fileService; + _mapper = mapper; } #endregion @@ -44,7 +48,7 @@ public class GetFilesQueryHandler : IRequestHandler>> Handle(GetFilesQuery request, CancellationToken cancellationToken) { ErrorOr> result = _fileService.GetFiles(request.Path, request.IncludeHiddenElements); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map>(values)), errors => errors)); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs index 7d822f64..09d3c486 100644 --- a/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs @@ -1,9 +1,10 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Contracts.Responses.FileManagement; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Mapster; +using MapsterMapper; using Mediator; using System.Collections.Generic; using System.Threading; @@ -19,6 +20,7 @@ public class GetTreeFilesQueryHandler : IRequestHandler class. /// /// Injected service for handling files. - public GetTreeFilesQueryHandler(IFileService fileService) + /// Injected service for mapping objects. + public GetTreeFilesQueryHandler(IFileService fileService, IMapper mapper) { _fileService = fileService; + _mapper = mapper; } #endregion @@ -44,7 +48,7 @@ public class GetTreeFilesQueryHandler : IRequestHandler>> Handle(GetTreeFilesQuery request, CancellationToken cancellationToken) { ErrorOr> result = _fileService.GetFiles(request.Path, request.IncludeHiddenElements); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map>(values)), errors => errors)); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs b/src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs index d2ad4bbd..b25c0a0f 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Paths/Commands/SplitPath/SplitPathCommandHandler.cs @@ -1,9 +1,9 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Contracts.Responses.FileManagement; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Mapster; +using MapsterMapper; using Mediator; using System.Collections.Generic; using System.Threading; @@ -19,6 +19,7 @@ public class SplitPathCommandHandler : IRequestHandler class. /// /// Injected service for handling file system paths. - public SplitPathCommandHandler(IPathService pathService) + /// Injected service for mapping objects. + public SplitPathCommandHandler(IPathService pathService, IMapper mapper) { _pathService = pathService; + _mapper = mapper; } #endregion @@ -44,7 +47,7 @@ public class SplitPathCommandHandler : IRequestHandler>> Handle(SplitPathCommand request, CancellationToken cancellationToken) { ErrorOr> result = _pathService.ParsePath(request.Path); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map>(values)), errors => errors)); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs index dbd7f8b7..f0b0ee24 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandler.cs @@ -1,9 +1,9 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Contracts.Responses.FileManagement; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Mapster; +using MapsterMapper; using Mediator; using System.Collections.Generic; using System.Threading; @@ -19,6 +19,7 @@ public class GetPathParentQueryHandler : IRequestHandler class. /// /// Injected service for managing file system paths. - public GetPathParentQueryHandler(IPathService pathService) + /// Injected service for mapping objects. + public GetPathParentQueryHandler(IPathService pathService, IMapper mapper) { _pathService = pathService; + _mapper = mapper; } #endregion @@ -44,7 +47,7 @@ public class GetPathParentQueryHandler : IRequestHandler>> Handle(GetPathParentQuery request, CancellationToken cancellationToken) { ErrorOr> result = _pathService.GoUpOneLevel(request.Path); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt>()), errors => errors)); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map>(values)), errors => errors)); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs index b08dba31..f5dd1050 100644 --- a/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Paths/Queries/GetPathRoot/GetPathRootQueryHandler.cs @@ -1,9 +1,9 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using ErrorOr; using Lumina.Contracts.Responses.FileManagement; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Mapster; +using MapsterMapper; using Mediator; using System.Threading; using System.Threading.Tasks; @@ -18,6 +18,7 @@ public class GetPathRootQueryHandler : IRequestHandler class. /// /// Injected service for managing file system paths. - public GetPathRootQueryHandler(IPathService pathService) + /// Injected service for mapping objects. + public GetPathRootQueryHandler(IPathService pathService, IMapper mapper) { _pathService = pathService; + _mapper = mapper; } #endregion @@ -41,7 +44,7 @@ public class GetPathRootQueryHandler : IRequestHandler> Handle(GetPathRootQuery request, CancellationToken cancellationToken) { ErrorOr result = _pathService.GetPathRoot(request.Path); - return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt()), errors => errors)); + return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map(values)), errors => errors)); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs b/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs index c43e0f79..53541a68 100644 --- a/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs +++ b/src/Lumina.Application/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandler.cs @@ -3,7 +3,7 @@ using ErrorOr; using Lumina.Contracts.Responses.FileManagement; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; -using Mapster; +using MapsterMapper; using Mediator; using System.Threading; using System.Threading.Tasks; @@ -18,6 +18,7 @@ public class GetThumbnailQueryHandler : IRequestHandler class. /// /// Injected service for handling thumbnails. - public GetThumbnailQueryHandler(IThumbnailService thumbnailsService) + /// Injected service for mapping objects. + public GetThumbnailQueryHandler(IThumbnailService thumbnailsService, IMapper mapper) { _thumbnailsService = thumbnailsService; + _mapper = mapper; } #endregion @@ -41,7 +44,7 @@ public class GetThumbnailQueryHandler : IRequestHandler> Handle(GetThumbnailQuery request, CancellationToken cancellationToken) { ErrorOr result = await _thumbnailsService.GetThumbnailAsync(request.Path, request.Quality, cancellationToken); - return await ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt()), errors => errors)); + return await ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map(values)), errors => errors)); } #endregion } diff --git a/src/Lumina.Contracts/Responses/FileManagement/SplitPathResponse.cs b/src/Lumina.Contracts/Responses/FileManagement/SplitPathResponse.cs deleted file mode 100644 index 2416699c..00000000 --- a/src/Lumina.Contracts/Responses/FileManagement/SplitPathResponse.cs +++ /dev/null @@ -1,14 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Responses.FileManagement; - -/// -/// Represents a response containing the result of splitting a file system path. -/// -/// The returned path segments. -[DebuggerDisplay("{PathSegments}")] -public record SplitPathResponse( - string[] PathSegments -); \ No newline at end of file diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs index b69d2e2a..e24aca81 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/UnixPathStrategy.cs @@ -94,16 +94,19 @@ public class UnixPathStrategy : IUnixPathStrategy return Errors.FileManagement.InvalidPath; // get the path segments List splitSegments = [.. path.Path.Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries)]; - IEnumerable segments = splitSegments.Select((segment, index) => + IEnumerable> segmentsResults = splitSegments.Select((segment, index) => { bool isDirectory; if (segment.Contains('.')) isDirectory = index != splitSegments.Count - 1 || path.Path.EndsWith(PathSeparator); // check if it's the last segment or if the path ends with a '/' else isDirectory = true; - return new PathSegment(segment, isDirectory, isDrive: false); - }).Prepend(new PathSegment(PathSeparator.ToString(), isDirectory: false, isDrive: true)); // UNIX paths have '/' as "root drive" - return ErrorOrFactory.From(segments); + return PathSegment.Create(segment, isDirectory, isDrive: false); + }).Prepend(PathSegment.Create(PathSeparator.ToString(), isDirectory: false, isDrive: true)); // UNIX paths have '/' as "root drive" + foreach (ErrorOr segment in segmentsResults) + if (segment.IsError) + return segment.Errors; + return ErrorOrFactory.From(segmentsResults.Select(segmentResult => segmentResult.Value)); } /// @@ -153,7 +156,7 @@ public class UnixPathStrategy : IUnixPathStrategy // On Unix-like systems, the root is always "/" if (path.Path.StartsWith(PathSeparator)) - return new PathSegment(PathSeparator.ToString(), isDirectory: false, isDrive: true); + return PathSegment.Create(PathSeparator.ToString(), isDirectory: false, isDrive: true); return Errors.FileManagement.InvalidPath; } #endregion diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs index 78981aeb..bb375722 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs @@ -4,6 +4,7 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO.Abstractions; using System.Linq; using System.Text.RegularExpressions; @@ -91,11 +92,15 @@ public class WindowsPathStrategy : IWindowsPathStrategy // Windows paths usually start with a drive letter and colon, e.g., "C:" if (!path.Path.Contains(':') || !path.Path.Contains(PathSeparator) || !char.IsLetter(path.Path[0]) || path.Path[1] != ':' || path.Path[2] != PathSeparator) return Errors.FileManagement.InvalidPath; - return ErrorOrFactory.From(GetPathSegments()); - IEnumerable GetPathSegments() + IEnumerable> getPathSegmentsResults = GetPathSegments(); + foreach (ErrorOr getPathSegmentsResult in getPathSegmentsResults) + if (getPathSegmentsResult.IsError) + return getPathSegmentsResult.Errors; + return ErrorOrFactory.From(getPathSegmentsResults.Select(getPathSegmentsResult => getPathSegmentsResult.Value)); + IEnumerable> GetPathSegments() { // the drive segment - yield return new PathSegment(path.Path[..2], isDirectory: false, isDrive: true); + yield return PathSegment.Create(path.Path[..2], isDirectory: false, isDrive: true); // extract the other segments string[] segments = path.Path[3..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < segments.Length; i++) @@ -106,7 +111,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy isDirectory = i != segments.Length - 1 || path.Path.EndsWith(PathSeparator); // check if it's the last segment or if the next segment also contains a path delimiter else isDirectory = true; - yield return new PathSegment(segment, isDirectory, isDrive: false); + yield return PathSegment.Create(segment, isDirectory, isDrive: false); } } } @@ -164,7 +169,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy string root = path.Path[..2]; if (path.Path.Length > 2 && path.Path[2] == PathSeparator) root += PathSeparator; - return new PathSegment(root, isDirectory: true, isDrive: true); + return PathSegment.Create(root, isDirectory: true, isDrive: true); } // check for UNC paths (e.g., "\\server\share") if (path.Path.StartsWith('\\')) @@ -177,7 +182,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy if (segments.Count >= 2) { string root = $@"\\{segments[0].Name}\{segments[1].Name}\"; - return new PathSegment(root, isDirectory: true, isDrive: false); + return PathSegment.Create(root, isDirectory: true, isDrive: false); } } return Errors.FileManagement.InvalidPath; diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/PathSegment.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/PathSegment.cs index d8e3d326..d14b5717 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/PathSegment.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/PathSegment.cs @@ -1,4 +1,6 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using System.Collections.Generic; using System.Diagnostics; @@ -36,7 +38,7 @@ public class PathSegment : ValueObject /// The name of the path segment. /// Value indicating if the current path segment is a file system directory or not. /// Value indicating if the current path segment is a file system drive or not. - public PathSegment(string name, bool isDirectory, bool isDrive) + private PathSegment(string name, bool isDirectory, bool isDrive) { Name = name; IsDirectory = isDirectory; @@ -45,6 +47,22 @@ public class PathSegment : ValueObject #endregion #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a new instance of the class. + /// + /// The name of the path segment. + /// Value indicating if the current path segment is a file system directory or not. + /// Value indicating if the current path segment is a file system drive or not. + /// + /// An containing either a successfully created or an error message. + /// + public static ErrorOr Create(string name, bool isDirectory, bool isDrive) + { + if (string.IsNullOrWhiteSpace(name)) + return Errors.FileManagement.NameCannotBeEmpty; + return new PathSegment(name, isDirectory, isDrive); + } + /// public override IEnumerable GetEqualityComponents() { @@ -53,4 +71,4 @@ public class PathSegment : ValueObject yield return IsDrive; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FileSystemController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FileSystemController.cs index b8eb2a8a..b7050380 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FileSystemController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FileSystemController.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSysem; +using Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSystem; using Lumina.Contracts.Responses.FileManagement; using Lumina.Presentation.Api.Core.Controllers.Common; using Mediator; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/Fixtures/ValidationBehaviorFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/Fixtures/ValidationBehaviorFixture.cs new file mode 100644 index 00000000..3fc074bd --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/Fixtures/ValidationBehaviorFixture.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Mediator; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Behaviors.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidationBehaviorFixture : IRequest> +{ + +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/Fixtures/ValidationBehaviorTestResponse.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/Fixtures/ValidationBehaviorTestResponse.cs new file mode 100644 index 00000000..bd3f7b13 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/Fixtures/ValidationBehaviorTestResponse.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Behaviors.Fixtures; + +/// +/// Fixture test class for validation behavior responses. +/// +[ExcludeFromCodeCoverage] +public class ValidationBehaviorTestResponse +{ +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/ValidationBehaviorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/ValidationBehaviorTests.cs new file mode 100644 index 00000000..c0d06549 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Behaviors/ValidationBehaviorTests.cs @@ -0,0 +1,106 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using FluentValidation; +using FluentValidation.Results; +using Lumina.Application.Common.Behaviors; +using Lumina.Application.UnitTests.Common.Behaviors.Fixtures; +using Mediator; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Common.Behaviors; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidationBehaviorTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IValidator _mockValidator; + private readonly MessageHandlerDelegate> _nextDelegate; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public ValidationBehaviorTests() + { + _mockValidator = Substitute.For>(); + _nextDelegate = Substitute.For>>(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task Handle_WhenValidatorIsNull_ShouldInvokeNextDelegate() + { + // Arrange + ValidationBehavior> behavior = new(); + ValidationBehaviorFixture request = new(); + ValidationBehaviorTestResponse expectedResponse = new(); + _nextDelegate.Invoke(request, Arg.Any()).Returns(new ValueTask>(ErrorOrFactory.From(expectedResponse))); + + // Act + ErrorOr result = await behavior.Handle(request, CancellationToken.None, _nextDelegate); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(expectedResponse); + await _nextDelegate.Received(1).Invoke(request, Arg.Any()); + } + + [Fact] + public async Task Handle_WhenValidationSucceeds_ShouldInvokeNextDelegate() + { + // Arrange + ValidationBehavior> behavior = new(_mockValidator); + ValidationBehaviorFixture request = new(); + ValidationBehaviorTestResponse expectedResponse = new(); + _mockValidator.ValidateAsync(request, Arg.Any()).Returns(new ValidationResult()); + _nextDelegate.Invoke(request, Arg.Any()).Returns(new ValueTask>(ErrorOrFactory.From(expectedResponse))); + + // Act + ErrorOr result = await behavior.Handle(request, CancellationToken.None, _nextDelegate); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(expectedResponse); + await _mockValidator.Received(1).ValidateAsync(request, Arg.Any()); + await _nextDelegate.Received(1).Invoke(request, Arg.Any()); + } + + [Fact] + public async Task Handle_WhenValidationFails_ShouldReturnErrors() + { + // Arrange + ValidationBehavior> behavior = new(_mockValidator); + ValidationBehaviorFixture request = new(); + List validationFailures = + [ + new ValidationFailure("Property1", "Error message 1"), + new ValidationFailure("Property2", "Error message 2") + ]; + _mockValidator.ValidateAsync(request, Arg.Any()).Returns(new ValidationResult(validationFailures)); + + // Act + ErrorOr result = await behavior.Handle(request, CancellationToken.None, _nextDelegate); + + // Assert + result.IsError.Should().BeTrue(); + result.Errors.Should().HaveCount(2); + result.Errors[0].Type.Should().Be(ErrorType.Validation); + result.Errors[0].Description.Should().Be("Error message 1"); + result.Errors[1].Type.Should().Be(ErrorType.Validation); + result.Errors[1].Description.Should().Be("Error message 2"); + await _mockValidator.Received(1).ValidateAsync(request, Arg.Any()); + await _nextDelegate.DidNotReceive().Invoke(request, Arg.Any()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/Fixtures/OptionalJsonConverterFactoryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/Fixtures/OptionalJsonConverterFactoryFixture.cs new file mode 100644 index 00000000..e4f39081 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/Fixtures/OptionalJsonConverterFactoryFixture.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Converters.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class OptionalJsonConverterFactoryFixture +{ +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterFactoryTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterFactoryTests.cs new file mode 100644 index 00000000..5edfcce1 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterFactoryTests.cs @@ -0,0 +1,117 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Converters; +using Lumina.Application.UnitTests.Common.Converters.Fixtures; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Application.UnitTests.Common.Converters; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class OptionalJsonConverterFactoryTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly OptionalJsonConverterFactory _factory; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public OptionalJsonConverterFactoryTests() + { + _factory = new OptionalJsonConverterFactory(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void CanConvert_WhenTypeIsOptional_ShouldReturnTrue() + { + // Arrange + Type typeToConvert = typeof(Optional); + + // Act + bool result = _factory.CanConvert(typeToConvert); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void CanConvert_WhenTypeIsNotOptional_ShouldReturnFalse() + { + // Arrange + Type typeToConvert = typeof(string); + + // Act + bool result = _factory.CanConvert(typeToConvert); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void CanConvert_WhenTypeIsGenericButNotOptional_ShouldReturnFalse() + { + // Arrange + Type typeToConvert = typeof(List); + + // Act + bool result = _factory.CanConvert(typeToConvert); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void CreateConverter_WhenTypeIsOptionalString_ShouldReturnCorrectConverterType() + { + // Arrange + Type typeToConvert = typeof(Optional); + JsonSerializerOptions options = new(); + + // Act + JsonConverter converter = _factory.CreateConverter(typeToConvert, options); + + // Assert + converter.Should().BeOfType>(); + } + + [Fact] + public void CreateConverter_WhenTypeIsOptionalInt_ShouldReturnCorrectConverterType() + { + // Arrange + Type typeToConvert = typeof(Optional); + JsonSerializerOptions options = new(); + + // Act + JsonConverter converter = _factory.CreateConverter(typeToConvert, options); + + // Assert + converter.Should().BeOfType>(); + } + + [Fact] + public void CreateConverter_WhenTypeIsOptionalCustomClass_ShouldReturnCorrectConverterType() + { + // Arrange + Type typeToConvert = typeof(Optional); + JsonSerializerOptions options = new(); + + // Act + JsonConverter converter = _factory.CreateConverter(typeToConvert, options); + + // Assert + converter.Should().BeOfType>(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterTests.cs new file mode 100644 index 00000000..e9846124 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Converters/OptionalJsonConverterTests.cs @@ -0,0 +1,142 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Converters; +using Lumina.Domain.Common.Primitives; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Application.UnitTests.Common.Converters; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class OptionalJsonConverterTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly JsonSerializerOptions _options; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public OptionalJsonConverterTests() + { + _options = new JsonSerializerOptions(); + _options.Converters.Add(new OptionalJsonConverter()); + _options.Converters.Add(new OptionalJsonConverter()); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Read_WhenJsonIsNull_ShouldReturnNone() + { + // Arrange + string json = "null"; + + // Act + Optional result = JsonSerializer.Deserialize>(json, _options); + + // Assert + result.HasValue.Should().BeFalse(); + } + + [Fact] + public void Read_WhenJsonHasStringValue_ShouldReturnSomeWithCorrectValue() + { + // Arrange + string json = "\"test\""; + + // Act + Optional result = JsonSerializer.Deserialize>(json, _options); + + // Assert + result.HasValue.Should().BeTrue(); + result.Value.Should().Be("test"); + } + + [Fact] + public void Read_WhenJsonHasIntValue_ShouldReturnSomeWithCorrectValue() + { + // Arrange + string json = "42"; + + // Act + Optional result = JsonSerializer.Deserialize>(json, _options); + + // Assert + result.HasValue.Should().BeTrue(); + result.Value.Should().Be(42); + } + + [Fact] + public void Write_WhenOptionalHasNoValue_ShouldWriteNull() + { + // Arrange + Optional optional = Optional.None(); + + // Act + string json = JsonSerializer.Serialize(optional, _options); + + // Assert + json.Should().Be("null"); + } + + [Fact] + public void Write_WhenOptionalHasStringValue_ShouldWriteCorrectJson() + { + // Arrange + Optional optional = Optional.Some("test"); + + // Act + string json = JsonSerializer.Serialize(optional, _options); + + // Assert + json.Should().Be("\"test\""); + } + + [Fact] + public void Write_WhenOptionalHasIntValue_ShouldWriteCorrectJson() + { + // Arrange + Optional optional = Optional.Some(42); + + // Act + string json = JsonSerializer.Serialize(optional, _options); + + // Assert + json.Should().Be("42"); + } + + [Fact] + public void ReadWrite_WhenSerializingAndDeserializingSomeValue_ShouldPreserveValue() + { + // Arrange + Optional original = Optional.Some("test"); + + // Act + string json = JsonSerializer.Serialize(original, _options); + Optional deserialized = JsonSerializer.Deserialize>(json, _options); + + // Assert + deserialized.Should().Be(original); + } + + [Fact] + public void ReadWrite_WhenSerializingAndDeserializingNone_ShouldPreserveNone() + { + // Arrange + Optional original = Optional.None(); + + // Act + string json = JsonSerializer.Serialize(original, _options); + Optional deserialized = JsonSerializer.Deserialize>(json, _options); + + // Assert + deserialized.Should().Be(original); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/DirectoryMappingConfigTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/DirectoryMappingConfigTests.cs new file mode 100644 index 00000000..9abd16fd --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/DirectoryMappingConfigTests.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileManagement; +using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; +using Lumina.Contracts.Models.FileManagement; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Mapster; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileManagement; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DirectoryMappingConfigTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly TypeAdapterConfig _config; + private readonly DirectoryMappingConfig _directoryMappingConfig; + private readonly FileSystemTreeMappingConfig _fileSystemTreeMappingConfig; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + public DirectoryMappingConfigTests() + { + _config = new TypeAdapterConfig(); + _directoryMappingConfig = new DirectoryMappingConfig(); + _fileSystemTreeMappingConfig = new FileSystemTreeMappingConfig(); + _directoryMappingConfig.Register(_config); + _fileSystemTreeMappingConfig.Register(_config); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Register_WhenMappingDirectoryToFileSystemTreeNodeResponse_ShouldMapCorrectly() + { + // Arrange + DirectoryFixture directoryFixture = new(); + Directory directory = directoryFixture.CreateDirectory(); + + // create some child items + List childItems = + [ + directoryFixture.CreateDirectory(), + directoryFixture.CreateDirectory() + ]; + foreach (FileSystemItem item in childItems) + directory.AddItem(item); + + // Act + FileSystemTreeNodeResponse result = directory.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(directory.Name); + result.Path.Should().Be(directory.Id.Path); + result.ItemType.Should().Be(directory.Type); + result.IsExpanded.Should().BeFalse(); + result.ChildrenLoaded.Should().BeFalse(); + result.Children.Should().NotBeNull(); + result.Children.Should().HaveCount(childItems.Count); + + // Verify that each child item is correctly mapped + for (int i = 0; i < childItems.Count; i++) + { + result.Children[i].Name.Should().Be(childItems[i].Name); + result.Children[i].Path.Should().Be(childItems[i].Id.Path); + result.Children[i].ItemType.Should().Be(childItems[i].Type); + } + } + + [Fact] + public void Register_WhenMappingDirectoryToDirectoryResponse_ShouldMapCorrectly() + { + // Arrange + DirectoryFixture directoryFixture = new(); + Directory directory = directoryFixture.CreateDirectory(); + + // Act + DirectoryResponse result = directory.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(directory.Id.Path); + result.Name.Should().Be(directory.Name); + result.DateCreated.Should().Be(directory.DateCreated.Value); + result.DateModified.Should().Be(directory.DateModified.Value); + result.Items.Should().BeAssignableTo>(); + result.Items.Should().HaveCount(directory.Items.Count); + } + + [Fact] + public void Register_WhenMappingDirectoryToFileSystemItemModel_ShouldMapCorrectly() + { + // Arrange + DirectoryFixture directoryFixture = new(); + Directory directory = directoryFixture.CreateDirectory(); + DateTime beforeMapping = DateTime.Now; + + // Act + FileSystemItemModel result = directory.Adapt(_config); + DateTime afterMapping = DateTime.Now; + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(directory.Id.Path); + result.Name.Should().Be(directory.Name); + result.DateCreated.Should().BeOnOrAfter(beforeMapping).And.BeOnOrBefore(afterMapping); + result.DateModified.Should().BeOnOrAfter(beforeMapping).And.BeOnOrBefore(afterMapping); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileMappingConfigTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileMappingConfigTests.cs new file mode 100644 index 00000000..0a78789b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileMappingConfigTests.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileManagement; +using Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Mapster; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileManagement; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileMappingConfigTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly TypeAdapterConfig _config; + private readonly FileMappingConfig _fileMappingConfig; + private readonly FileSystemTreeMappingConfig _fileSystemTreeMappingConfig; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + public FileMappingConfigTests() + { + _config = new TypeAdapterConfig(); + _fileMappingConfig = new FileMappingConfig(); + _fileSystemTreeMappingConfig = new FileSystemTreeMappingConfig(); + _fileMappingConfig.Register(_config); + _fileSystemTreeMappingConfig.Register(_config); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Register_WhenMappingFileToFileSystemTreeNodeResponse_ShouldMapCorrectly() + { + // Arrange + FileFixture fileFixture = new(); + File file = fileFixture.CreateFile(); + + // Act + FileSystemTreeNodeResponse result = file.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(file.Name); + result.Path.Should().Be(file.Id.Path); + result.ItemType.Should().Be(file.Type); + result.IsExpanded.Should().BeFalse(); + result.ChildrenLoaded.Should().BeFalse(); + result.Children.Should().BeEmpty(); + } + + [Fact] + public void Register_WhenMappingFileToFileResponse_ShouldMapCorrectly() + { + // Arrange + FileFixture fileFixture = new(); + File file = fileFixture.CreateFile(); + + // Act + FileResponse result = file.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(file.Id.Path); + result.Name.Should().Be(file.Name); + result.DateCreated.Should().Be(file.DateCreated.Value); + result.DateModified.Should().Be(file.DateModified.Value); + result.Size.Should().Be(file.Size); + } + + [Fact] + public void Register_WhenMappingFileToFileResponseWithoutDates_ShouldMapCorrectly() + { + // Arrange + FileFixture fileFixture = new(); + File file = FileFixture.CreateFileWithoutDates(); + + // Act + FileResponse result = file.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(file.Id.Path); + result.Name.Should().Be(file.Name); + result.DateCreated.Should().Be(default); + result.DateModified.Should().Be(default); + result.Size.Should().Be(file.Size); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileSystemTreeMappingConfigTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileSystemTreeMappingConfigTests.cs new file mode 100644 index 00000000..2747f23e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/FileSystemTreeMappingConfigTests.cs @@ -0,0 +1,164 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileManagement; +using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; +using Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Mapster; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileManagement; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemTreeMappingConfigTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly TypeAdapterConfig _config; + private readonly FileSystemTreeMappingConfig _fileSystemTreeMappingConfig; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + public FileSystemTreeMappingConfigTests() + { + _config = new TypeAdapterConfig(); + _fileSystemTreeMappingConfig = new FileSystemTreeMappingConfig(); + _fileSystemTreeMappingConfig.Register(_config); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Register_WhenMappingWindowsRootItemToFileSystemTreeNodeResponse_ShouldMapCorrectly() + { + // Arrange + WindowsRootItem windowsRoot = WindowsRootItem.Create("C:", "C:").Value; + + // Act + FileSystemTreeNodeResponse result = windowsRoot.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(windowsRoot.Id.Path); + result.Name.Should().Be(windowsRoot.Name); + result.ItemType.Should().Be(FileSystemItemType.Root); + result.IsExpanded.Should().BeFalse(); + result.Children.Should().NotBeNull(); + result.Children.Should().BeEmpty(); + } + + [Fact] + public void Register_WhenMappingFileSystemTreeNodeResponseToWindowsRootItem_ShouldMapCorrectly() + { + // Arrange + FileSystemTreeNodeResponse response = new() + { + Path = "D:", + Name = "D:", + ItemType = FileSystemItemType.Root, + IsExpanded = false + }; + + // Act + WindowsRootItem result = response.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Id.Path.Should().Be(response.Path); + result.Name.Should().Be(response.Name); + result.Type.Should().Be(FileSystemItemType.Root); + result.Status.Should().Be(FileSystemItemStatus.Accessible); + } + + [Fact] + public void Register_WhenMappingUnixRootItemToFileSystemTreeNodeResponse_ShouldMapCorrectly() + { + // Arrange + UnixRootItem unixRoot = UnixRootItem.Create().Value; + + // Act + FileSystemTreeNodeResponse result = unixRoot.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(unixRoot.Id.Path); + result.Name.Should().Be(unixRoot.Name); + result.ItemType.Should().Be(FileSystemItemType.Root); + result.IsExpanded.Should().BeFalse(); + result.ChildrenLoaded.Should().BeFalse(); + result.Children.Should().NotBeNull(); + result.Children.Should().BeEmpty(); + } + + [Fact] + public void Register_WhenMappingFileSystemTreeNodeResponseToUnixRootItem_ShouldMapCorrectly() + { + // Arrange + FileSystemTreeNodeResponse response = new() + { + Path = "/", + Name = "/", + ItemType = FileSystemItemType.Root, + IsExpanded = false + }; + + // Act + UnixRootItem result = response.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Id.Path.Should().Be("/"); + result.Name.Should().Be("/"); + result.Type.Should().Be(FileSystemItemType.Root); + result.Status.Should().Be(FileSystemItemStatus.Accessible); + } + + [Fact] + public void Register_WhenMappingDirectoryToFileSystemTreeNodeResponse_ShouldMapCorrectly() + { + // Arrange + DirectoryFixture directoryFixture = new(); + Directory directory = directoryFixture.CreateDirectory(); + directory.AddItem(directoryFixture.CreateDirectory()); + directory.AddItem(directoryFixture.CreateDirectory()); + + // Act + FileSystemTreeNodeResponse result = directory.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(directory.Name); + result.Path.Should().Be(directory.Id.Path); + result.ItemType.Should().Be(directory.Type); + result.IsExpanded.Should().BeFalse(); + result.ChildrenLoaded.Should().BeFalse(); + result.Children.Should().NotBeNull(); + result.Children.Should().HaveCount(2); + } + + [Fact] + public void Register_WhenMappingFileToFileSystemTreeNodeResponse_ShouldMapCorrectly() + { + // Arrange + FileFixture fileFixture = new(); + File file = fileFixture.CreateFile(); + + // Act + FileSystemTreeNodeResponse result = file.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(file.Name); + result.Path.Should().Be(file.Id.Path); + result.ItemType.Should().Be(file.Type); + result.IsExpanded.Should().BeFalse(); + result.ChildrenLoaded.Should().BeFalse(); + result.Children.Should().BeEmpty(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/PathSegmentMappingConfigTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/PathSegmentMappingConfigTests.cs new file mode 100644 index 00000000..4d687d7e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/PathSegmentMappingConfigTests.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileManagement; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Mapster; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileManagement; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PathSegmentMappingConfigTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly TypeAdapterConfig _config; + private readonly PathSegmentMappingConfig _pathSegmentMappingConfig; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + public PathSegmentMappingConfigTests() + { + _config = new TypeAdapterConfig(); + _pathSegmentMappingConfig = new PathSegmentMappingConfig(); + _pathSegmentMappingConfig.Register(_config); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Register_WhenMappingPathSegmentToPathSegmentResponse_ShouldMapCorrectly() + { + // Arrange + ErrorOr createResult = PathSegment.Create("TestSegment", true, false); + createResult.IsError.Should().BeFalse(); + PathSegment pathSegment = createResult.Value; + + // Act + PathSegmentResponse result = pathSegment.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(pathSegment.Name); + } + + [Theory] + [InlineData("Folder", true, false)] + [InlineData("File.txt", false, false)] + [InlineData("C:", false, true)] + public void Register_WhenMappingDifferentPathSegmentTypes_ShouldMapCorrectly(string name, bool isDirectory, bool isDrive) + { + // Arrange + ErrorOr createResult = PathSegment.Create(name, isDirectory, isDrive); + createResult.IsError.Should().BeFalse(); + PathSegment pathSegment = createResult.Value; + + // Act + PathSegmentResponse result = pathSegment.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Path.Should().Be(pathSegment.Name); + } + + [Fact] + public void Register_WhenMappingMultiplePathSegments_ShouldMapAllCorrectly() + { + // Arrange + List pathSegments = + [ + PathSegment.Create("C:", false, true).Value, + PathSegment.Create("Users", true, false).Value, + PathSegment.Create("Documents", true, false).Value, + PathSegment.Create("file.txt", false, false).Value + ]; + + // Act + List results = pathSegments.Adapt>(_config); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(pathSegments.Count); + for (int i = 0; i < pathSegments.Count; i++) + { + results[i].Path.Should().Be(pathSegments[i].Name); + } + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/ThumbnailMappingConfigTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/ThumbnailMappingConfigTests.cs new file mode 100644 index 00000000..8e00ca94 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileManagement/ThumbnailMappingConfigTests.cs @@ -0,0 +1,115 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileManagement; +using Lumina.Contracts.Enums.PhotoLibrary; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Mapster; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.FileManagement; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThumbnailMappingConfigTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly TypeAdapterConfig _config; + private readonly ThumbnailMappingConfig _thumbnailMappingConfig; + private readonly Faker _faker; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + public ThumbnailMappingConfigTests() + { + _config = new TypeAdapterConfig(); + _thumbnailMappingConfig = new ThumbnailMappingConfig(); + _thumbnailMappingConfig.Register(_config); + _faker = new Faker(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Register_WhenMappingThumbnailToThumbnailResponse_ShouldMapCorrectly() + { + // Arrange + ImageType imageType = _faker.PickRandom(); + byte[] bytes = _faker.Random.Bytes(100); + Thumbnail thumbnail = new(imageType, bytes); + + // Act + ThumbnailResponse result = thumbnail.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Type.Should().Be(thumbnail.Type); + result.Bytes.Should().BeEquivalentTo(thumbnail.Bytes); + } + + [Theory] + [InlineData(ImageType.JPEG)] + [InlineData(ImageType.PNG)] + [InlineData(ImageType.GIF)] + public void Register_WhenMappingDifferentImageTypes_ShouldMapCorrectly(ImageType imageType) + { + // Arrange + byte[] bytes = _faker.Random.Bytes(100); + Thumbnail thumbnail = new(imageType, bytes); + + // Act + ThumbnailResponse result = thumbnail.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Type.Should().Be(imageType); + result.Bytes.Should().BeEquivalentTo(bytes); + } + + [Fact] + public void Register_WhenMappingThumbnailWithEmptyBytes_ShouldMapCorrectly() + { + // Arrange + ImageType imageType = _faker.PickRandom(); + byte[] emptyBytes = []; + Thumbnail thumbnail = new(imageType, emptyBytes); + + // Act + ThumbnailResponse result = thumbnail.Adapt(_config); + + // Assert + result.Should().NotBeNull(); + result.Type.Should().Be(imageType); + result.Bytes.Should().BeEmpty(); + } + + [Fact] + public void Register_WhenMappingMultipleThumbnails_ShouldMapAllCorrectly() + { + // Arrange + List thumbnails = + [ + new Thumbnail(ImageType.JPEG, _faker.Random.Bytes(100)), + new Thumbnail(ImageType.PNG, _faker.Random.Bytes(200)), + new Thumbnail(ImageType.GIF, _faker.Random.Bytes(150)) + ]; + + // Act + List results = thumbnails.Adapt>(_config); + + // Assert + results.Should().NotBeNull(); + results.Should().HaveCount(thumbnails.Count); + for (int i = 0; i < thumbnails.Count; i++) + { + results[i].Type.Should().Be(thumbnails[i].Type); + results[i].Bytes.Should().BeEquivalentTo(thumbnails[i].Bytes); + } + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryFixture.cs new file mode 100644 index 00000000..6882de15 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryFixture.cs @@ -0,0 +1,109 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using ErrorOr; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class DirectoryFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public DirectoryFixture() + { + _faker = new Faker(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// The created . + public Directory CreateDirectory( + string? path = null, + string? name = null, + Optional? dateCreated = null, + Optional? dateModified = null, + FileSystemItemStatus? status = null, + List? childItems = null) + { + path ??= _faker.System.FilePath(); + name ??= _faker.System.FileName(); + dateCreated ??= Optional.Some(_faker.Date.Past()); + dateModified ??= Optional.Some(_faker.Date.Recent()); + status ??= _faker.PickRandom(); + + ErrorOr directoryResult = Directory.Create(path, name, dateCreated.Value, dateModified.Value, status.Value); + + if (directoryResult.IsError) + throw new InvalidOperationException("Failed to create Directory: " + string.Join(", ", directoryResult.Errors)); + Directory directory = directoryResult.Value; + + if (childItems != null) + foreach (FileSystemItem item in childItems) + directory.AddItem(item); + return directory; + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count).Select(_ => CreateDirectory()).ToList(); + } + + /// + /// Creates a list of nested objects with a hierarchical structure. + /// + /// The number of top-level directories to create. Default is 3. + /// The maximum depth of the directory hierarchy. Default is 3. + /// The maximum number of child items (files or directories) per directory. Default is 3. + /// A list of objects with nested structures. + public List CreateManyNested(int count = 3, int maxDepth = 3, int maxChildrenPerDirectory = 3) + { + return Enumerable.Range(0, count).Select(_ => CreateNestedDirectory(1, maxDepth, maxChildrenPerDirectory)).ToList(); + } + + /// + /// Recursively creates a nested structure. + /// + /// The current depth in the directory hierarchy. + /// The maximum allowed depth for the directory hierarchy. + /// The maximum number of child items (files or directories) allowed per directory. + /// A object that may contain nested directories and files. + private Directory CreateNestedDirectory(int currentDepth, int maxDepth, int maxChildrenPerDirectory) + { + List childItems = []; + + if (currentDepth < maxDepth) + { + int childCount = _faker.Random.Int(0, maxChildrenPerDirectory); + for (int i = 0; i < childCount; i++) + childItems.Add(CreateNestedDirectory(currentDepth + 1, maxDepth, maxChildrenPerDirectory)); + } + return CreateDirectory(childItems: childItems); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryResponseFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryResponseFixture.cs new file mode 100644 index 00000000..053d0b32 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryResponseFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.FileManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class DirectoryResponseFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker = new(); + private readonly FileSystemItemModelFixture _fileSystemItemModelFixture = new(); + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// The number of children elements to create. + /// The created . + public DirectoryResponse Create(int itemCount = 3) + { + return new DirectoryResponse( + _faker.System.FilePath(), + _faker.System.FileName(), + _faker.Date.Past(), + _faker.Date.Recent(), + _fileSystemItemModelFixture.CreateMany(itemCount) + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The number of children elemens to create for each element. + /// The created list. + public List CreateMany(int count = 3, int itemCount = 3) + { + return Enumerable.Range(0, count).Select(_ => Create(itemCount)).ToList(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/FileSystemItemModelFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/FileSystemItemModelFixture.cs new file mode 100644 index 00000000..d14fa2f0 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/FileSystemItemModelFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Models.FileManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemItemModelFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker = new(); + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// The created . + public FileSystemItemModel Create() + { + return new FileSystemItemModel( + _faker.System.FilePath(), + _faker.System.FileName(), + _faker.Date.Past(), + _faker.Date.Recent() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count).Select(_ => Create()).ToList(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/FileSystemTreeNodeResponseFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/FileSystemTreeNodeResponseFixture.cs new file mode 100644 index 00000000..39fc0d8f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/FileSystemTreeNodeResponseFixture.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemTreeNodeResponseFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker = new(); + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a single with a nested structure. + /// + /// The current depth in the tree structure. Default is 0 (root level). + /// The maximum depth of the tree structure. Default is 2. + /// The maximum number of children for each node. Default is 3. + /// A with a nested structure. + public FileSystemTreeNodeResponse Create(int currentDepth = 0, int maxDepth = 2, int maxChildren = 3) + { + FileSystemTreeNodeResponse response = new() + { + Path = _faker.System.FilePath(), + Name = _faker.System.FileName(), + ItemType = FileSystemItemType.Directory, + IsExpanded = _faker.Random.Bool(), + ChildrenLoaded = true, + Children = [] + }; + if (currentDepth < maxDepth) + { + int childCount = _faker.Random.Int(1, maxChildren); + for (int i = 0; i < childCount; i++) + response.Children.Add(Create(currentDepth + 1, maxDepth, maxChildren)); + } + return response; + } + + /// + /// Creates a list of objects, each with a nested structure. + /// + /// The number of root-level nodes to create. Default is 2. + /// The maximum depth of the tree structure for each root node. Default is 2. + /// The maximum number of children for each node. Default is 3. + /// A list of objects with nested structures. + public List CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3) + { + return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/Fixtures/GetDirectoriesQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/Fixtures/GetDirectoriesQueryFixture.cs new file mode 100644 index 00000000..14e9a183 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/Fixtures/GetDirectoriesQueryFixture.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectories.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesQueryFixture +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid query to get directories. + /// + /// Whether to include hidden file system elements or not. + /// The created query to get directories. + public static GetDirectoriesQuery CreateGetDirectoriesQuery(bool includeHiddenElements = false) + { + return new Faker() + .CustomInstantiator(f => new GetDirectoriesQuery( + default!, + default + )) + .RuleFor(x => x.Path, f => f.System.DirectoryPath()) + .RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs new file mode 100644 index 00000000..647000b3 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs @@ -0,0 +1,153 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories; +using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; +using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectories.Fixtures; +using Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; +using Lumina.Contracts.Enums.BookLibrary; +using Lumina.Contracts.Models.Common; +using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; +using MapsterMapper; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectories; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesQueryHandlerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly IMapper _mockMapper; + private readonly IDirectoryService _mockDirectoryService; + private readonly GetDirectoriesQueryHandler _sut; + private readonly DirectoryFixture _directoryFixture; + private readonly DirectoryResponseFixture _directoryResponseFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetDirectoriesQueryHandlerTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockDirectoryService = Substitute.For(); + _mockMapper = Substitute.For(); + _sut = new GetDirectoriesQueryHandler(_mockDirectoryService, _mockMapper); + _directoryFixture = new DirectoryFixture(); + _directoryResponseFixture = new DirectoryResponseFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task Handle_WhenCalledWithValidQueryWithoutFilesIncluded_ShouldReturnSuccessResult() + { + // Arrange + GetDirectoriesQuery getDirectoriesQuery = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(false); + + IEnumerable directories = _directoryFixture.CreateMany(); + IEnumerable directoryResponses = _directoryResponseFixture.CreateMany(directories.Count()); + + _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements) + .Returns(ErrorOrFactory.From(directories)); + + _mockMapper.Map>(Arg.Is>(d => d == directories)) + .Returns(directoryResponses); + + // Act + ErrorOr> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeAssignableTo>(); + result.Value.Should().BeEquivalentTo(directoryResponses); + _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements); + _mockMapper.Received(1).Map>(Arg.Is>(d => d == directories)); + } + + [Fact] + public async Task Handle_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult() + { + // Arrange + GetDirectoriesQuery getDirectoriesQuery = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(true); + + IEnumerable directories = _directoryFixture.CreateMany(); + IEnumerable directoryResponses = _directoryResponseFixture.CreateMany(directories.Count()); + + _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements) + .Returns(ErrorOrFactory.From(directories)); + + _mockMapper.Map>(Arg.Is>(d => d == directories)) + .Returns(directoryResponses); + + // Act + ErrorOr> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeAssignableTo>(); + result.Value.Should().BeEquivalentTo(directoryResponses); + _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements); + _mockMapper.Received(1).Map>(Arg.Is>(d => d == directories)); + } + + [Fact] + public async Task Handle_WhenDirectoryServiceReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetDirectoriesQuery query = _fixture.Create(); + Error error = Error.Failure("DirectoryService.Error", "An error occurred"); + _mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements) + .Returns(error); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + _mockDirectoryService.Received(1).GetSubdirectories(query.Path, query.IncludeHiddenElements); + } + + [Fact] + public async Task Handle_WhenDirectoryServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() + { + // Arrange + GetDirectoriesQuery query = _fixture.Create(); + ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); + _mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements) + .Returns(emptyList); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEmpty(); + _mockDirectoryService.Received(1).GetSubdirectories(query.Path, query.IncludeHiddenElements); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs new file mode 100644 index 00000000..0bb62d61 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories; +using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectories.Fixtures; +using System.Diagnostics.CodeAnalysis; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectories; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesQueryValidatorTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly GetDirectoriesQueryValidator _validator; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetDirectoriesQueryValidatorTests() + { + _validator = new GetDirectoriesQueryValidator(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Validate_WhenPathIsNull_ShouldHaveValidationError() + { + // Arrange + GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(); + query = query with { Path = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(); + query = query with { Path = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() + { + // Arrange + GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(); + query = query with { Path = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(); + query = query with { Path = "/valid/path" }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Path); + } + + [Fact] + public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() + { + // Arrange + GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(); + query = query with { IncludeHiddenElements = true }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + } + + [Fact] + public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() + { + // Arrange + GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(); + query = query with { IncludeHiddenElements = false }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/Fixtures/GetDirectoryTreeQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/Fixtures/GetDirectoryTreeQueryFixture.cs new file mode 100644 index 00000000..02094b22 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/Fixtures/GetDirectoryTreeQueryFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectoryTree.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoryTreeQueryFixture +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid query to get directory tree. + /// + /// Whether to include file system files or not. + /// Whether to include hidden file system elements or not. + /// The created query to get directory tree. + public static GetDirectoryTreeQuery CreateGetDirectoryTreeQuery(bool includeFiles = false, bool includeHiddenElements = false) + { + return new Faker() + .CustomInstantiator(f => new GetDirectoryTreeQuery( + default!, + default, + default + )) + .RuleFor(x => x.Path, f => f.System.DirectoryPath()) + .RuleFor(x => x.IncludeFiles, f => includeFiles) + .RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandlerTests.cs new file mode 100644 index 00000000..a4e0accd --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandlerTests.cs @@ -0,0 +1,393 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; +using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; +using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectoryTree.Fixtures; +using Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +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.FileManagement.Directories.Queries.GetDirectoryTree; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoryTreeQueryHandlerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly IDriveService _mockDriveService; + private readonly IDirectoryService _mockDirectoryService; + private readonly IFileService _mockFileService; + private readonly IPathService _mockPathService; + private readonly GetDirectoryTreeQueryHandler _sut; + private readonly GetDirectoryTreeQueryFixture _getDirectoryTreeQueryFixture; + private readonly DirectoryFixture _directoryFixture; + private readonly PathSegmentFixture _pathSegmentFixture; + private readonly FileFixture _fileFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetDirectoryTreeQueryHandlerTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockDriveService = Substitute.For(); + _mockDirectoryService = Substitute.For(); + _mockFileService = Substitute.For(); + _mockPathService = Substitute.For(); + _sut = new GetDirectoryTreeQueryHandler(_mockDriveService, _mockDirectoryService, _mockFileService, _mockPathService); + _getDirectoryTreeQueryFixture = new GetDirectoryTreeQueryFixture(); + _directoryFixture = new DirectoryFixture(); + _pathSegmentFixture = new PathSegmentFixture(); + _fileFixture = new FileFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task Handle_WhenCalledWithValidQueryAndNoIncludeFiles_ShouldReturnSuccessResult() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(false, true); + + // Create a drive that matches what the implementation expects + string drivePath = "C:\\"; + IEnumerable drives = + [ + WindowsRootItem.Create(drivePath, "C:").Value + ]; + + // Ensure the first path segment matches the drive path + PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true); + List otherPathSegments = _pathSegmentFixture.CreateMany(2); + IEnumerable pathSegments = new[] { firstPathSegment }.Concat(otherPathSegments); + + IEnumerable subdirectories = _directoryFixture.CreateMany(2); + IEnumerable files = _fileFixture.CreateMany(2); + + _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); + _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From(pathSegments)); + _mockPathService.CombinePath(Arg.Is(x => true), Arg.Is(y => true)).Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); + _mockDirectoryService.GetSubdirectories(Arg.Any(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories)); + _mockFileService.GetFiles(Arg.Any(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(files)); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeEmpty(); + result.Value.First().Children.Should().NotBeEmpty(); + _mockDriveService.Received(1).GetDrives(); + _mockPathService.Received(1).ParsePath(query.Path); + _mockDirectoryService.Received(1).GetSubdirectories(Arg.Any(), query.IncludeHiddenElements); + _mockFileService.Received(0).GetFiles(Arg.Any(), query.IncludeHiddenElements); + } + + [Fact] + public async Task Handle_WhenCalledWithValidQueryAndIncludeFiles_ShouldReturnSuccessResult() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(true, true); + + // Create a drive that matches what the implementation expects + string drivePath = "C:\\"; + IEnumerable drives = + [ + WindowsRootItem.Create(drivePath, "C:").Value + ]; + + // Ensure the first path segment matches the drive path + PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true); + List otherPathSegments = _pathSegmentFixture.CreateMany(2); + IEnumerable pathSegments = new[] { firstPathSegment }.Concat(otherPathSegments); + + IEnumerable subdirectories = _directoryFixture.CreateMany(2); + IEnumerable files = _fileFixture.CreateMany(2); + + _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); + _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From(pathSegments)); + _mockPathService.CombinePath(Arg.Is(x => true), Arg.Is(y => true)).Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); + _mockDirectoryService.GetSubdirectories(Arg.Any(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories)); + _mockFileService.GetFiles(Arg.Any(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(files)); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeEmpty(); + result.Value.First().Children.Should().NotBeEmpty(); + _mockDriveService.Received(1).GetDrives(); + _mockPathService.Received(1).ParsePath(query.Path); + _mockDirectoryService.Received(1).GetSubdirectories(Arg.Any(), query.IncludeHiddenElements); + _mockFileService.Received(1).GetFiles(Arg.Any(), query.IncludeHiddenElements); + } + + [Fact] + public async Task Handle_WhenGetDrivesReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); + Error error = Error.Failure("DriveService.Error", "An error occurred"); + _mockDriveService.GetDrives().Returns(error); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + _mockDriveService.Received(1).GetDrives(); + } + + [Fact] + public async Task Handle_WhenParsePathReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); + IEnumerable drives = + [ + WindowsRootItem.Create("C:\\", "Local Disk").Value + ]; + Error error = Error.Failure("PathService.Error", "An error occurred"); + + _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); + _mockPathService.ParsePath(query.Path).Returns(error); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + _mockDriveService.Received(1).GetDrives(); + _mockPathService.Received(1).ParsePath(query.Path); + } + + [Fact] + public async Task Handle_WhenCombinePathReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); + IEnumerable drives = + [ + WindowsRootItem.Create("C:\\", "C:").Value + ]; + PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true); + IEnumerable pathSegments = new[] { firstPathSegment }.Concat(_pathSegmentFixture.CreateMany(2)); + Error error = Error.Failure("PathService.Error", "An error occurred"); + + _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); + _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From(pathSegments)); + _mockPathService.CombinePath(Arg.Any(), Arg.Any()).Returns(error); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + _mockDriveService.Received(1).GetDrives(); + _mockPathService.Received(1).ParsePath(query.Path); + _mockPathService.Received(1).CombinePath(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Handle_WhenGetSubdirectoriesReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); + IEnumerable drives = + [ + WindowsRootItem.Create("C:\\", "C:").Value + ]; + PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true); + IEnumerable pathSegments = new[] { firstPathSegment }.Concat(_pathSegmentFixture.CreateMany(2)); + Error error = Error.Failure("DirectoryService.Error", "An error occurred"); + + _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); + _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From(pathSegments)); + _mockPathService.CombinePath(Arg.Is(x => true), Arg.Is(y => true)).Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); + _mockDirectoryService.GetSubdirectories(Arg.Any(), query.IncludeHiddenElements).Returns(error); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + _mockDriveService.Received(1).GetDrives(); + _mockPathService.Received(1).ParsePath(query.Path); + _mockDirectoryService.Received(1).GetSubdirectories(Arg.Any(), query.IncludeHiddenElements); + } + + [Fact] + public async Task Handle_WhenGetFilesReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(true); + IEnumerable drives = + [ + WindowsRootItem.Create("C:\\", "C:").Value + ]; + PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true); + IEnumerable pathSegments = new[] { firstPathSegment }.Concat(_pathSegmentFixture.CreateMany(2)); + IEnumerable subdirectories = _directoryFixture.CreateMany(2); + Error error = Error.Failure("FileService.Error", "An error occurred"); + + _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); + _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From(pathSegments)); + _mockPathService.CombinePath(Arg.Is(x => true), Arg.Is(y => true)).Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); + _mockDirectoryService.GetSubdirectories(Arg.Any(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories)); + _mockFileService.GetFiles(Arg.Any(), query.IncludeHiddenElements).Returns(error); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + _mockDriveService.Received(1).GetDrives(); + _mockPathService.Received(1).ParsePath(query.Path); + _mockDirectoryService.Received(1).GetSubdirectories(Arg.Any(), query.IncludeHiddenElements); + _mockFileService.Received(1).GetFiles(Arg.Any(), query.IncludeHiddenElements); + } + + [Fact] + public async Task Handle_WhenPathOnlyContainsRoot_ShouldReturnOnlyRootNode() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); + query = query with { Path = "C:" }; + IEnumerable drives = [WindowsRootItem.Create("C:\\", "C:").Value]; + PathSegment rootSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true); + + _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); + _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From((IEnumerable)[rootSegment])); + _mockDirectoryService.GetSubdirectories(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + result.Value.First().Name.Should().Be("C:"); + result.Value.First().Children.Should().BeEmpty(); + } + + [Fact] + public async Task Handle_WhenPathHasManySegments_ShouldCreateCorrectTreeStructure() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); + IEnumerable drives = [WindowsRootItem.Create("C:\\", "C:").Value]; + List pathSegments = + [ + _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true), + _pathSegmentFixture.CreatePathSegment(name: "Users"), + _pathSegmentFixture.CreatePathSegment(name: "Username"), + _pathSegmentFixture.CreatePathSegment(name: "Documents"), + _pathSegmentFixture.CreatePathSegment(name: "Projects"), + _pathSegmentFixture.CreatePathSegment(name: "MyProject") + ]; + + _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); + _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From((IEnumerable)pathSegments)); + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); + + _mockDirectoryService.GetSubdirectories(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + FileSystemTreeNodeResponse root = result.Value.First(); + root.Name.Should().Be("C:"); + root.Children.Should().HaveCount(1); + root.Children.First().Name.Should().Be("Users"); + root.Children.First().Children.First().Name.Should().Be("Username"); + root.Children.First().Children.First().Children.First().Name.Should().Be("Documents"); + root.Children.First().Children.First().Children.First().Children.First().Name.Should().Be("Projects"); + root.Children.First().Children.First().Children.First().Children.First().Children.First().Name.Should().Be("MyProject"); + } + + [Fact] + public async Task Handle_WhenPathContainsSpecialCharacters_ShouldHandleCorrectly() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); + IEnumerable drives = [WindowsRootItem.Create("C:\\", "C:").Value]; + List pathSegments = + [ + _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true), + _pathSegmentFixture.CreatePathSegment(name: "Program Files"), + _pathSegmentFixture.CreatePathSegment(name: "My Awesome App!"), + _pathSegmentFixture.CreatePathSegment(name: "Data Files") + ]; + + _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); + _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From((IEnumerable)pathSegments)); + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); + _mockDirectoryService.GetSubdirectories(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + FileSystemTreeNodeResponse root = result.Value.First(); + root.Children.First().Name.Should().Be("Program Files"); + root.Children.First().Children.First().Name.Should().Be("My Awesome App!"); + } + + [Fact] + public async Task Handle_WhenIncludeHiddenElementsIsFalse_ShouldNotIncludeHiddenItems() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(includeHiddenElements: false); + IEnumerable drives = [WindowsRootItem.Create("C:\\", "C:").Value]; + PathSegment rootSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true); + + _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); + _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From((IEnumerable)[rootSegment])); + + IEnumerable visibleDirectories = _directoryFixture.CreateMany(2); + _mockDirectoryService.GetSubdirectories(Arg.Any(), false).Returns(ErrorOrFactory.From(visibleDirectories)); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.First().Children.Should().HaveCount(2); + _mockDirectoryService.Received(1).GetSubdirectories(Arg.Any(), false); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidatorTests.cs new file mode 100644 index 00000000..aa9e83d8 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidatorTests.cs @@ -0,0 +1,147 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; +using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectoryTree.Fixtures; +using Lumina.Domain.Common.Errors; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectoryTree; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoryTreeQueryValidatorTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly GetDirectoryTreeQueryValidator _validator; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetDirectoryTreeQueryValidatorTests() + { + _validator = new GetDirectoryTreeQueryValidator(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Validate_WhenPathIsNull_ShouldHaveValidationError() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); + query = query with { Path = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); + query = query with { Path = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); + query = query with { Path = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); + query = query with { Path = "/valid/path" }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Path); + } + + [Fact] + public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); + query = query with { IncludeHiddenElements = true }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + } + + [Fact] + public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); + query = query with { IncludeHiddenElements = false }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + } + + [Fact] + public void Validate_WhenIncludeFilesIsTrue_ShouldNotHaveValidationError() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); + query = query with { IncludeFiles = true }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.IncludeFiles); + } + + [Fact] + public void Validate_WhenIncludeFilesIsFalse_ShouldNotHaveValidationError() + { + // Arrange + GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); + query = query with { IncludeFiles = false }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.IncludeFiles); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/Fixtures/GetTreeDirectoriesQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/Fixtures/GetTreeDirectoriesQueryFixture.cs new file mode 100644 index 00000000..433e1b4a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/Fixtures/GetTreeDirectoriesQueryFixture.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetTreeDirectories.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeDirectoriesQueryFixture +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid query to get tree directories. + /// + /// Whether to include hidden file system elements or not. + /// The created query to get tree directory. + public static GetTreeDirectoriesQuery CreateGetTreeDirectoryQuery(bool includeHiddenElements = false) + { + return new Faker() + .CustomInstantiator(f => new GetTreeDirectoriesQuery( + default!, + default + )) + .RuleFor(x => x.Path, f => f.System.DirectoryPath()) + .RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs new file mode 100644 index 00000000..3384b0d7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs @@ -0,0 +1,174 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories; +using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; +using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectoryTree.Fixtures; +using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetTreeDirectories.Fixtures; +using Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using MapsterMapper; +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.FileManagement.Directories.Queries.GetTreeDirectories; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeDirectoriesQueryHandlerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly IMapper _mockMapper; + private readonly IDirectoryService _mockDirectoryService; + private readonly GetTreeDirectoriesQueryHandler _sut; + private readonly GetTreeDirectoriesQueryFixture _getTreeDirectoriesQueryFixture; + private readonly DirectoryFixture _directoryFixture; + private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetTreeDirectoriesQueryHandlerTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockDirectoryService = Substitute.For(); + _mockMapper = Substitute.For(); + _sut = new GetTreeDirectoriesQueryHandler(_mockDirectoryService, _mockMapper); + _getTreeDirectoriesQueryFixture = new GetTreeDirectoriesQueryFixture(); + _directoryFixture = new DirectoryFixture(); + _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task Handle_WhenCalledWithValidQueryWithoutFilesIncluded_ShouldReturnSuccessResult() + { + // Arrange + GetTreeDirectoriesQuery getDirectoriesQuery = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(false); + + IEnumerable directories = _directoryFixture.CreateMany(); + IEnumerable directoryResponses = _fileSystemTreeNodeResponseFixture.CreateMany(directories.Count()); + + _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements) + .Returns(ErrorOrFactory.From(directories)); + + _mockMapper.Map>(Arg.Is>(d => d == directories)) + .Returns(directoryResponses); + + // Act + ErrorOr> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeAssignableTo>(); + result.Value.Should().BeEquivalentTo(directoryResponses); + _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements); + _mockMapper.Received(1).Map>(Arg.Is>(d => d == directories)); + } + + [Fact] + public async Task Handle_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult() + { + // Arrange + GetTreeDirectoriesQuery getDirectoriesQuery = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(true); + + IEnumerable directories = _directoryFixture.CreateMany(); + IEnumerable directoryResponses = _fileSystemTreeNodeResponseFixture.CreateMany(directories.Count()); + + _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements) + .Returns(ErrorOrFactory.From(directories)); + + _mockMapper.Map>(Arg.Is>(d => d == directories)) + .Returns(directoryResponses); + + // Act + ErrorOr> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeAssignableTo>(); + result.Value.Should().BeEquivalentTo(directoryResponses); + _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements); + _mockMapper.Received(1).Map>(Arg.Is>(d => d == directories)); + } + + [Fact] + public async Task Handle_WhenDirectoryServiceReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetTreeDirectoriesQuery query = _fixture.Create(); + Error error = Error.Failure("DirectoryService.Error", "An error occurred"); + _mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements) + .Returns(error); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + _mockDirectoryService.Received(1).GetSubdirectories(query.Path, query.IncludeHiddenElements); + } + + [Fact] + public async Task Handle_WhenDirectoryServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() + { + // Arrange + GetTreeDirectoriesQuery query = _fixture.Create(); + ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); + _mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements) + .Returns(emptyList); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEmpty(); + _mockDirectoryService.Received(1).GetSubdirectories(query.Path, query.IncludeHiddenElements); + } + + [Fact] + public async Task Handle_WhenCalledWithNestedDirectories_ShouldReturnCorrectlyNestedResponse() + { + // Arrange + GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(true); + IEnumerable nestedDirectories = _directoryFixture.CreateManyNested(); + IEnumerable nestedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(2, 2, 2); + + _mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements) + .Returns(ErrorOrFactory.From(nestedDirectories)); + + _mockMapper.Map>(Arg.Is>(d => d == nestedDirectories)) + .Returns(nestedResponses); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeAssignableTo>(); + result.Value.Should().BeEquivalentTo(nestedResponses, options => options.IncludingNestedObjects()); + result.Value.Any(r => r.Children.Count != 0).Should().BeTrue(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidatorTests.cs new file mode 100644 index 00000000..ddd10a1d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidatorTests.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories; +using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetTreeDirectories.Fixtures; +using Lumina.Domain.Common.Errors; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetTreeDirectories; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeDirectoriesQueryValidatorTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly GetTreeDirectoriesQueryValidator _validator; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetTreeDirectoriesQueryValidatorTests() + { + _validator = new GetTreeDirectoriesQueryValidator(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Validate_WhenPathIsNull_ShouldHaveValidationError() + { + // Arrange + GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(); + query = query with { Path = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(); + query = query with { Path = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() + { + // Arrange + GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(); + query = query with { Path = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(); + query = query with { Path = "/valid/path" }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Path); + } + + [Fact] + public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() + { + // Arrange + GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(); + query = query with { IncludeHiddenElements = true }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + } + + [Fact] + public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() + { + // Arrange + GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(); + query = query with { IncludeHiddenElements = false }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Drives/Queries/GetDrives/Fixtures/GetDrivesQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Drives/Queries/GetDrives/Fixtures/GetDrivesQueryFixture.cs new file mode 100644 index 00000000..eb3e95cc --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Drives/Queries/GetDrives/Fixtures/GetDrivesQueryFixture.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Drives.Queries.GetDrives.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDrivesQueryFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker = new(); + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a single with a nested structure. + /// + /// The current depth in the tree structure. Default is 0 (root level). + /// The maximum depth of the tree structure. Default is 2. + /// The maximum number of children for each node. Default is 3. + /// A with a nested structure. + public FileSystemTreeNodeResponse Create(int currentDepth = 0, int maxDepth = 2, int maxChildren = 3) + { + FileSystemTreeNodeResponse response = new() + { + Path = _faker.System.FilePath(), + Name = _faker.System.FileName(), + ItemType = FileSystemItemType.Directory, + IsExpanded = _faker.Random.Bool(), + ChildrenLoaded = true, + Children = [] + }; + if (currentDepth < maxDepth) + { + int childCount = _faker.Random.Int(1, maxChildren); + for (int i = 0; i < childCount; i++) + response.Children.Add(Create(currentDepth + 1, maxDepth, maxChildren)); + } + return response; + } + + /// + /// Creates a list of objects, each with a nested structure. + /// + /// The number of root-level nodes to create. Default is 2. + /// The maximum depth of the tree structure for each root node. Default is 2. + /// The maximum number of children for each node. Default is 3. + /// A list of objects with nested structures. + public List CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3) + { + return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs new file mode 100644 index 00000000..59e16f64 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs @@ -0,0 +1,123 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Drives.Queries.GetDrives; +using Lumina.Application.UnitTests.Core.FileManagement.Drives.Queries.GetDrives.Fixtures; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using MapsterMapper; +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.FileManagement.Drives.Queries.GetDrives; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDrivesQueryHandlerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly IMapper _mockMapper; + private readonly IDriveService _mockDriveService; + private readonly GetDrivesQueryHandler _sut; + private readonly GetDrivesQueryFixture _getDrivesQueryFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetDrivesQueryHandlerTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockDriveService = Substitute.For(); + _mockMapper = Substitute.For(); + _sut = new GetDrivesQueryHandler(_mockDriveService, _mockMapper); + _getDrivesQueryFixture = new GetDrivesQueryFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task Handle_WhenCalled_ShouldReturnSuccessResult() + { + // Arrange + GetDrivesQuery getDrivesQuery = _fixture.Create(); + + IEnumerable drives = + [ + WindowsRootItem.Create("C:\\", "C:").Value, + WindowsRootItem.Create("D:\\", "D:").Value + ]; + + List driveResponses = _getDrivesQueryFixture.CreateMany(); + + _mockDriveService.GetDrives() + .Returns(ErrorOrFactory.From(drives)); + + _mockMapper.Map>(Arg.Is>(d => d == drives)) + .Returns(driveResponses); + + // Act + ErrorOr> result = await _sut.Handle(getDrivesQuery, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeAssignableTo>(); + result.Value.Should().BeEquivalentTo(driveResponses); + _mockDriveService.Received(1).GetDrives(); + _mockMapper.Received(1).Map>(Arg.Is>(d => d == drives)); + } + + [Fact] + public async Task Handle_WhenDriveServiceReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetDrivesQuery query = _fixture.Create(); + Error error = Error.Failure("DriveService.Error", "An error occurred"); + _mockDriveService.GetDrives() + .Returns(error); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + _mockDriveService.Received(1).GetDrives(); + } + + [Fact] + public async Task Handle_WhenDriveServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() + { + // Arrange + GetDrivesQuery query = _fixture.Create(); + ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); + _mockDriveService.GetDrives() + .Returns(emptyList); + + _mockMapper.Map>(Arg.Any>()) + .Returns([]); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEmpty(); + _mockDriveService.Received(1).GetDrives(); + _mockMapper.Received(1).Map>(Arg.Any>()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs new file mode 100644 index 00000000..55193fc9 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/FileSystem/Queries/GetFileSystem/GetFileSystemQueryHandlerTests.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSystem; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.FileSystem.Queries.GetFileSystem; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetFileSystemQueryHandlerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly IPlatformContextManager _mockPlatformContextManager; + private readonly IPlatformContext _mockPlatformContext; + private readonly GetFileSystemQueryHandler _sut; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetFileSystemQueryHandlerTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockPlatformContextManager = Substitute.For(); + _mockPlatformContext = Substitute.For(); + _mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext); + _sut = new GetFileSystemQueryHandler(_mockPlatformContextManager); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Theory] + [InlineData(PlatformType.Unix)] + [InlineData(PlatformType.Windows)] + public async Task Handle_WhenCalled_ShouldReturnCorrectFileSystemTypeResponse(PlatformType platformType) + { + // Arrange + GetFileSystemQuery query = _fixture.Create(); + _mockPlatformContext.Platform.Returns(platformType); + + // Act + FileSystemTypeResponse result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.Should().NotBeNull(); + result.PlatformType.Should().Be(platformType); + _mockPlatformContextManager.Received(1).GetCurrentContext(); + } + + [Fact] + public async Task Handle_WhenCalled_ShouldReturnValueTaskResult() + { + // Arrange + GetFileSystemQuery query = _fixture.Create(); + _mockPlatformContext.Platform.Returns(PlatformType.Unix); + + // Act + ValueTask resultTask = _sut.Handle(query, CancellationToken.None); + + // Assert + resultTask.IsCompleted.Should().BeTrue(); + FileSystemTypeResponse result = await resultTask; + result.Should().NotBeNull(); + result.PlatformType.Should().Be(PlatformType.Unix); + } + + [Fact] + public async Task Handle_WhenCalled_ShouldNotDependOnQueryContent() + { + // Arrange + GetFileSystemQuery query1 = _fixture.Create(); + GetFileSystemQuery query2 = _fixture.Create(); + _mockPlatformContext.Platform.Returns(PlatformType.Windows); + + // Act + FileSystemTypeResponse result1 = await _sut.Handle(query1, CancellationToken.None); + FileSystemTypeResponse result2 = await _sut.Handle(query2, CancellationToken.None); + + // Assert + result1.Should().BeEquivalentTo(result2); + _mockPlatformContextManager.Received(1).GetCurrentContext(); + } + + [Fact] + public async Task Handle_WhenCalled_ShouldIgnoreCancellationToken() + { + // Arrange + GetFileSystemQuery query = _fixture.Create(); + _mockPlatformContext.Platform.Returns(PlatformType.Unix); + CancellationToken cancellationToken = new(true); + + // Act + Func act = async () => await _sut.Handle(query, cancellationToken); + + // Assert + await act.Should().NotThrowAsync(); + _mockPlatformContextManager.Received(1).GetCurrentContext(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Fixtures/FileFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Fixtures/FileFixture.cs new file mode 100644 index 00000000..8ee7080d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Fixtures/FileFixture.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using ErrorOr; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class FileFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public FileFixture() + { + _faker = new Faker(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// The created . + public File CreateFile( + string? path = null, + string? name = null, + Optional? dateCreated = null, + Optional? dateModified = null, + long? size = null, + FileSystemItemStatus? status = null) + { + path ??= _faker.System.FilePath(); + name ??= _faker.System.FileName(); + dateCreated ??= Optional.Some(_faker.Date.Past()); + dateModified ??= Optional.Some(_faker.Date.Recent()); + size ??= _faker.Random.Long(); + status ??= _faker.PickRandom(); + + ErrorOr fileResult = File.Create(path, name, dateCreated.Value, dateModified.Value, size.Value, status.Value); + + if (fileResult.IsError) + throw new InvalidOperationException("Failed to create File: " + string.Join(", ", fileResult.Errors)); + return fileResult.Value; + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count).Select(_ => CreateFile()).ToList(); + } + + /// + /// Creates a random valid , without creationg and modification dates. + /// + /// + public static File CreateFileWithoutDates() + { + return File.Create( + "/path/to/file_without_dates.txt", + "file_without_dates.txt", + Optional.None(), + Optional.None(), + 2048, + FileSystemItemStatus.Accessible + ).Value; + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Fixtures/FileResponseFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Fixtures/FileResponseFixture.cs new file mode 100644 index 00000000..5034c39d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Fixtures/FileResponseFixture.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.FileManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class FileResponseFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker = new(); + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// The created . + public FileResponse Create() + { + return new FileResponse( + _faker.System.FilePath(), + _faker.System.FileName(), + _faker.Date.Past(), + _faker.Date.Recent(), + _faker.Random.Long() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count).Select(_ => Create()).ToList(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/Fixtures/GetFilesQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/Fixtures/GetFilesQueryFixture.cs new file mode 100644 index 00000000..da53734d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/Fixtures/GetFilesQueryFixture.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileManagement.Files.Queries.GetFiles; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetFiles.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetFilesQueryFixture +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid query to get files. + /// + /// Whether to include hidden file system elements or not. + /// The created query to get files. + public static GetFilesQuery CreateGetFilesQuery(bool includeHiddenElements = false) + { + return new Faker() + .CustomInstantiator(f => new GetFilesQuery( + default!, + default + )) + .RuleFor(x => x.Path, f => f.System.FilePath()) + .RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs new file mode 100644 index 00000000..7173015d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs @@ -0,0 +1,149 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Files.Queries.GetFiles; +using Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; +using Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetFiles.Fixtures; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using MapsterMapper; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetFiles; + + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetFilesQueryHandlerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly IMapper _mockMapper; + private readonly IFileService _mockFileService; + private readonly GetFilesQueryHandler _sut; + private readonly FileFixture _fileFixture; + private readonly FileResponseFixture _fileResponseFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetFilesQueryHandlerTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockFileService = Substitute.For(); + _mockMapper = Substitute.For(); + _sut = new GetFilesQueryHandler(_mockFileService, _mockMapper); + _fileFixture = new FileFixture(); + _fileResponseFixture = new FileResponseFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task Handle_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult() + { + // Arrange + GetFilesQuery getFilesQuery = GetFilesQueryFixture.CreateGetFilesQuery(false); + + IEnumerable files = _fileFixture.CreateMany(); + IEnumerable fileResponses = _fileResponseFixture.CreateMany(files.Count()); + + _mockFileService.GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements) + .Returns(ErrorOrFactory.From(files)); + + _mockMapper.Map>(Arg.Is>(f => f == files)) + .Returns(fileResponses); + + // Act + ErrorOr> result = await _sut.Handle(getFilesQuery, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeAssignableTo>(); + result.Value.Should().BeEquivalentTo(fileResponses); + _mockFileService.Received(1).GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements); + _mockMapper.Received(1).Map>(Arg.Is>(f => f == files)); + } + + [Fact] + public async Task Handle_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult() + { + // Arrange + GetFilesQuery getFilesQuery = GetFilesQueryFixture.CreateGetFilesQuery(true); + + IEnumerable files = _fileFixture.CreateMany(); + IEnumerable fileResponses = _fileResponseFixture.CreateMany(files.Count()); + + _mockFileService.GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements) + .Returns(ErrorOrFactory.From(files)); + + _mockMapper.Map>(Arg.Is>(f => f == files)) + .Returns(fileResponses); + + // Act + ErrorOr> result = await _sut.Handle(getFilesQuery, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeAssignableTo>(); + result.Value.Should().BeEquivalentTo(fileResponses); + _mockFileService.Received(1).GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements); + _mockMapper.Received(1).Map>(Arg.Is>(f => f == files)); + } + + [Fact] + public async Task Handle_WhenFileServiceReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetFilesQuery query = _fixture.Create(); + Error error = Error.Failure("FileService.Error", "An error occurred"); + _mockFileService.GetFiles(query.Path, query.IncludeHiddenElements) + .Returns(error); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + _mockFileService.Received(1).GetFiles(query.Path, query.IncludeHiddenElements); + _mockMapper.DidNotReceive().Map>(Arg.Any>()); + } + + [Fact] + public async Task Handle_WhenFileServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() + { + // Arrange + GetFilesQuery query = _fixture.Create(); + ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); + _mockFileService.GetFiles(query.Path, query.IncludeHiddenElements) + .Returns(emptyList); + + _mockMapper.Map>(Arg.Is>(f => !f.Any())) + .Returns([]); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEmpty(); + _mockFileService.Received(1).GetFiles(query.Path, query.IncludeHiddenElements); + _mockMapper.Received(1).Map>(Arg.Is>(f => !f.Any())); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs new file mode 100644 index 00000000..824d1034 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Core.FileManagement.Files.Queries.GetFiles; +using Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetFiles.Fixtures; +using Lumina.Domain.Common.Errors; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetFiles; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetFilesQueryValidatorTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly GetFilesQueryValidator _validator; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetFilesQueryValidatorTests() + { + _validator = new GetFilesQueryValidator(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Validate_WhenPathIsNull_ShouldHaveValidationError() + { + // Arrange + GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery(); + query = query with { Path = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery(); + query = query with { Path = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() + { + // Arrange + GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery(); + query = query with { Path = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery(); + query = query with { Path = "/valid/path" }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Path); + } + + [Fact] + public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() + { + // Arrange + GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery(); + query = query with { IncludeHiddenElements = true }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + } + + [Fact] + public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() + { + // Arrange + GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery(); + query = query with { IncludeHiddenElements = false }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/Fixtures/GetTreeFilesQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/Fixtures/GetTreeFilesQueryFixture.cs new file mode 100644 index 00000000..07d9d818 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/Fixtures/GetTreeFilesQueryFixture.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetTreeFiles.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeFilesQueryFixture +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid query to get files. + /// + /// Whether to include hidden file system elements or not. + /// The created query to get files. + public static GetTreeFilesQuery CreateGetFilesQuery(bool includeHiddenElements = false) + { + return new Faker() + .CustomInstantiator(f => new GetTreeFilesQuery( + default!, + default + )) + .RuleFor(x => x.Path, f => f.System.FilePath()) + .RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs new file mode 100644 index 00000000..d0880e7f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs @@ -0,0 +1,143 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles; +using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; +using Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures; +using Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetTreeFiles.Fixtures; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using MapsterMapper; +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.FileManagement.Files.Queries.GetTreeFiles; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeFilesQueryHandlerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly IMapper _mockMapper; + private readonly IFileService _mockFileService; + private readonly GetTreeFilesQueryHandler _sut; + private readonly FileFixture _fileFixture; + private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetTreeFilesQueryHandlerTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockFileService = Substitute.For(); + _mockMapper = Substitute.For(); + _sut = new GetTreeFilesQueryHandler(_mockFileService, _mockMapper); + _fileFixture = new FileFixture(); + _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task Handle_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult() + { + // Arrange + GetTreeFilesQuery getFilesQuery = GetTreeFilesQueryFixture.CreateGetFilesQuery(false); + + IEnumerable files = _fileFixture.CreateMany(); + IEnumerable fileResponses = _fileSystemTreeNodeResponseFixture.CreateMany(files.Count()); + + _mockFileService.GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements) + .Returns(ErrorOrFactory.From(files)); + + _mockMapper.Map>(Arg.Is>(f => f == files)) + .Returns(fileResponses); + + // Act + ErrorOr> result = await _sut.Handle(getFilesQuery, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeAssignableTo>(); + result.Value.Should().BeEquivalentTo(fileResponses); + _mockFileService.Received(1).GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements); + _mockMapper.Received(1).Map>(Arg.Is>(f => f == files)); + } + + [Fact] + public async Task Handle_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult() + { + // Arrange + GetTreeFilesQuery getFilesQuery = GetTreeFilesQueryFixture.CreateGetFilesQuery(true); + + IEnumerable files = _fileFixture.CreateMany(); + IEnumerable fileResponses = _fileSystemTreeNodeResponseFixture.CreateMany(files.Count()); + + _mockFileService.GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements) + .Returns(ErrorOrFactory.From(files)); + + _mockMapper.Map>(Arg.Is>(f => f == files)) + .Returns(fileResponses); + + // Act + ErrorOr> result = await _sut.Handle(getFilesQuery, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeAssignableTo>(); + result.Value.Should().BeEquivalentTo(fileResponses); + _mockFileService.Received(1).GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements); + _mockMapper.Received(1).Map>(Arg.Is>(f => f == files)); + } + + [Fact] + public async Task Handle_WhenFileServiceReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetTreeFilesQuery query = _fixture.Create(); + Error error = Error.Failure("FileService.Error", "An error occurred"); + _mockFileService.GetFiles(query.Path, query.IncludeHiddenElements) + .Returns(error); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + _mockFileService.Received(1).GetFiles(query.Path, query.IncludeHiddenElements); + } + + [Fact] + public async Task Handle_WhenFileServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() + { + // Arrange + GetTreeFilesQuery query = _fixture.Create(); + ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); + _mockFileService.GetFiles(query.Path, query.IncludeHiddenElements) + .Returns(emptyList); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEmpty(); + _mockFileService.Received(1).GetFiles(query.Path, query.IncludeHiddenElements); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs new file mode 100644 index 00000000..73722b8e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles; +using Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetTreeFiles.Fixtures; +using Lumina.Domain.Common.Errors; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Files.Queries.GetTreeFiles; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeFilesQueryValidatorTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly GetTreeFilesQueryValidator _validator; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetTreeFilesQueryValidatorTests() + { + _validator = new GetTreeFilesQueryValidator(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Validate_WhenPathIsNull_ShouldHaveValidationError() + { + // Arrange + GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery(); + query = query with { Path = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery(); + query = query with { Path = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() + { + // Arrange + GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery(); + query = query with { Path = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery(); + query = query with { Path = "/valid/path" }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Path); + } + + [Fact] + public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() + { + // Arrange + GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery(); + query = query with { IncludeHiddenElements = true }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + } + + [Fact] + public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() + { + // Arrange + GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery(); + query = query with { IncludeHiddenElements = false }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs new file mode 100644 index 00000000..1a5d8ef7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/CombinePathCommandHandlerTests.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Paths.Commands.CombinePath; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.CombinePath.Fixtures; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.CombinePath; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CombinePathCommandHandlerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly IPathService _mockPathService; + private readonly CombinePathCommandHandler _sut; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public CombinePathCommandHandlerTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockPathService = Substitute.For(); + _sut = new CombinePathCommandHandler(_mockPathService); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task Handle_WhenCalledWithValidCommand_ShouldReturnSuccessResult() + { + // Arrange + CombinePathCommand combinePathCommand = CombinePathCommandFixture.CreateCombinePathCommand(); + string combinedPath = System.IO.Path.Combine(combinePathCommand.OriginalPath, combinePathCommand.NewPath); + + _mockPathService.CombinePath(combinePathCommand.OriginalPath, combinePathCommand.NewPath) + .Returns(ErrorOrFactory.From(combinedPath)); + + // Act + ErrorOr result = await _sut.Handle(combinePathCommand, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeOfType(); + result.Value.Path.Should().Be(combinedPath); + _mockPathService.Received(1).CombinePath(combinePathCommand.OriginalPath, combinePathCommand.NewPath); + } + + [Fact] + public async Task Handle_WhenPathServiceReturnsError_ShouldReturnFailureResult() + { + // Arrange + CombinePathCommand command = _fixture.Create(); + Error error = Error.Failure("PathService.Error", "An error occurred"); + _mockPathService.CombinePath(command.OriginalPath, command.NewPath) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + _mockPathService.Received(1).CombinePath(command.OriginalPath, command.NewPath); + } + + [Fact] + public async Task Handle_WhenPathServiceReturnsEmptyString_ShouldReturnSuccessResultWithEmptyPath() + { + // Arrange + CombinePathCommand command = _fixture.Create(); + _mockPathService.CombinePath(command.OriginalPath, command.NewPath) + .Returns(ErrorOrFactory.From(string.Empty)); + + // Act + ErrorOr result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeOfType(); + result.Value.Path.Should().BeEmpty(); + _mockPathService.Received(1).CombinePath(command.OriginalPath, command.NewPath); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs new file mode 100644 index 00000000..582bb39d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/CombinePathCommandValidatorTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Core.FileManagement.Paths.Commands.CombinePath; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.CombinePath.Fixtures; +using Lumina.Domain.Common.Errors; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.CombinePath; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CombinePathCommandValidatorTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly CombinePathCommandValidator _validator; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public CombinePathCommandValidatorTests() + { + _validator = new CombinePathCommandValidator(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Validate_WhenOriginalPathIsNull_ShouldHaveValidationError() + { + // Arrange + CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand(); + command = command with { OriginalPath = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.OriginalPath) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenOriginalPathIsEmpty_ShouldHaveValidationError() + { + // Arrange + CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand(); + command = command with { OriginalPath = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.OriginalPath) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenOriginalPathIsWhitespace_ShouldHaveValidationError() + { + // Arrange + CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand(); + command = command with { OriginalPath = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.OriginalPath) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenNewPathIsNull_ShouldHaveValidationError() + { + // Arrange + CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand(); + command = command with { NewPath = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPath) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenNewPathIsEmpty_ShouldHaveValidationError() + { + // Arrange + CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand(); + command = command with { NewPath = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPath) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenNewPathIsWhitespace_ShouldHaveValidationError() + { + // Arrange + CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand(); + command = command with { NewPath = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.NewPath) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenBothPathsAreValid_ShouldNotHaveValidationError() + { + // Arrange + CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand(); + command = command with { OriginalPath = "/valid/path", NewPath = "new/segment" }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.OriginalPath); + result.ShouldNotHaveValidationErrorFor(x => x.NewPath); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/Fixtures/CombinePathCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/Fixtures/CombinePathCommandFixture.cs new file mode 100644 index 00000000..45908d7e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/CombinePath/Fixtures/CombinePathCommandFixture.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileManagement.Paths.Commands.CombinePath; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.CombinePath.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class CombinePathCommandFixture +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid command to combine paths. + /// + /// The created command. + public static CombinePathCommand CreateCombinePathCommand() + { + return new Faker() + .CustomInstantiator(f => new CombinePathCommand( + default!, + default! + )) + .RuleFor(x => x.OriginalPath, f => f.System.FilePath()) + .RuleFor(x => x.NewPath, f => f.System.FilePath()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/Fixtures/SplitPathCommandFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/Fixtures/SplitPathCommandFixture.cs new file mode 100644 index 00000000..f1167bfa --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/Fixtures/SplitPathCommandFixture.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.SplitPath.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class SplitPathCommandFixture +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid command for splitting paths. + /// + /// The created command. + public static SplitPathCommand CreateSplitPathCommand() + { + return new Faker() + .CustomInstantiator(f => new SplitPathCommand( + default! + )) + .RuleFor(x => x.Path, f => f.System.FilePath()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs new file mode 100644 index 00000000..fd3984a2 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/SplitPathCommandHandlerTests.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Mapping.FileManagement; +using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.SplitPath.Fixtures; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Mapster; +using MapsterMapper; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.SplitPath; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SplitPathCommandHandlerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly IMapper _mockMapper; + private readonly IPathService _mockPathService; + private readonly SplitPathCommandHandler _sut; + private readonly PathSegmentFixture _pathSegmentFixture; + private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; + private readonly PathSegmentMappingConfig _pathSegmentMappingConfig; + private readonly TypeAdapterConfig _config; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public SplitPathCommandHandlerTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockPathService = Substitute.For(); + _mockMapper = Substitute.For(); + _sut = new SplitPathCommandHandler(_mockPathService, _mockMapper); + _pathSegmentFixture = new PathSegmentFixture(); + _pathSegmentResponseFixture = new PathSegmentResponseFixture(); + + _config = new TypeAdapterConfig(); + _pathSegmentMappingConfig = new PathSegmentMappingConfig(); + _pathSegmentMappingConfig.Register(_config); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task Handle_WhenCalledWithValidCommand_ShouldReturnSuccessResult() + { + // Arrange + SplitPathCommand splitPathCommand = SplitPathCommandFixture.CreateSplitPathCommand(); + + IEnumerable pathSegments = _pathSegmentFixture.CreateMany(); + IEnumerable pathSegmentResponses = _pathSegmentResponseFixture.CreateMany(pathSegments.Count()); + + _mockPathService.ParsePath(splitPathCommand.Path) + .Returns(ErrorOrFactory.From(pathSegments)); + + _mockMapper.Map>(Arg.Any>()) + .Returns(pathSegmentResponses); + + // Act + ErrorOr> result = await _sut.Handle(splitPathCommand, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeAssignableTo>(); + result.Value.Should().BeEquivalentTo(pathSegmentResponses); + _mockPathService.Received(1).ParsePath(splitPathCommand.Path); + _mockMapper.Received(1).Map>(Arg.Any>()); + } + + [Fact] + public async Task Handle_WhenPathServiceReturnsError_ShouldReturnFailureResult() + { + // Arrange + SplitPathCommand command = _fixture.Create(); + Error error = Error.Failure("PathService.Error", "An error occurred"); + _mockPathService.ParsePath(command.Path) + .Returns(error); + + // Act + ErrorOr> result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + _mockPathService.Received(1).ParsePath(command.Path); + _mockMapper.DidNotReceive().Map>(Arg.Any>>()); + } + + [Fact] + public async Task Handle_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() + { + // Arrange + SplitPathCommand command = _fixture.Create(); + ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); + _mockPathService.ParsePath(command.Path) + .Returns(emptyList); + + _mockMapper.Map>(Arg.Any>()) + .Returns([]); + + // Act + ErrorOr> result = await _sut.Handle(command, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEmpty(); + _mockPathService.Received(1).ParsePath(command.Path); + _mockMapper.Received(1).Map>(Arg.Any>()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs new file mode 100644 index 00000000..572c1c02 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Commands/SplitPath/SplitPathCommandValidatorTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.SplitPath.Fixtures; +using Lumina.Domain.Common.Errors; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Commands.SplitPath; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SplitPathCommandValidatorTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly SplitPathCommandValidator _validator; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public SplitPathCommandValidatorTests() + { + _validator = new SplitPathCommandValidator(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Validate_WhenPathIsNull_ShouldHaveValidationError() + { + // Arrange + SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand(); + command = command with { Path = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() + { + // Arrange + SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand(); + command = command with { Path = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() + { + // Arrange + SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand(); + command = command with { Path = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() + { + // Arrange + SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand(); + command = command with { Path = "/valid/path" }; + + // Act + TestValidationResult result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Path); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSegmentFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSegmentFixture.cs new file mode 100644 index 00000000..f587fa12 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSegmentFixture.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using ErrorOr; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class PathSegmentFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public PathSegmentFixture() + { + _faker = new Faker(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// The created . + public PathSegment CreatePathSegment( + string? name = null, + bool? isDirectory = null, + bool? isDrive = null) + { + name ??= _faker.System.FileName(); + isDirectory ??= true; + isDrive ??= false; + + ErrorOr pathResult = PathSegment.Create(name, isDirectory.Value, isDrive.Value); + + if (pathResult.IsError) + throw new InvalidOperationException("Failed to create PathSegment: " + string.Join(", ", pathResult.Errors)); + return pathResult.Value; + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count).Select(_ => CreatePathSegment()).ToList(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSegmentResponseFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSegmentResponseFixture.cs new file mode 100644 index 00000000..a2fe2461 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSegmentResponseFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.FileManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class PathSegmentResponseFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker = new(); + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// The created . + public PathSegmentResponse Create() + { + return new PathSegmentResponse(_faker.System.DirectoryPath()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count).Select(_ => Create()).ToList(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSeparatorResponseFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSeparatorResponseFixture.cs new file mode 100644 index 00000000..487e8727 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Fixtures/PathSeparatorResponseFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.FileManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class PathSeparatorResponseFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker = new(); + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// The created . + public PathSeparatorResponse Create() + { + return new PathSeparatorResponse(_faker.System.DirectoryPath()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count).Select(_ => Create()).ToList(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs new file mode 100644 index 00000000..0fcf9e4b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Paths.Queries.CheckPathExists; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.CheckPathExists.Fixtures; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.CheckPathExists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CheckPathExistsQueryHandlerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IPathService _mockPathService; + private readonly CheckPathExistsQueryHandler _sut; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public CheckPathExistsQueryHandlerTests() + { + _mockPathService = Substitute.For(); + _sut = new CheckPathExistsQueryHandler(_mockPathService); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task Handle_WhenPathExists_ShouldReturnTrueResponse() + { + // Arrange + CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); + _mockPathService.Exists(query.Path).Returns(true); + + // Act + PathExistsResponse result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.Exists.Should().BeTrue(); + _mockPathService.Received(1).Exists(query.Path); + } + + [Fact] + public async Task Handle_WhenPathDoesNotExist_ShouldReturnFalseResponse() + { + // Arrange + CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); + _mockPathService.Exists(query.Path).Returns(false); + + // Act + PathExistsResponse result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.Exists.Should().BeFalse(); + _mockPathService.Received(1).Exists(query.Path); + } + + [Fact] + public async Task Handle_WhenCalledWithNullPath_ShouldStillCallPathService() + { + // Arrange + CheckPathExistsQuery query = new(null!); + _mockPathService.Exists(Arg.Any()).Returns(false); + + // Act + PathExistsResponse result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.Exists.Should().BeFalse(); + _mockPathService.Received(1).Exists(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenCancellationRequested_ShouldStillCompleteOperation() + { + // Arrange + CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); + _mockPathService.Exists(query.Path).Returns(true); + CancellationToken cancellationToken = new(true); + + // Act + PathExistsResponse result = await _sut.Handle(query, cancellationToken); + + // Assert + result.Exists.Should().BeTrue(); + _mockPathService.Received(1).Exists(query.Path); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs new file mode 100644 index 00000000..30f114a0 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryValidatorTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Core.FileManagement.Paths.Queries.CheckPathExists; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.CheckPathExists.Fixtures; +using Lumina.Domain.Common.Errors; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.CheckPathExists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CheckPathExistsQueryValidatorTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly CheckPathExistsQueryValidator _validator; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public CheckPathExistsQueryValidatorTests() + { + _validator = new CheckPathExistsQueryValidator(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Validate_WhenPathIsNull_ShouldHaveValidationError() + { + // Arrange + CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); + query = query with { Path = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() + { + // Arrange + CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); + query = query with { Path = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() + { + // Arrange + CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); + query = query with { Path = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() + { + // Arrange + CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(); + query = query with { Path = "/valid/path" }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Path); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/Fixtures/CheckPathExistsQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/Fixtures/CheckPathExistsQueryFixture.cs new file mode 100644 index 00000000..b8323566 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/CheckPathExists/Fixtures/CheckPathExistsQueryFixture.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileManagement.Paths.Queries.CheckPathExists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.CheckPathExists.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class CheckPathExistsQueryFixture +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid query to check if paths exist. + /// + /// The created query. + public static CheckPathExistsQuery CreateCheckPathExistsQuery() + { + return new Faker() + .CustomInstantiator(f => new CheckPathExistsQuery( + default! + )) + .RuleFor(x => x.Path, f => f.System.FilePath()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/Fixtures/GetPathParentQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/Fixtures/GetPathParentQueryFixture.cs new file mode 100644 index 00000000..11cd45a3 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/Fixtures/GetPathParentQueryFixture.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathParent; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathParent.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathParentQueryFixture +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid query to check if paths exist. + /// + /// The created query. + public static GetPathParentQuery CreateGetPathParentQuery() + { + return new Faker() + .CustomInstantiator(f => new GetPathParentQuery( + default! + )) + .RuleFor(x => x.Path, f => f.System.FilePath()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs new file mode 100644 index 00000000..92ec3a77 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathParent; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathParent.Fixtures; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using MapsterMapper; +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.FileManagement.Pahs.Queries.GetPathParent; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathParentQueryHandlerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly IMapper _mockMapper; + private readonly IPathService _mockPathService; + private readonly GetPathParentQueryHandler _sut; + private readonly PathSegmentFixture _pathSegmentFixture; + private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + public GetPathParentQueryHandlerTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockPathService = Substitute.For(); + _mockMapper = Substitute.For(); + _sut = new GetPathParentQueryHandler(_mockPathService, _mockMapper); + _pathSegmentFixture = new PathSegmentFixture(); + _pathSegmentResponseFixture = new PathSegmentResponseFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task Handle_WhenCalledWithValidQuery_ShouldReturnSuccessResult() + { + // Arrange + GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery(); + + IEnumerable pathSegments = _pathSegmentFixture.CreateMany(); + IEnumerable pathSegmentResponses = _pathSegmentResponseFixture.CreateMany(pathSegments.Count()); + + _mockPathService.GoUpOneLevel(query.Path) + .Returns(ErrorOrFactory.From(pathSegments)); + + _mockMapper.Map>(Arg.Is>(p => p == pathSegments)) + .Returns(pathSegmentResponses); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeAssignableTo>(); + result.Value.Should().BeEquivalentTo(pathSegmentResponses); + _mockPathService.Received(1).GoUpOneLevel(query.Path); + _mockMapper.Received(1).Map>(Arg.Is>(p => p == pathSegments)); + } + + [Fact] + public async Task Handle_WhenPathServiceReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetPathParentQuery query = _fixture.Create(); + Error error = Error.Failure("PathService.Error", "An error occurred"); + _mockPathService.GoUpOneLevel(query.Path) + .Returns(error); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + _mockPathService.Received(1).GoUpOneLevel(query.Path); + _mockMapper.DidNotReceive().Map>(Arg.Any>()); + } + + [Fact] + public async Task Handle_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() + { + // Arrange + GetPathParentQuery query = _fixture.Create(); + ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); + _mockPathService.GoUpOneLevel(query.Path) + .Returns(emptyList); + + _mockMapper.Map>(Arg.Is>(p => !p.Any())) + .Returns([]); + + // Act + ErrorOr> result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEmpty(); + _mockPathService.Received(1).GoUpOneLevel(query.Path); + _mockMapper.Received(1).Map>(Arg.Is>(p => !p.Any())); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs new file mode 100644 index 00000000..c0f56971 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathParent/GetPathParentQueryValidatorTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathParent; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathParent.Fixtures; +using Lumina.Domain.Common.Errors; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathParent; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathParentQueryValidatorTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly GetPathParentQueryValidator _validator; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetPathParentQueryValidatorTests() + { + _validator = new GetPathParentQueryValidator(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Validate_WhenPathIsNull_ShouldHaveValidationError() + { + // Arrange + GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery(); + query = query with { Path = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery(); + query = query with { Path = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() + { + // Arrange + GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery(); + query = query with { Path = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery(); + query = query with { Path = "/valid/path" }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Path); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/Fixtures/GetPathRootQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/Fixtures/GetPathRootQueryFixture.cs new file mode 100644 index 00000000..8e8a2e01 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/Fixtures/GetPathRootQueryFixture.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathRoot; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathRoot.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathRootQueryFixture +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid query to check if paths exist. + /// + /// The created query. + public static GetPathRootQuery CreateGetPathRootQuery() + { + return new Faker() + .CustomInstantiator(f => new GetPathRootQuery( + default! + )) + .RuleFor(x => x.Path, f => f.System.FilePath()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs new file mode 100644 index 00000000..d25e8358 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryHandlerTests.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathRoot; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathRoot.Fixtures; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using MapsterMapper; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathRoot; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathRootQueryHandlerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly IMapper _mockMapper; + private readonly IPathService _mockPathService; + private readonly GetPathRootQueryHandler _sut; + private readonly PathSegmentFixture _pathSegmentFixture; + private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetPathRootQueryHandlerTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockPathService = Substitute.For(); + _mockMapper = Substitute.For(); + _sut = new GetPathRootQueryHandler(_mockPathService, _mockMapper); + _pathSegmentFixture = new PathSegmentFixture(); + _pathSegmentResponseFixture = new PathSegmentResponseFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task Handle_WhenCalledWithValidQuery_ShouldReturnSuccessResult() + { + // Arrange + GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); + PathSegment pathSegment = _pathSegmentFixture.CreatePathSegment(isDrive: true); + PathSegmentResponse pathSegmentResponse = _pathSegmentResponseFixture.Create(); + + _mockPathService.GetPathRoot(query.Path) + .Returns(ErrorOrFactory.From(pathSegment)); + + _mockMapper.Map(Arg.Is(p => p == pathSegment)) + .Returns(pathSegmentResponse); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEquivalentTo(pathSegmentResponse); + _mockPathService.Received(1).GetPathRoot(query.Path); + _mockMapper.Received(1).Map(Arg.Is(p => p == pathSegment)); + } + + [Fact] + public async Task Handle_WhenPathServiceReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); + Error error = Error.Failure("PathService.Error", "An error occurred"); + _mockPathService.GetPathRoot(query.Path) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + _mockPathService.Received(1).GetPathRoot(query.Path); + _mockMapper.DidNotReceive().Map(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenPathServiceReturnsRootPathSegment_ShouldReturnRootSuccessResult() + { + // Arrange + GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); + PathSegment rootPathSegment = _pathSegmentFixture.CreatePathSegment(name: "/", isDirectory: true, isDrive: true); + PathSegmentResponse rootResponse = _pathSegmentResponseFixture.Create(); + + _mockPathService.GetPathRoot(query.Path) + .Returns(ErrorOrFactory.From(rootPathSegment)); + + _mockMapper.Map(Arg.Is(p => p == rootPathSegment)) + .Returns(rootResponse); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEquivalentTo(rootResponse); + _mockPathService.Received(1).GetPathRoot(query.Path); + _mockMapper.Received(1).Map(Arg.Is(p => p == rootPathSegment)); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs new file mode 100644 index 00000000..59c3fc43 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathRoot/GetPathRootQueryValidatorTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathRoot; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathRoot.Fixtures; +using Lumina.Domain.Common.Errors; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathRoot; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathRootQueryValidatorTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly GetPathRootQueryValidator _validator; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetPathRootQueryValidatorTests() + { + _validator = new GetPathRootQueryValidator(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Validate_WhenPathIsNull_ShouldHaveValidationError() + { + // Arrange + GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); + query = query with { Path = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); + query = query with { Path = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() + { + // Arrange + GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); + query = query with { Path = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery(); + query = query with { Path = "/valid/path" }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Path); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs new file mode 100644 index 00000000..e0fc358e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/GetPathSeparator/GetPathSeparatorQueryHandlerTests.cs @@ -0,0 +1,105 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathSeparator; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.GetPathSeparator; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathSeparatorQueryHandlerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IPathService _mockPathService; + private readonly GetPathSeparatorQueryHandler _sut; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public GetPathSeparatorQueryHandlerTests() + { + _mockPathService = Substitute.For(); + _sut = new GetPathSeparatorQueryHandler(_mockPathService); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task Handle_WhenCalled_ShouldReturnPathSeparatorResponse() + { + // Arrange + GetPathSeparatorQuery query = new(); + char expectedSeparator = System.IO.Path.DirectorySeparatorChar; + _mockPathService.PathSeparator.Returns(expectedSeparator); + + // Act + PathSeparatorResponse result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.Should().NotBeNull(); + result.Separator.Should().Be(expectedSeparator.ToString()); + + _mockPathService.Received(1); + } + + [Theory] + [InlineData('/')] + [InlineData('\\')] + public async Task Handle_WithDifferentSeparators_ShouldReturnCorrectSeparator(char separator) + { + // Arrange + GetPathSeparatorQuery query = new(); + _mockPathService.PathSeparator.Returns(separator); + + // Act + PathSeparatorResponse result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.Should().NotBeNull(); + result.Separator.Should().Be(separator.ToString()); + _mockPathService.Received(1); + } + + [Fact] + public async Task Handle_WhenCalledMultipleTimes_ShouldReturnSameResult() + { + // Arrange + GetPathSeparatorQuery query = new(); + char expectedSeparator = System.IO.Path.DirectorySeparatorChar; + _mockPathService.PathSeparator.Returns(expectedSeparator); + + // Act + PathSeparatorResponse result1 = await _sut.Handle(query, CancellationToken.None); + PathSeparatorResponse result2 = await _sut.Handle(query, CancellationToken.None); + + // Assert + result1.Should().BeEquivalentTo(result2); + _mockPathService.Received(2); + } + + [Fact] + public async Task Handle_WithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + GetPathSeparatorQuery query = new(); + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => await _sut.Handle(query, cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/Fixtures/ValidatePathQueryFixure.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/Fixtures/ValidatePathQueryFixure.cs new file mode 100644 index 00000000..18cca19b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/Fixtures/ValidatePathQueryFixure.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileManagement.Paths.Queries.ValidatePath; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.ValidatePath.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathQueryFixure +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid query to check if paths exist. + /// + /// The created query. + public static ValidatePathQuery CreateValidatePathQuery() + { + return new Faker() + .CustomInstantiator(f => new ValidatePathQuery( + default! + )) + .RuleFor(x => x.Path, f => f.System.FilePath()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs new file mode 100644 index 00000000..c16d8ee8 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/ValidatePathQueryHandlerTests.cs @@ -0,0 +1,98 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Paths.Queries.ValidatePath; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.ValidatePath.Fixtures; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.ValidatePath; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathQueryHandlerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IPathService _mockPathService; + private readonly ValidatePathQueryHandler _sut; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public ValidatePathQueryHandlerTests() + { + _mockPathService = Substitute.For(); + _sut = new ValidatePathQueryHandler(_mockPathService); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task Handle_WhenCalledWithValidPath_ShouldReturnTrueResponse() + { + // Arrange + ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); + _mockPathService.IsValidPath(query.Path).Returns(true); + + // Act + PathValidResponse result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsValid.Should().BeTrue(); + _mockPathService.Received(1).IsValidPath(query.Path); + } + + [Fact] + public async Task Handle_WhenCalledWithInvalidPath_ShouldReturnFalseResponse() + { + // Arrange + ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); + _mockPathService.IsValidPath(query.Path).Returns(false); + + // Act + PathValidResponse result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsValid.Should().BeFalse(); + _mockPathService.Received(1).IsValidPath(query.Path); + } + + [Fact] + public async Task Handle_WhenCalledWithNullPath_ShouldReturnFalseResponse() + { + // Arrange + ValidatePathQuery query = new(null!); + _mockPathService.IsValidPath(Arg.Any()).Returns(false); + + // Act + PathValidResponse result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsValid.Should().BeFalse(); + _mockPathService.Received(1).IsValidPath(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenCalledWithEmptyPath_ShouldReturnFalseResponse() + { + // Arrange + ValidatePathQuery query = new(string.Empty); + _mockPathService.IsValidPath(Arg.Any()).Returns(false); + + // Act + PathValidResponse result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsValid.Should().BeFalse(); + _mockPathService.Received(1).IsValidPath(Arg.Any()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs new file mode 100644 index 00000000..5dc5b812 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Pahs/Queries/ValidatePath/ValidatePathQueryValidatorTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation.TestHelper; +using Lumina.Application.Core.FileManagement.Paths.Queries.ValidatePath; +using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.ValidatePath.Fixtures; +using Lumina.Domain.Common.Errors; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Pahs.Queries.ValidatePath; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathQueryValidatorTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly ValidatePathQueryValidator _validator; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public ValidatePathQueryValidatorTests() + { + _validator = new ValidatePathQueryValidator(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Validate_WhenPathIsNull_ShouldHaveValidationError() + { + // Arrange + ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); + query = query with { Path = null! }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() + { + // Arrange + ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); + query = query with { Path = string.Empty }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() + { + // Arrange + ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); + query = query with { Path = " " }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationErrorFor(x => x.Path) + .WithErrorMessage(Errors.FileManagement.PathCannotBeEmpty.Code); + } + + [Fact] + public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() + { + // Arrange + ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery(); + query = query with { Path = "/valid/path" }; + + // Act + TestValidationResult result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationErrorFor(x => x.Path); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Fixtures/ThumbnailResponseFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Fixtures/ThumbnailResponseFixture.cs new file mode 100644 index 00000000..79113cd6 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Fixtures/ThumbnailResponseFixture.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Enums.PhotoLibrary; +using Lumina.Contracts.Responses.FileManagement; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Thumbnails.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ThumbnailResponseFixture +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid query to get a thumbnail. + /// + /// The created query. + public static ThumbnailResponse CreateThumbnailResponse() + { + return new Faker() + .CustomInstantiator(f => new ThumbnailResponse( + default, + default! + )) + .RuleFor(x => x.Type, f => f.PickRandom()) + .RuleFor(x => x.Bytes, f => f.Random.Bytes(20)); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/Fixtures/GetThumbnailQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/Fixtures/GetThumbnailQueryFixture.cs new file mode 100644 index 00000000..2ad00692 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/Fixtures/GetThumbnailQueryFixture.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Thumbnails.Queries.GetThumbnail.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThumbnailQueryFixture +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid query to get a thumbnail. + /// + /// The created query. + public static GetThumbnailQuery CreateGetThumbnailQuery() + { + return new Faker() + .CustomInstantiator(f => new GetThumbnailQuery( + default!, + default + )) + .RuleFor(x => x.Path, f => f.System.FilePath()) + .RuleFor(x => x.Quality, f => f.Random.Int()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs new file mode 100644 index 00000000..ef6c04cd --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Thumbnails/Queries/GetThumbnail/GetThumbnailQueryHandlerTests.cs @@ -0,0 +1,104 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail; +using Lumina.Application.UnitTests.Core.FileManagement.Thumbnails.Fixtures; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using MapsterMapper; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.FileManagement.Thumbnails.Queries.GetThumbnail; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThumbnailQueryHandlerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly IThumbnailService _mockThumbnailService; + private readonly IMapper _mockMapper; + private readonly GetThumbnailQueryHandler _sut; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + public GetThumbnailQueryHandlerTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockThumbnailService = Substitute.For(); + _mockMapper = Substitute.For(); + _sut = new GetThumbnailQueryHandler(_mockThumbnailService, _mockMapper); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task Handle_WhenCalledWithValidQuery_ShouldReturnSuccessResult() + { + // Arrange + GetThumbnailQuery query = _fixture.Create(); + Thumbnail thumbnail = _fixture.Create(); + ThumbnailResponse thumbnailResponse = ThumbnailResponseFixture.CreateThumbnailResponse(); + + _mockThumbnailService.GetThumbnailAsync(query.Path, query.Quality, Arg.Any()) + .Returns(ErrorOrFactory.From(thumbnail)); + + _mockMapper.Map(Arg.Is(t => t == thumbnail)) + .Returns(thumbnailResponse); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEquivalentTo(thumbnailResponse); + await _mockThumbnailService.Received(1).GetThumbnailAsync(query.Path, query.Quality, Arg.Any()); + _mockMapper.Received(1).Map(Arg.Is(t => t == thumbnail)); + } + + [Fact] + public async Task Handle_WhenThumbnailServiceReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetThumbnailQuery query = _fixture.Create(); + Error error = Error.Failure("ThumbnailService.Error", "An error occurred"); + _mockThumbnailService.GetThumbnailAsync(query.Path, query.Quality, Arg.Any()) + .Returns(error); + + // Act + ErrorOr result = await _sut.Handle(query, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(error); + await _mockThumbnailService.Received(1).GetThumbnailAsync(query.Path, query.Quality, Arg.Any()); + _mockMapper.DidNotReceive().Map(Arg.Any()); + } + + [Fact] + public async Task Handle_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetThumbnailQuery query = _fixture.Create(); + CancellationTokenSource cts = new(); + cts.Cancel(); + + _mockThumbnailService.GetThumbnailAsync(query.Path, query.Quality, cts.Token) + .Returns(Task.FromCanceled>(cts.Token)); + + // Act & Assert + await Assert.ThrowsAsync(() => _sut.Handle(query, cts.Token).AsTask()); + await _mockThumbnailService.Received(1).GetThumbnailAsync(query.Path, query.Quality, cts.Token); + _mockMapper.DidNotReceive().Map(Arg.Any()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs index a97f16c2..c3c53341 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Bogus; using FluentValidation.TestHelper; using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; @@ -13,7 +13,7 @@ using System.Linq; namespace Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; /// -/// Contains unit tests for the class. +/// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] public class AddBookCommandValidatorTests @@ -1894,4 +1894,4 @@ public class AddBookCommandValidatorTests result.ShouldNotHaveValidationErrorFor(x => x.Ratings[0].VoteCount); } #endregion -} \ No newline at end of file +}