Merge pull request #13 from BinaryAlley/refactor/add-file-system-application-unit-tests

Adds Application layer unit tests for file system browser dialog
This commit is contained in:
BinaryAlley authored and GitHub committed 2024-10-05 09:36:59 +03:00
commit 33f5936ab9
79 files changed
+5484 -91

No files matched your search

@@ -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<List<FileSystemTreeNodeResponse>>())
.MapToConstructor(true);
config.NewConfig<Directory, DirectoryResponse>()
@@ -49,4 +49,4 @@ public class DirectoryMappingConfig : IRegister
));
}
#endregion
}
}
@@ -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<FileSystemTreeNodeResponse>(config)).ToList());
config.NewConfig<FileSystemTreeNodeResponse, UnixRootItem>()
.MapWith(src => UnixRootItem.Create(
@@ -46,15 +49,19 @@ public class FileSystemTreeMappingConfig : IRegister
.Value);
config.NewConfig<FileSystemItem, FileSystemTreeNodeResponse>()
.MapWith(src => new FileSystemTreeNodeResponse
{
Path = src.Id.Path,
Name = src.Name,
ItemType = src.Type,
IsExpanded = false,
ChildrenLoaded = false,
Children = new List<FileSystemTreeNodeResponse>()
});
.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<FileSystemTreeNodeResponse>(config)).ToList();
else
dest.Children = [];
});
}
#endregion
}
}
@@ -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<GetDirectoriesQuery, E
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IDirectoryService _directoryService;
private readonly IMapper _mapper;
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -26,9 +28,11 @@ public class GetDirectoriesQueryHandler : IRequestHandler<GetDirectoriesQuery, E
/// Initializes a new instance of the <see cref="GetDirectoriesQueryHandler"/> class.
/// </summary>
/// <param name="directoryService">Injected service for handling directories.</param>
public GetDirectoriesQueryHandler(IDirectoryService directoryService)
/// <param name="mapper">Injected service for mapping objects.</param>
public GetDirectoriesQueryHandler(IDirectoryService directoryService, IMapper mapper)
{
_directoryService = directoryService;
_mapper = mapper;
}
#endregion
@@ -44,7 +48,7 @@ public class GetDirectoriesQueryHandler : IRequestHandler<GetDirectoriesQuery, E
public ValueTask<ErrorOr<IEnumerable<DirectoryResponse>>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<Directory>> result = _directoryService.GetSubdirectories(request.Path, request.IncludeHiddenElements);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<DirectoryResponse>>()), errors => errors));
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map<IEnumerable<DirectoryResponse>>(values)), errors => errors));
}
#endregion
}
}
@@ -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<GetTreeDirectories
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IDirectoryService _directoryService;
private readonly IMapper _mapper;
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -26,9 +28,11 @@ public class GetTreeDirectoriesQueryHandler : IRequestHandler<GetTreeDirectories
/// Initializes a new instance of the <see cref="GetTreeDirectoriesQueryHandler"/> class.
/// </summary>
/// <param name="directoryService">Injected service for handling directories.</param>
public GetTreeDirectoriesQueryHandler(IDirectoryService directoryService)
/// <param name="mapper">Injected service for mapping objects.</param>
public GetTreeDirectoriesQueryHandler(IDirectoryService directoryService, IMapper mapper)
{
_directoryService = directoryService;
_mapper = mapper;
}
#endregion
@@ -44,7 +48,7 @@ public class GetTreeDirectoriesQueryHandler : IRequestHandler<GetTreeDirectories
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetTreeDirectoriesQuery request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<Directory>> result = _directoryService.GetSubdirectories(request.Path, request.IncludeHiddenElements);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>()), errors => errors));
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map<IEnumerable<FileSystemTreeNodeResponse>>(values)), errors => errors));
}
#endregion
}
}
@@ -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<GetDrivesQuery, ErrorOr<IEn
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IDriveService _driveService;
private readonly IMapper _mapper;
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -26,9 +28,11 @@ public class GetDrivesQueryHandler : IRequestHandler<GetDrivesQuery, ErrorOr<IEn
/// Initializes a new instance of the <see cref="GetDrivesQueryHandler"/> class.
/// </summary>
/// <param name="driveService">Injected service for handling file system drives.</param>
public GetDrivesQueryHandler(IDriveService driveService)
/// <param name="mapper">Injected service for mapping objects.</param>
public GetDrivesQueryHandler(IDriveService driveService, IMapper mapper)
{
_driveService = driveService;
_mapper = mapper;
}
#endregion
@@ -44,7 +48,7 @@ public class GetDrivesQueryHandler : IRequestHandler<GetDrivesQuery, ErrorOr<IEn
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetDrivesQuery request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemItem>> result = _driveService.GetDrives();
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.Adapt<IEnumerable<FileSystemTreeNodeResponse>>()), errors => errors));
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map<IEnumerable<FileSystemTreeNodeResponse>>(values)), errors => errors));
}
#endregion
}
}
@@ -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;
/// <summary>
/// Query for retrieving the file system type.
/// </summary>
public record GetFileSystemQuery() : IRequest<FileSystemTypeResponse>;
public record GetFileSystemQuery() : IRequest<FileSystemTypeResponse>;
@@ -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;
/// <summary>
/// Handler for the query to get the file system type.
@@ -40,4 +40,4 @@ public class GetFileSystemQueryHandler : IRequestHandler<GetFileSystemQuery, Fil
return ValueTask.FromResult(new FileSystemTypeResponse(_platformContext.Platform));
}
#endregion
}
}
@@ -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 GetFilesQueryHandler : IRequestHandler<GetFilesQuery, ErrorOr<IEnum
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IFileService _fileService;
private readonly IMapper _mapper;
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -26,9 +28,11 @@ public class GetFilesQueryHandler : IRequestHandler<GetFilesQuery, ErrorOr<IEnum
/// Initializes a new instance of the <see cref="GetFilesQueryHandler"/> class.
/// </summary>
/// <param name="fileService">Injected service for handling files.</param>
public GetFilesQueryHandler(IFileService fileService)
/// <param name="mapper">Injected service for mapping objects.</param>
public GetFilesQueryHandler(IFileService fileService, IMapper mapper)
{
_fileService = fileService;
_mapper = mapper;
}
#endregion
@@ -44,7 +48,7 @@ public class GetFilesQueryHandler : IRequestHandler<GetFilesQuery, ErrorOr<IEnum
public ValueTask<ErrorOr<IEnumerable<FileResponse>>> Handle(GetFilesQuery request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<File>> result = _fileService.GetFiles(request.Path, request.IncludeHiddenElements);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<FileResponse>>()), errors => errors));
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map<IEnumerable<FileResponse>>(values)), errors => errors));
}
#endregion
}
}
@@ -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<GetTreeFilesQuery, Error
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IFileService _fileService;
private readonly IMapper _mapper;
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -26,9 +28,11 @@ public class GetTreeFilesQueryHandler : IRequestHandler<GetTreeFilesQuery, Error
/// Initializes a new instance of the <see cref="GetTreeFilesQueryHandler"/> class.
/// </summary>
/// <param name="fileService">Injected service for handling files.</param>
public GetTreeFilesQueryHandler(IFileService fileService)
/// <param name="mapper">Injected service for mapping objects.</param>
public GetTreeFilesQueryHandler(IFileService fileService, IMapper mapper)
{
_fileService = fileService;
_mapper = mapper;
}
#endregion
@@ -44,7 +48,7 @@ public class GetTreeFilesQueryHandler : IRequestHandler<GetTreeFilesQuery, Error
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetTreeFilesQuery request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<File>> result = _fileService.GetFiles(request.Path, request.IncludeHiddenElements);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<FileSystemTreeNodeResponse>>()), errors => errors));
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map<IEnumerable<FileSystemTreeNodeResponse>>(values)), errors => errors));
}
#endregion
}
}
@@ -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<SplitPathCommand, ErrorOr
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IPathService _pathService;
private readonly IMapper _mapper;
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -26,9 +27,11 @@ public class SplitPathCommandHandler : IRequestHandler<SplitPathCommand, ErrorOr
/// Initializes a new instance of the <see cref="SplitPathCommandHandler"/> class.
/// </summary>
/// <param name="pathService">Injected service for handling file system paths.</param>
public SplitPathCommandHandler(IPathService pathService)
/// <param name="mapper">Injected service for mapping objects.</param>
public SplitPathCommandHandler(IPathService pathService, IMapper mapper)
{
_pathService = pathService;
_mapper = mapper;
}
#endregion
@@ -44,7 +47,7 @@ public class SplitPathCommandHandler : IRequestHandler<SplitPathCommand, ErrorOr
public ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>> Handle(SplitPathCommand request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PathSegment>> result = _pathService.ParsePath(request.Path);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<PathSegmentResponse>>()), errors => errors));
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map<IEnumerable<PathSegmentResponse>>(values)), errors => errors));
}
#endregion
}
}
@@ -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<GetPathParentQuery, Err
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IPathService _pathService;
private readonly IMapper _mapper;
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -26,9 +27,11 @@ public class GetPathParentQueryHandler : IRequestHandler<GetPathParentQuery, Err
/// Initializes a new instance of the <see cref="GetPathParentQueryHandler"/> class.
/// </summary>
/// <param name="pathService">Injected service for managing file system paths.</param>
public GetPathParentQueryHandler(IPathService pathService)
/// <param name="mapper">Injected service for mapping objects.</param>
public GetPathParentQueryHandler(IPathService pathService, IMapper mapper)
{
_pathService = pathService;
_mapper = mapper;
}
#endregion
@@ -44,7 +47,7 @@ public class GetPathParentQueryHandler : IRequestHandler<GetPathParentQuery, Err
public ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>> Handle(GetPathParentQuery request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PathSegment>> result = _pathService.GoUpOneLevel(request.Path);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<IEnumerable<PathSegmentResponse>>()), errors => errors));
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map<IEnumerable<PathSegmentResponse>>(values)), errors => errors));
}
#endregion
}
}
@@ -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<GetPathRootQuery, ErrorOr
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IPathService _pathService;
private readonly IMapper _mapper;
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -25,9 +26,11 @@ public class GetPathRootQueryHandler : IRequestHandler<GetPathRootQuery, ErrorOr
/// Initializes a new instance of the <see cref="GetPathRootQueryHandler"/> class.
/// </summary>
/// <param name="pathService">Injected service for managing file system paths.</param>
public GetPathRootQueryHandler(IPathService pathService)
/// <param name="mapper">Injected service for mapping objects.</param>
public GetPathRootQueryHandler(IPathService pathService, IMapper mapper)
{
_pathService = pathService;
_mapper = mapper;
}
#endregion
@@ -41,7 +44,7 @@ public class GetPathRootQueryHandler : IRequestHandler<GetPathRootQuery, ErrorOr
public ValueTask<ErrorOr<PathSegmentResponse>> Handle(GetPathRootQuery request, CancellationToken cancellationToken)
{
ErrorOr<PathSegment> result = _pathService.GetPathRoot(request.Path);
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<PathSegmentResponse>()), errors => errors));
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map<PathSegmentResponse>(values)), errors => errors));
}
#endregion
}
}
@@ -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<GetThumbnailQuery, Error
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IThumbnailService _thumbnailsService;
private readonly IMapper _mapper;
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -25,9 +26,11 @@ public class GetThumbnailQueryHandler : IRequestHandler<GetThumbnailQuery, Error
/// Initializes a new instance of the <see cref="GetThumbnailQueryHandler"/> class.
/// </summary>
/// <param name="thumbnailsService">Injected service for handling thumbnails.</param>
public GetThumbnailQueryHandler(IThumbnailService thumbnailsService)
/// <param name="mapper">Injected service for mapping objects.</param>
public GetThumbnailQueryHandler(IThumbnailService thumbnailsService, IMapper mapper)
{
_thumbnailsService = thumbnailsService;
_mapper = mapper;
}
#endregion
@@ -41,7 +44,7 @@ public class GetThumbnailQueryHandler : IRequestHandler<GetThumbnailQuery, Error
public async ValueTask<ErrorOr<ThumbnailResponse>> Handle(GetThumbnailQuery request, CancellationToken cancellationToken)
{
ErrorOr<Thumbnail> result = await _thumbnailsService.GetThumbnailAsync(request.Path, request.Quality, cancellationToken);
return await ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(result.Value.Adapt<ThumbnailResponse>()), errors => errors));
return await ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(_mapper.Map<ThumbnailResponse>(values)), errors => errors));
}
#endregion
}
@@ -1,14 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.FileManagement;
/// <summary>
/// Represents a response containing the result of splitting a file system path.
/// </summary>
/// <param name="PathSegments">The returned path segments.</param>
[DebuggerDisplay("{PathSegments}")]
public record SplitPathResponse(
string[] PathSegments
);
@@ -94,16 +94,19 @@ public class UnixPathStrategy : IUnixPathStrategy
return Errors.FileManagement.InvalidPath;
// get the path segments
List<string> splitSegments = [.. path.Path.Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries)];
IEnumerable<PathSegment> segments = splitSegments.Select((segment, index) =>
IEnumerable<ErrorOr<PathSegment>> 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<PathSegment> segment in segmentsResults)
if (segment.IsError)
return segment.Errors;
return ErrorOrFactory.From(segmentsResults.Select(segmentResult => segmentResult.Value));
}
/// <summary>
@@ -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
@@ -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<PathSegment> GetPathSegments()
IEnumerable<ErrorOr<PathSegment>> getPathSegmentsResults = GetPathSegments();
foreach (ErrorOr<PathSegment> getPathSegmentsResult in getPathSegmentsResults)
if (getPathSegmentsResult.IsError)
return getPathSegmentsResult.Errors;
return ErrorOrFactory.From(getPathSegmentsResults.Select(getPathSegmentsResult => getPathSegmentsResult.Value));
IEnumerable<ErrorOr<PathSegment>> 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;
@@ -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
/// <param name="name">The name of the path segment.</param>
/// <param name="isDirectory">Value indicating if the current path segment is a file system directory or not.</param>
/// <param name="isDrive">Value indicating if the current path segment is a file system drive or not.</param>
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 ===================================================================================
/// <summary>
/// Creates a new instance of the <see cref="PathSegment"/> class.
/// </summary>
/// <param name="name">The name of the path segment.</param>
/// <param name="isDirectory">Value indicating if the current path segment is a file system directory or not.</param>
/// <param name="isDrive">Value indicating if the current path segment is a file system drive or not.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="PathSegment"/> or an error message.
/// </returns>
public static ErrorOr<PathSegment> Create(string name, bool isDirectory, bool isDrive)
{
if (string.IsNullOrWhiteSpace(name))
return Errors.FileManagement.NameCannotBeEmpty;
return new PathSegment(name, isDirectory, isDrive);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
@@ -53,4 +71,4 @@ public class PathSegment : ValueObject
yield return IsDrive;
}
#endregion
}
}
@@ -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;
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Mediator;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Behaviors.Fixtures;
/// <summary>
/// Fixture class for the <see cref="ValidationBehavior"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidationBehaviorFixture : IRequest<ErrorOr<ValidationBehaviorTestResponse>>
{
}
@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Behaviors.Fixtures;
/// <summary>
/// Fixture test class for validation behavior responses.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidationBehaviorTestResponse
{
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="ValidationBehavior"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidationBehaviorTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IValidator<ValidationBehaviorFixture> _mockValidator;
private readonly MessageHandlerDelegate<ValidationBehaviorFixture, ErrorOr<ValidationBehaviorTestResponse>> _nextDelegate;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="ValidationBehaviorTests"/> class.
/// </summary>
public ValidationBehaviorTests()
{
_mockValidator = Substitute.For<IValidator<ValidationBehaviorFixture>>();
_nextDelegate = Substitute.For<MessageHandlerDelegate<ValidationBehaviorFixture, ErrorOr<ValidationBehaviorTestResponse>>>();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public async Task Handle_WhenValidatorIsNull_ShouldInvokeNextDelegate()
{
// Arrange
ValidationBehavior<ValidationBehaviorFixture, ErrorOr<ValidationBehaviorTestResponse>> behavior = new();
ValidationBehaviorFixture request = new();
ValidationBehaviorTestResponse expectedResponse = new();
_nextDelegate.Invoke(request, Arg.Any<CancellationToken>()).Returns(new ValueTask<ErrorOr<ValidationBehaviorTestResponse>>(ErrorOrFactory.From(expectedResponse)));
// Act
ErrorOr<ValidationBehaviorTestResponse> 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<CancellationToken>());
}
[Fact]
public async Task Handle_WhenValidationSucceeds_ShouldInvokeNextDelegate()
{
// Arrange
ValidationBehavior<ValidationBehaviorFixture, ErrorOr<ValidationBehaviorTestResponse>> behavior = new(_mockValidator);
ValidationBehaviorFixture request = new();
ValidationBehaviorTestResponse expectedResponse = new();
_mockValidator.ValidateAsync(request, Arg.Any<CancellationToken>()).Returns(new ValidationResult());
_nextDelegate.Invoke(request, Arg.Any<CancellationToken>()).Returns(new ValueTask<ErrorOr<ValidationBehaviorTestResponse>>(ErrorOrFactory.From(expectedResponse)));
// Act
ErrorOr<ValidationBehaviorTestResponse> 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<CancellationToken>());
await _nextDelegate.Received(1).Invoke(request, Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_WhenValidationFails_ShouldReturnErrors()
{
// Arrange
ValidationBehavior<ValidationBehaviorFixture, ErrorOr<ValidationBehaviorTestResponse>> behavior = new(_mockValidator);
ValidationBehaviorFixture request = new();
List<ValidationFailure> validationFailures =
[
new ValidationFailure("Property1", "Error message 1"),
new ValidationFailure("Property2", "Error message 2")
];
_mockValidator.ValidateAsync(request, Arg.Any<CancellationToken>()).Returns(new ValidationResult(validationFailures));
// Act
ErrorOr<ValidationBehaviorTestResponse> 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<CancellationToken>());
await _nextDelegate.DidNotReceive().Invoke(request, Arg.Any<CancellationToken>());
}
#endregion
}
@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Converters.Fixtures;
/// <summary>
/// Fixture class for the <see cref="OptionalJsonConverterFactory"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class OptionalJsonConverterFactoryFixture
{
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetFilesQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class OptionalJsonConverterFactoryTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly OptionalJsonConverterFactory _factory;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="OptionalJsonConverterFactoryTests"/> class.
/// </summary>
public OptionalJsonConverterFactoryTests()
{
_factory = new OptionalJsonConverterFactory();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void CanConvert_WhenTypeIsOptional_ShouldReturnTrue()
{
// Arrange
Type typeToConvert = typeof(Optional<string>);
// 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<string>);
// Act
bool result = _factory.CanConvert(typeToConvert);
// Assert
result.Should().BeFalse();
}
[Fact]
public void CreateConverter_WhenTypeIsOptionalString_ShouldReturnCorrectConverterType()
{
// Arrange
Type typeToConvert = typeof(Optional<string>);
JsonSerializerOptions options = new();
// Act
JsonConverter converter = _factory.CreateConverter(typeToConvert, options);
// Assert
converter.Should().BeOfType<OptionalJsonConverter<string>>();
}
[Fact]
public void CreateConverter_WhenTypeIsOptionalInt_ShouldReturnCorrectConverterType()
{
// Arrange
Type typeToConvert = typeof(Optional<int>);
JsonSerializerOptions options = new();
// Act
JsonConverter converter = _factory.CreateConverter(typeToConvert, options);
// Assert
converter.Should().BeOfType<OptionalJsonConverter<int>>();
}
[Fact]
public void CreateConverter_WhenTypeIsOptionalCustomClass_ShouldReturnCorrectConverterType()
{
// Arrange
Type typeToConvert = typeof(Optional<OptionalJsonConverterFactoryFixture>);
JsonSerializerOptions options = new();
// Act
JsonConverter converter = _factory.CreateConverter(typeToConvert, options);
// Assert
converter.Should().BeOfType<OptionalJsonConverter<OptionalJsonConverterFactoryFixture>>();
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="OptionalJsonConverter"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class OptionalJsonConverterTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly JsonSerializerOptions _options;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="OptionalJsonConverterTests"/> class.
/// </summary>
public OptionalJsonConverterTests()
{
_options = new JsonSerializerOptions();
_options.Converters.Add(new OptionalJsonConverter<string>());
_options.Converters.Add(new OptionalJsonConverter<int>());
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void Read_WhenJsonIsNull_ShouldReturnNone()
{
// Arrange
string json = "null";
// Act
Optional<string> result = JsonSerializer.Deserialize<Optional<string>>(json, _options);
// Assert
result.HasValue.Should().BeFalse();
}
[Fact]
public void Read_WhenJsonHasStringValue_ShouldReturnSomeWithCorrectValue()
{
// Arrange
string json = "\"test\"";
// Act
Optional<string> result = JsonSerializer.Deserialize<Optional<string>>(json, _options);
// Assert
result.HasValue.Should().BeTrue();
result.Value.Should().Be("test");
}
[Fact]
public void Read_WhenJsonHasIntValue_ShouldReturnSomeWithCorrectValue()
{
// Arrange
string json = "42";
// Act
Optional<int> result = JsonSerializer.Deserialize<Optional<int>>(json, _options);
// Assert
result.HasValue.Should().BeTrue();
result.Value.Should().Be(42);
}
[Fact]
public void Write_WhenOptionalHasNoValue_ShouldWriteNull()
{
// Arrange
Optional<string> optional = Optional<string>.None();
// Act
string json = JsonSerializer.Serialize(optional, _options);
// Assert
json.Should().Be("null");
}
[Fact]
public void Write_WhenOptionalHasStringValue_ShouldWriteCorrectJson()
{
// Arrange
Optional<string> optional = Optional<string>.Some("test");
// Act
string json = JsonSerializer.Serialize(optional, _options);
// Assert
json.Should().Be("\"test\"");
}
[Fact]
public void Write_WhenOptionalHasIntValue_ShouldWriteCorrectJson()
{
// Arrange
Optional<int> optional = Optional<int>.Some(42);
// Act
string json = JsonSerializer.Serialize(optional, _options);
// Assert
json.Should().Be("42");
}
[Fact]
public void ReadWrite_WhenSerializingAndDeserializingSomeValue_ShouldPreserveValue()
{
// Arrange
Optional<string> original = Optional<string>.Some("test");
// Act
string json = JsonSerializer.Serialize(original, _options);
Optional<string> deserialized = JsonSerializer.Deserialize<Optional<string>>(json, _options);
// Assert
deserialized.Should().Be(original);
}
[Fact]
public void ReadWrite_WhenSerializingAndDeserializingNone_ShouldPreserveNone()
{
// Arrange
Optional<string> original = Optional<string>.None();
// Act
string json = JsonSerializer.Serialize(original, _options);
Optional<string> deserialized = JsonSerializer.Deserialize<Optional<string>>(json, _options);
// Assert
deserialized.Should().Be(original);
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="DirectoryMappingConfig"/> class.
/// </summary>
[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<FileSystemItem> childItems =
[
directoryFixture.CreateDirectory(),
directoryFixture.CreateDirectory()
];
foreach (FileSystemItem item in childItems)
directory.AddItem(item);
// Act
FileSystemTreeNodeResponse result = directory.Adapt<FileSystemTreeNodeResponse>(_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<DirectoryResponse>(_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<List<FileSystemItemModel>>();
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<FileSystemItemModel>(_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
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="FileMappingConfig"/> class.
/// </summary>
[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<FileSystemTreeNodeResponse>(_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<FileResponse>(_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<FileResponse>(_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
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="FileSystemTreeMappingConfig"/> class.
/// </summary>
[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<FileSystemTreeNodeResponse>(_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<WindowsRootItem>(_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<FileSystemTreeNodeResponse>(_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<UnixRootItem>(_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<FileSystemTreeNodeResponse>(_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<FileSystemTreeNodeResponse>(_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
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="PathSegmentMappingConfig"/> class.
/// </summary>
[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<PathSegment> createResult = PathSegment.Create("TestSegment", true, false);
createResult.IsError.Should().BeFalse();
PathSegment pathSegment = createResult.Value;
// Act
PathSegmentResponse result = pathSegment.Adapt<PathSegmentResponse>(_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<PathSegment> createResult = PathSegment.Create(name, isDirectory, isDrive);
createResult.IsError.Should().BeFalse();
PathSegment pathSegment = createResult.Value;
// Act
PathSegmentResponse result = pathSegment.Adapt<PathSegmentResponse>(_config);
// Assert
result.Should().NotBeNull();
result.Path.Should().Be(pathSegment.Name);
}
[Fact]
public void Register_WhenMappingMultiplePathSegments_ShouldMapAllCorrectly()
{
// Arrange
List<PathSegment> 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<PathSegmentResponse> results = pathSegments.Adapt<List<PathSegmentResponse>>(_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
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="ThumbnailMappingConfig"/> class.
/// </summary>
[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<ImageType>();
byte[] bytes = _faker.Random.Bytes(100);
Thumbnail thumbnail = new(imageType, bytes);
// Act
ThumbnailResponse result = thumbnail.Adapt<ThumbnailResponse>(_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<ThumbnailResponse>(_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<ImageType>();
byte[] emptyBytes = [];
Thumbnail thumbnail = new(imageType, emptyBytes);
// Act
ThumbnailResponse result = thumbnail.Adapt<ThumbnailResponse>(_config);
// Assert
result.Should().NotBeNull();
result.Type.Should().Be(imageType);
result.Bytes.Should().BeEmpty();
}
[Fact]
public void Register_WhenMappingMultipleThumbnails_ShouldMapAllCorrectly()
{
// Arrange
List<Thumbnail> 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<ThumbnailResponse> results = thumbnails.Adapt<List<ThumbnailResponse>>(_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
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="Directory"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DirectoryFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryFixture"/> class.
/// </summary>
public DirectoryFixture()
{
_faker = new Faker();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid <see cref="Directory"/>.
/// </summary>
/// <returns>The created <see cref="Directory"/>.</returns>
public Directory CreateDirectory(
string? path = null,
string? name = null,
Optional<DateTime>? dateCreated = null,
Optional<DateTime>? dateModified = null,
FileSystemItemStatus? status = null,
List<FileSystemItem>? childItems = null)
{
path ??= _faker.System.FilePath();
name ??= _faker.System.FileName();
dateCreated ??= Optional<DateTime>.Some(_faker.Date.Past());
dateModified ??= Optional<DateTime>.Some(_faker.Date.Recent());
status ??= _faker.PickRandom<FileSystemItemStatus>();
ErrorOr<Directory> 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;
}
/// <summary>
/// Creates a list of <see cref="Directory"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<Directory> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => CreateDirectory()).ToList();
}
/// <summary>
/// Creates a list of nested <see cref="Directory"/> objects with a hierarchical structure.
/// </summary>
/// <param name="count">The number of top-level directories to create. Default is 3.</param>
/// <param name="maxDepth">The maximum depth of the directory hierarchy. Default is 3.</param>
/// <param name="maxChildrenPerDirectory">The maximum number of child items (files or directories) per directory. Default is 3.</param>
/// <returns>A list of <see cref="Directory"/> objects with nested structures.</returns>
public List<Directory> CreateManyNested(int count = 3, int maxDepth = 3, int maxChildrenPerDirectory = 3)
{
return Enumerable.Range(0, count).Select(_ => CreateNestedDirectory(1, maxDepth, maxChildrenPerDirectory)).ToList();
}
/// <summary>
/// Recursively creates a nested <see cref="Directory"/> structure.
/// </summary>
/// <param name="currentDepth">The current depth in the directory hierarchy.</param>
/// <param name="maxDepth">The maximum allowed depth for the directory hierarchy.</param>
/// <param name="maxChildrenPerDirectory">The maximum number of child items (files or directories) allowed per directory.</param>
/// <returns>A <see cref="Directory"/> object that may contain nested directories and files.</returns>
private Directory CreateNestedDirectory(int currentDepth, int maxDepth, int maxChildrenPerDirectory)
{
List<FileSystemItem> childItems = [];
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
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="DirectoryResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DirectoryResponseFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker = new();
private readonly FileSystemItemModelFixture _fileSystemItemModelFixture = new();
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid <see cref="DirectoryResponse"/>.
/// </summary>
/// <param name="itemCount">The number of children elements to create.</param>
/// <returns>The created <see cref="DirectoryResponse"/>.</returns>
public DirectoryResponse Create(int itemCount = 3)
{
return new DirectoryResponse(
_faker.System.FilePath(),
_faker.System.FileName(),
_faker.Date.Past(),
_faker.Date.Recent(),
_fileSystemItemModelFixture.CreateMany(itemCount)
);
}
/// <summary>
/// Creates a list of <see cref="DirectoryResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <param name="itemCount">The number of children elemens to create for each element.</param>
/// <returns>The created list.</returns>
public List<DirectoryResponse> CreateMany(int count = 3, int itemCount = 3)
{
return Enumerable.Range(0, count).Select(_ => Create(itemCount)).ToList();
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="FileSystemItemModel"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemItemModelFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker = new();
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid <see cref="FileSystemItemModel"/>.
/// </summary>
/// <returns>The created <see cref="FileSystemItemModel"/>.</returns>
public FileSystemItemModel Create()
{
return new FileSystemItemModel(
_faker.System.FilePath(),
_faker.System.FileName(),
_faker.Date.Past(),
_faker.Date.Recent()
);
}
/// <summary>
/// Creates a list of <see cref="FileSystemItemModel"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<FileSystemItemModel> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="FileSystemTreeNodeResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemTreeNodeResponseFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker = new();
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a single <see cref="FileSystemTreeNodeResponse"/> with a nested structure.
/// </summary>
/// <param name="currentDepth">The current depth in the tree structure. Default is 0 (root level).</param>
/// <param name="maxDepth">The maximum depth of the tree structure. Default is 2.</param>
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
/// <returns>A <see cref="FileSystemTreeNodeResponse"/> with a nested structure.</returns>
public FileSystemTreeNodeResponse Create(int currentDepth = 0, int maxDepth = 2, int maxChildren = 3)
{
FileSystemTreeNodeResponse response = new()
{
Path = _faker.System.FilePath(),
Name = _faker.System.FileName(),
ItemType = FileSystemItemType.Directory,
IsExpanded = _faker.Random.Bool(),
ChildrenLoaded = true,
Children = []
};
if (currentDepth < maxDepth)
{
int childCount = _faker.Random.Int(1, maxChildren);
for (int i = 0; i < childCount; i++)
response.Children.Add(Create(currentDepth + 1, maxDepth, maxChildren));
}
return response;
}
/// <summary>
/// Creates a list of <see cref="FileSystemTreeNodeResponse"/> objects, each with a nested structure.
/// </summary>
/// <param name="count">The number of root-level nodes to create. Default is 2.</param>
/// <param name="maxDepth">The maximum depth of the tree structure for each root node. Default is 2.</param>
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
/// <returns>A list of <see cref="FileSystemTreeNodeResponse"/> objects with nested structures.</returns>
public List<FileSystemTreeNodeResponse> CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3)
{
return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList();
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetDirectoriesQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoriesQueryFixture
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid query to get directories.
/// </summary>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query to get directories.</returns>
public static GetDirectoriesQuery CreateGetDirectoriesQuery(bool includeHiddenElements = false)
{
return new Faker<GetDirectoriesQuery>()
.CustomInstantiator(f => new GetDirectoriesQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.DirectoryPath())
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetDirectoriesQueryHandler"/> class.
/// </summary>
[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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoriesQueryHandlerTests"/> class.
/// </summary>
public GetDirectoriesQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockDirectoryService = Substitute.For<IDirectoryService>();
_mockMapper = Substitute.For<IMapper>();
_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<Directory> directories = _directoryFixture.CreateMany();
IEnumerable<DirectoryResponse> directoryResponses = _directoryResponseFixture.CreateMany(directories.Count());
_mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(directories));
_mockMapper.Map<IEnumerable<DirectoryResponse>>(Arg.Is<IEnumerable<Directory>>(d => d == directories))
.Returns(directoryResponses);
// Act
ErrorOr<IEnumerable<DirectoryResponse>> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<DirectoryResponse>>();
result.Value.Should().BeEquivalentTo(directoryResponses);
_mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements);
_mockMapper.Received(1).Map<IEnumerable<DirectoryResponse>>(Arg.Is<IEnumerable<Directory>>(d => d == directories));
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult()
{
// Arrange
GetDirectoriesQuery getDirectoriesQuery = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(true);
IEnumerable<Directory> directories = _directoryFixture.CreateMany();
IEnumerable<DirectoryResponse> directoryResponses = _directoryResponseFixture.CreateMany(directories.Count());
_mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(directories));
_mockMapper.Map<IEnumerable<DirectoryResponse>>(Arg.Is<IEnumerable<Directory>>(d => d == directories))
.Returns(directoryResponses);
// Act
ErrorOr<IEnumerable<DirectoryResponse>> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<DirectoryResponse>>();
result.Value.Should().BeEquivalentTo(directoryResponses);
_mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements);
_mockMapper.Received(1).Map<IEnumerable<DirectoryResponse>>(Arg.Is<IEnumerable<Directory>>(d => d == directories));
}
[Fact]
public async Task Handle_WhenDirectoryServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDirectoriesQuery query = _fixture.Create<GetDirectoriesQuery>();
Error error = Error.Failure("DirectoryService.Error", "An error occurred");
_mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements)
.Returns(error);
// Act
ErrorOr<IEnumerable<DirectoryResponse>> 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<GetDirectoriesQuery>();
ErrorOr<IEnumerable<Directory>> emptyList = ErrorOrFactory.From(Enumerable.Empty<Directory>());
_mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements)
.Returns(emptyList);
// Act
ErrorOr<IEnumerable<DirectoryResponse>> 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
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetDirectoriesQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoriesQueryValidatorTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly GetDirectoriesQueryValidator _validator;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoriesQueryValidatorTests"/> class.
/// </summary>
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<GetDirectoriesQuery> 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<GetDirectoriesQuery> 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<GetDirectoriesQuery> 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<GetDirectoriesQuery> 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<GetDirectoriesQuery> 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<GetDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetDirectoryTreeQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeQueryFixture
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid query to get directory tree.
/// </summary>
/// <param name="includeFiles">Whether to include file system files or not.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query to get directory tree.</returns>
public static GetDirectoryTreeQuery CreateGetDirectoryTreeQuery(bool includeFiles = false, bool includeHiddenElements = false)
{
return new Faker<GetDirectoryTreeQuery>()
.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
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetDirectoryTreeQueryHandler"/> class.
/// </summary>
[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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeQueryHandlerTests"/> class.
/// </summary>
public GetDirectoryTreeQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockDriveService = Substitute.For<IDriveService>();
_mockDirectoryService = Substitute.For<IDirectoryService>();
_mockFileService = Substitute.For<IFileService>();
_mockPathService = Substitute.For<IPathService>();
_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<FileSystemItem> drives =
[
WindowsRootItem.Create(drivePath, "C:").Value
];
// Ensure the first path segment matches the drive path
PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
List<PathSegment> otherPathSegments = _pathSegmentFixture.CreateMany(2);
IEnumerable<PathSegment> pathSegments = new[] { firstPathSegment }.Concat(otherPathSegments);
IEnumerable<Directory> subdirectories = _directoryFixture.CreateMany(2);
IEnumerable<File> files = _fileFixture.CreateMany(2);
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From(pathSegments));
_mockPathService.CombinePath(Arg.Is<string>(x => true), Arg.Is<string>(y => true)).Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories));
_mockFileService.GetFiles(Arg.Any<string>(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(files));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<string>(), query.IncludeHiddenElements);
_mockFileService.Received(0).GetFiles(Arg.Any<string>(), 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<FileSystemItem> drives =
[
WindowsRootItem.Create(drivePath, "C:").Value
];
// Ensure the first path segment matches the drive path
PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
List<PathSegment> otherPathSegments = _pathSegmentFixture.CreateMany(2);
IEnumerable<PathSegment> pathSegments = new[] { firstPathSegment }.Concat(otherPathSegments);
IEnumerable<Directory> subdirectories = _directoryFixture.CreateMany(2);
IEnumerable<File> files = _fileFixture.CreateMany(2);
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From(pathSegments));
_mockPathService.CombinePath(Arg.Is<string>(x => true), Arg.Is<string>(y => true)).Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories));
_mockFileService.GetFiles(Arg.Any<string>(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(files));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<string>(), query.IncludeHiddenElements);
_mockFileService.Received(1).GetFiles(Arg.Any<string>(), 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<IEnumerable<FileSystemTreeNodeResponse>> 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<FileSystemItem> 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<IEnumerable<FileSystemTreeNodeResponse>> 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<FileSystemItem> drives =
[
WindowsRootItem.Create("C:\\", "C:").Value
];
PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
IEnumerable<PathSegment> 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<string>(), Arg.Any<string>()).Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<string>(), Arg.Any<string>());
}
[Fact]
public async Task Handle_WhenGetSubdirectoriesReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
IEnumerable<FileSystemItem> drives =
[
WindowsRootItem.Create("C:\\", "C:").Value
];
PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
IEnumerable<PathSegment> 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<string>(x => true), Arg.Is<string>(y => true)).Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements).Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<string>(), query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenGetFilesReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(true);
IEnumerable<FileSystemItem> drives =
[
WindowsRootItem.Create("C:\\", "C:").Value
];
PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
IEnumerable<PathSegment> pathSegments = new[] { firstPathSegment }.Concat(_pathSegmentFixture.CreateMany(2));
IEnumerable<Directory> 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<string>(x => true), Arg.Is<string>(y => true)).Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories));
_mockFileService.GetFiles(Arg.Any<string>(), query.IncludeHiddenElements).Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<string>(), query.IncludeHiddenElements);
_mockFileService.Received(1).GetFiles(Arg.Any<string>(), query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenPathOnlyContainsRoot_ShouldReturnOnlyRootNode()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { Path = "C:" };
IEnumerable<FileSystemItem> 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<PathSegment>)[rootSegment]));
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), Arg.Any<bool>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<Directory>()));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<FileSystemItem> drives = [WindowsRootItem.Create("C:\\", "C:").Value];
List<PathSegment> 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<PathSegment>)pathSegments));
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), Arg.Any<bool>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<Directory>()));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<FileSystemItem> drives = [WindowsRootItem.Create("C:\\", "C:").Value];
List<PathSegment> 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<PathSegment>)pathSegments));
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), Arg.Any<bool>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<Directory>()));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<FileSystemItem> 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<PathSegment>)[rootSegment]));
IEnumerable<Directory> visibleDirectories = _directoryFixture.CreateMany(2);
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), false).Returns(ErrorOrFactory.From(visibleDirectories));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<string>(), false);
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetDirectoryTreeQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeQueryValidatorTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly GetDirectoryTreeQueryValidator _validator;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeQueryValidatorTests"/> class.
/// </summary>
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<GetDirectoryTreeQuery> 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<GetDirectoryTreeQuery> 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<GetDirectoryTreeQuery> 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<GetDirectoryTreeQuery> 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<GetDirectoryTreeQuery> 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<GetDirectoryTreeQuery> 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<GetDirectoryTreeQuery> 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<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeFiles);
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetTreeDirectoriesQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesQueryFixture
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid query to get tree directories.
/// </summary>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query to get tree directory.</returns>
public static GetTreeDirectoriesQuery CreateGetTreeDirectoryQuery(bool includeHiddenElements = false)
{
return new Faker<GetTreeDirectoriesQuery>()
.CustomInstantiator(f => new GetTreeDirectoriesQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.DirectoryPath())
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetTreeDirectoriesQueryHandler"/> class.
/// </summary>
[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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesQueryHandlerTests"/> class.
/// </summary>
public GetTreeDirectoriesQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockDirectoryService = Substitute.For<IDirectoryService>();
_mockMapper = Substitute.For<IMapper>();
_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<Directory> directories = _directoryFixture.CreateMany();
IEnumerable<FileSystemTreeNodeResponse> directoryResponses = _fileSystemTreeNodeResponseFixture.CreateMany(directories.Count());
_mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(directories));
_mockMapper.Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<Directory>>(d => d == directories))
.Returns(directoryResponses);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
result.Value.Should().BeEquivalentTo(directoryResponses);
_mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements);
_mockMapper.Received(1).Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<Directory>>(d => d == directories));
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult()
{
// Arrange
GetTreeDirectoriesQuery getDirectoriesQuery = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(true);
IEnumerable<Directory> directories = _directoryFixture.CreateMany();
IEnumerable<FileSystemTreeNodeResponse> directoryResponses = _fileSystemTreeNodeResponseFixture.CreateMany(directories.Count());
_mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(directories));
_mockMapper.Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<Directory>>(d => d == directories))
.Returns(directoryResponses);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
result.Value.Should().BeEquivalentTo(directoryResponses);
_mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements);
_mockMapper.Received(1).Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<Directory>>(d => d == directories));
}
[Fact]
public async Task Handle_WhenDirectoryServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetTreeDirectoriesQuery query = _fixture.Create<GetTreeDirectoriesQuery>();
Error error = Error.Failure("DirectoryService.Error", "An error occurred");
_mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements)
.Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<GetTreeDirectoriesQuery>();
ErrorOr<IEnumerable<Directory>> emptyList = ErrorOrFactory.From(Enumerable.Empty<Directory>());
_mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements)
.Returns(emptyList);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<Directory> nestedDirectories = _directoryFixture.CreateManyNested();
IEnumerable<FileSystemTreeNodeResponse> nestedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(2, 2, 2);
_mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(nestedDirectories));
_mockMapper.Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<Directory>>(d => d == nestedDirectories))
.Returns(nestedResponses);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
result.Value.Should().BeEquivalentTo(nestedResponses, options => options.IncludingNestedObjects());
result.Value.Any(r => r.Children.Count != 0).Should().BeTrue();
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetTreeDirectoriesQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesQueryValidatorTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly GetTreeDirectoriesQueryValidator _validator;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesQueryValidatorTests"/> class.
/// </summary>
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<GetTreeDirectoriesQuery> 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<GetTreeDirectoriesQuery> 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<GetTreeDirectoriesQuery> 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<GetTreeDirectoriesQuery> 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<GetTreeDirectoriesQuery> 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<GetTreeDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetDrivesQueryFixture"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDrivesQueryFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker = new();
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a single <see cref="FileSystemTreeNodeResponse"/> with a nested structure.
/// </summary>
/// <param name="currentDepth">The current depth in the tree structure. Default is 0 (root level).</param>
/// <param name="maxDepth">The maximum depth of the tree structure. Default is 2.</param>
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
/// <returns>A <see cref="FileSystemTreeNodeResponse"/> with a nested structure.</returns>
public FileSystemTreeNodeResponse Create(int currentDepth = 0, int maxDepth = 2, int maxChildren = 3)
{
FileSystemTreeNodeResponse response = new()
{
Path = _faker.System.FilePath(),
Name = _faker.System.FileName(),
ItemType = FileSystemItemType.Directory,
IsExpanded = _faker.Random.Bool(),
ChildrenLoaded = true,
Children = []
};
if (currentDepth < maxDepth)
{
int childCount = _faker.Random.Int(1, maxChildren);
for (int i = 0; i < childCount; i++)
response.Children.Add(Create(currentDepth + 1, maxDepth, maxChildren));
}
return response;
}
/// <summary>
/// Creates a list of <see cref="FileSystemTreeNodeResponse"/> objects, each with a nested structure.
/// </summary>
/// <param name="count">The number of root-level nodes to create. Default is 2.</param>
/// <param name="maxDepth">The maximum depth of the tree structure for each root node. Default is 2.</param>
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
/// <returns>A list of <see cref="FileSystemTreeNodeResponse"/> objects with nested structures.</returns>
public List<FileSystemTreeNodeResponse> CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3)
{
return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList();
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetDrivesQueryHandler"/> class.
/// </summary>
[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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetDrivesQueryHandlerTests"/> class.
/// </summary>
public GetDrivesQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockDriveService = Substitute.For<IDriveService>();
_mockMapper = Substitute.For<IMapper>();
_sut = new GetDrivesQueryHandler(_mockDriveService, _mockMapper);
_getDrivesQueryFixture = new GetDrivesQueryFixture();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public async Task Handle_WhenCalled_ShouldReturnSuccessResult()
{
// Arrange
GetDrivesQuery getDrivesQuery = _fixture.Create<GetDrivesQuery>();
IEnumerable<FileSystemItem> drives =
[
WindowsRootItem.Create("C:\\", "C:").Value,
WindowsRootItem.Create("D:\\", "D:").Value
];
List<FileSystemTreeNodeResponse> driveResponses = _getDrivesQueryFixture.CreateMany();
_mockDriveService.GetDrives()
.Returns(ErrorOrFactory.From(drives));
_mockMapper.Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<FileSystemItem>>(d => d == drives))
.Returns(driveResponses);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(getDrivesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
result.Value.Should().BeEquivalentTo(driveResponses);
_mockDriveService.Received(1).GetDrives();
_mockMapper.Received(1).Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<FileSystemItem>>(d => d == drives));
}
[Fact]
public async Task Handle_WhenDriveServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDrivesQuery query = _fixture.Create<GetDrivesQuery>();
Error error = Error.Failure("DriveService.Error", "An error occurred");
_mockDriveService.GetDrives()
.Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<GetDrivesQuery>();
ErrorOr<IEnumerable<FileSystemItem>> emptyList = ErrorOrFactory.From(Enumerable.Empty<FileSystemItem>());
_mockDriveService.GetDrives()
.Returns(emptyList);
_mockMapper.Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Any<IEnumerable<FileSystemItem>>())
.Returns([]);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEmpty();
_mockDriveService.Received(1).GetDrives();
_mockMapper.Received(1).Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Any<IEnumerable<FileSystemItem>>());
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetFileSystemQueryHandler"/> class.
/// </summary>
[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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetFileSystemQueryHandlerTests"/> class.
/// </summary>
public GetFileSystemQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockPlatformContextManager = Substitute.For<IPlatformContextManager>();
_mockPlatformContext = Substitute.For<IPlatformContext>();
_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<GetFileSystemQuery>();
_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<GetFileSystemQuery>();
_mockPlatformContext.Platform.Returns(PlatformType.Unix);
// Act
ValueTask<FileSystemTypeResponse> 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>();
GetFileSystemQuery query2 = _fixture.Create<GetFileSystemQuery>();
_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<GetFileSystemQuery>();
_mockPlatformContext.Platform.Returns(PlatformType.Unix);
CancellationToken cancellationToken = new(true);
// Act
Func<Task> act = async () => await _sut.Handle(query, cancellationToken);
// Assert
await act.Should().NotThrowAsync();
_mockPlatformContextManager.Received(1).GetCurrentContext();
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="File"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="FileFixture"/> class.
/// </summary>
public FileFixture()
{
_faker = new Faker();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid <see cref="File"/>.
/// </summary>
/// <returns>The created <see cref="File"/>.</returns>
public File CreateFile(
string? path = null,
string? name = null,
Optional<DateTime>? dateCreated = null,
Optional<DateTime>? dateModified = null,
long? size = null,
FileSystemItemStatus? status = null)
{
path ??= _faker.System.FilePath();
name ??= _faker.System.FileName();
dateCreated ??= Optional<DateTime>.Some(_faker.Date.Past());
dateModified ??= Optional<DateTime>.Some(_faker.Date.Recent());
size ??= _faker.Random.Long();
status ??= _faker.PickRandom<FileSystemItemStatus>();
ErrorOr<File> 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;
}
/// <summary>
/// Creates a list of <see cref="File"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<File> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => CreateFile()).ToList();
}
/// <summary>
/// Creates a random valid <see cref="File"/>, without creationg and modification dates.
/// </summary>
/// <returns></returns>
public static File CreateFileWithoutDates()
{
return File.Create(
"/path/to/file_without_dates.txt",
"file_without_dates.txt",
Optional<DateTime>.None(),
Optional<DateTime>.None(),
2048,
FileSystemItemStatus.Accessible
).Value;
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="FileResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileResponseFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker = new();
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid <see cref="FileResponse"/>.
/// </summary>
/// <returns>The created <see cref="FileResponse"/>.</returns>
public FileResponse Create()
{
return new FileResponse(
_faker.System.FilePath(),
_faker.System.FileName(),
_faker.Date.Past(),
_faker.Date.Recent(),
_faker.Random.Long()
);
}
/// <summary>
/// Creates a list of <see cref="FileResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<FileResponse> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetFilesQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFilesQueryFixture
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid query to get files.
/// </summary>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query to get files.</returns>
public static GetFilesQuery CreateGetFilesQuery(bool includeHiddenElements = false)
{
return new Faker<GetFilesQuery>()
.CustomInstantiator(f => new GetFilesQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetFilesQueryHandler"/> class.
/// </summary>
[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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesQueryHandlerTests"/> class.
/// </summary>
public GetFilesQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockFileService = Substitute.For<IFileService>();
_mockMapper = Substitute.For<IMapper>();
_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<File> files = _fileFixture.CreateMany();
IEnumerable<FileResponse> fileResponses = _fileResponseFixture.CreateMany(files.Count());
_mockFileService.GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(files));
_mockMapper.Map<IEnumerable<FileResponse>>(Arg.Is<IEnumerable<File>>(f => f == files))
.Returns(fileResponses);
// Act
ErrorOr<IEnumerable<FileResponse>> result = await _sut.Handle(getFilesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileResponse>>();
result.Value.Should().BeEquivalentTo(fileResponses);
_mockFileService.Received(1).GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements);
_mockMapper.Received(1).Map<IEnumerable<FileResponse>>(Arg.Is<IEnumerable<File>>(f => f == files));
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult()
{
// Arrange
GetFilesQuery getFilesQuery = GetFilesQueryFixture.CreateGetFilesQuery(true);
IEnumerable<File> files = _fileFixture.CreateMany();
IEnumerable<FileResponse> fileResponses = _fileResponseFixture.CreateMany(files.Count());
_mockFileService.GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(files));
_mockMapper.Map<IEnumerable<FileResponse>>(Arg.Is<IEnumerable<File>>(f => f == files))
.Returns(fileResponses);
// Act
ErrorOr<IEnumerable<FileResponse>> result = await _sut.Handle(getFilesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileResponse>>();
result.Value.Should().BeEquivalentTo(fileResponses);
_mockFileService.Received(1).GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements);
_mockMapper.Received(1).Map<IEnumerable<FileResponse>>(Arg.Is<IEnumerable<File>>(f => f == files));
}
[Fact]
public async Task Handle_WhenFileServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetFilesQuery query = _fixture.Create<GetFilesQuery>();
Error error = Error.Failure("FileService.Error", "An error occurred");
_mockFileService.GetFiles(query.Path, query.IncludeHiddenElements)
.Returns(error);
// Act
ErrorOr<IEnumerable<FileResponse>> 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<IEnumerable<FileResponse>>(Arg.Any<IEnumerable<File>>());
}
[Fact]
public async Task Handle_WhenFileServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
GetFilesQuery query = _fixture.Create<GetFilesQuery>();
ErrorOr<IEnumerable<File>> emptyList = ErrorOrFactory.From(Enumerable.Empty<File>());
_mockFileService.GetFiles(query.Path, query.IncludeHiddenElements)
.Returns(emptyList);
_mockMapper.Map<IEnumerable<FileResponse>>(Arg.Is<IEnumerable<File>>(f => !f.Any()))
.Returns([]);
// Act
ErrorOr<IEnumerable<FileResponse>> 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<IEnumerable<FileResponse>>(Arg.Is<IEnumerable<File>>(f => !f.Any()));
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetFilesQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFilesQueryValidatorTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly GetFilesQueryValidator _validator;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesQueryValidatorTests"/> class.
/// </summary>
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<GetFilesQuery> 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<GetFilesQuery> 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<GetFilesQuery> 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<GetFilesQuery> 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<GetFilesQuery> 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<GetFilesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetTreeFilesQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeFilesQueryFixture
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid query to get files.
/// </summary>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query to get files.</returns>
public static GetTreeFilesQuery CreateGetFilesQuery(bool includeHiddenElements = false)
{
return new Faker<GetTreeFilesQuery>()
.CustomInstantiator(f => new GetTreeFilesQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetTreeFilesQueryHandler"/> class.
/// </summary>
[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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeFilesQueryHandler"/> class.
/// </summary>
public GetTreeFilesQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockFileService = Substitute.For<IFileService>();
_mockMapper = Substitute.For<IMapper>();
_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<File> files = _fileFixture.CreateMany();
IEnumerable<FileSystemTreeNodeResponse> fileResponses = _fileSystemTreeNodeResponseFixture.CreateMany(files.Count());
_mockFileService.GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(files));
_mockMapper.Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<File>>(f => f == files))
.Returns(fileResponses);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(getFilesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
result.Value.Should().BeEquivalentTo(fileResponses);
_mockFileService.Received(1).GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements);
_mockMapper.Received(1).Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<File>>(f => f == files));
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult()
{
// Arrange
GetTreeFilesQuery getFilesQuery = GetTreeFilesQueryFixture.CreateGetFilesQuery(true);
IEnumerable<File> files = _fileFixture.CreateMany();
IEnumerable<FileSystemTreeNodeResponse> fileResponses = _fileSystemTreeNodeResponseFixture.CreateMany(files.Count());
_mockFileService.GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(files));
_mockMapper.Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<File>>(f => f == files))
.Returns(fileResponses);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(getFilesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
result.Value.Should().BeEquivalentTo(fileResponses);
_mockFileService.Received(1).GetFiles(getFilesQuery.Path, getFilesQuery.IncludeHiddenElements);
_mockMapper.Received(1).Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<File>>(f => f == files));
}
[Fact]
public async Task Handle_WhenFileServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetTreeFilesQuery query = _fixture.Create<GetTreeFilesQuery>();
Error error = Error.Failure("FileService.Error", "An error occurred");
_mockFileService.GetFiles(query.Path, query.IncludeHiddenElements)
.Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<GetTreeFilesQuery>();
ErrorOr<IEnumerable<File>> emptyList = ErrorOrFactory.From(Enumerable.Empty<File>());
_mockFileService.GetFiles(query.Path, query.IncludeHiddenElements)
.Returns(emptyList);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetTreeFilesQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeFilesQueryValidatorTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly GetTreeFilesQueryValidator _validator;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeFilesQueryValidatorTests"/> class.
/// </summary>
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<GetTreeFilesQuery> 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<GetTreeFilesQuery> 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<GetTreeFilesQuery> 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<GetTreeFilesQuery> 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<GetTreeFilesQuery> 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<GetTreeFilesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="CombinePathCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CombinePathCommandHandlerTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IFixture _fixture;
private readonly IPathService _mockPathService;
private readonly CombinePathCommandHandler _sut;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="CombinePathCommandHandlerTests"/> class.
/// </summary>
public CombinePathCommandHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockPathService = Substitute.For<IPathService>();
_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<PathSegmentResponse> result = await _sut.Handle(combinePathCommand, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeOfType<PathSegmentResponse>();
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<CombinePathCommand>();
Error error = Error.Failure("PathService.Error", "An error occurred");
_mockPathService.CombinePath(command.OriginalPath, command.NewPath)
.Returns(error);
// Act
ErrorOr<PathSegmentResponse> 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<CombinePathCommand>();
_mockPathService.CombinePath(command.OriginalPath, command.NewPath)
.Returns(ErrorOrFactory.From(string.Empty));
// Act
ErrorOr<PathSegmentResponse> result = await _sut.Handle(command, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeOfType<PathSegmentResponse>();
result.Value.Path.Should().BeEmpty();
_mockPathService.Received(1).CombinePath(command.OriginalPath, command.NewPath);
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="CombinePathCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CombinePathCommandValidatorTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly CombinePathCommandValidator _validator;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="CombinePathCommandValidatorTests"/> class.
/// </summary>
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<CombinePathCommand> 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<CombinePathCommand> 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<CombinePathCommand> 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<CombinePathCommand> 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<CombinePathCommand> 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<CombinePathCommand> 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<CombinePathCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.OriginalPath);
result.ShouldNotHaveValidationErrorFor(x => x.NewPath);
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="CombinePathCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CombinePathCommandFixture
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid command to combine paths.
/// </summary>
/// <returns>The created command.</returns>
public static CombinePathCommand CreateCombinePathCommand()
{
return new Faker<CombinePathCommand>()
.CustomInstantiator(f => new CombinePathCommand(
default!,
default!
))
.RuleFor(x => x.OriginalPath, f => f.System.FilePath())
.RuleFor(x => x.NewPath, f => f.System.FilePath());
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="SplitPathCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SplitPathCommandFixture
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid command for splitting paths.
/// </summary>
/// <returns>The created command.</returns>
public static SplitPathCommand CreateSplitPathCommand()
{
return new Faker<SplitPathCommand>()
.CustomInstantiator(f => new SplitPathCommand(
default!
))
.RuleFor(x => x.Path, f => f.System.FilePath());
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="SplitPathCommandHandler"/> class.
/// </summary>
[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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathCommandHandlerTests"/> class.
/// </summary>
public SplitPathCommandHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockPathService = Substitute.For<IPathService>();
_mockMapper = Substitute.For<IMapper>();
_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<PathSegment> pathSegments = _pathSegmentFixture.CreateMany();
IEnumerable<PathSegmentResponse> pathSegmentResponses = _pathSegmentResponseFixture.CreateMany(pathSegments.Count());
_mockPathService.ParsePath(splitPathCommand.Path)
.Returns(ErrorOrFactory.From(pathSegments));
_mockMapper.Map<IEnumerable<PathSegmentResponse>>(Arg.Any<IEnumerable<PathSegment>>())
.Returns(pathSegmentResponses);
// Act
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _sut.Handle(splitPathCommand, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<PathSegmentResponse>>();
result.Value.Should().BeEquivalentTo(pathSegmentResponses);
_mockPathService.Received(1).ParsePath(splitPathCommand.Path);
_mockMapper.Received(1).Map<IEnumerable<PathSegmentResponse>>(Arg.Any<IEnumerable<PathSegment>>());
}
[Fact]
public async Task Handle_WhenPathServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
SplitPathCommand command = _fixture.Create<SplitPathCommand>();
Error error = Error.Failure("PathService.Error", "An error occurred");
_mockPathService.ParsePath(command.Path)
.Returns(error);
// Act
ErrorOr<IEnumerable<PathSegmentResponse>> 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<IEnumerable<PathSegmentResponse>>(Arg.Any<ErrorOr<IEnumerable<PathSegment>>>());
}
[Fact]
public async Task Handle_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
SplitPathCommand command = _fixture.Create<SplitPathCommand>();
ErrorOr<IEnumerable<PathSegment>> emptyList = ErrorOrFactory.From(Enumerable.Empty<PathSegment>());
_mockPathService.ParsePath(command.Path)
.Returns(emptyList);
_mockMapper.Map<IEnumerable<PathSegmentResponse>>(Arg.Any<IEnumerable<PathSegment>>())
.Returns([]);
// Act
ErrorOr<IEnumerable<PathSegmentResponse>> 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<IEnumerable<PathSegmentResponse>>(Arg.Any<IEnumerable<PathSegment>>());
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="SplitPathCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SplitPathCommandValidatorTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly SplitPathCommandValidator _validator;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathCommandValidatorTests"/> class.
/// </summary>
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<SplitPathCommand> 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<SplitPathCommand> 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<SplitPathCommand> 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<SplitPathCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PathSegment"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PathSegmentFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="PathSegmentFixture"/> class.
/// </summary>
public PathSegmentFixture()
{
_faker = new Faker();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid <see cref="PathSegment"/>.
/// </summary>
/// <returns>The created <see cref="PathSegment"/>.</returns>
public PathSegment CreatePathSegment(
string? name = null,
bool? isDirectory = null,
bool? isDrive = null)
{
name ??= _faker.System.FileName();
isDirectory ??= true;
isDrive ??= false;
ErrorOr<PathSegment> 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;
}
/// <summary>
/// Creates a list of <see cref="PathSegment"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<PathSegment> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => CreatePathSegment()).ToList();
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PathSegmentResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PathSegmentResponseFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker = new();
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid <see cref="PathSegmentResponse"/>.
/// </summary>
/// <returns>The created <see cref="PathSegmentResponse"/>.</returns>
public PathSegmentResponse Create()
{
return new PathSegmentResponse(_faker.System.DirectoryPath());
}
/// <summary>
/// Creates a list of <see cref="PathSegmentResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<PathSegmentResponse> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PathSeparatorResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PathSeparatorResponseFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker = new();
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid <see cref="PathSeparatorResponse"/>.
/// </summary>
/// <returns>The created <see cref="PathSeparatorResponse"/>.</returns>
public PathSeparatorResponse Create()
{
return new PathSeparatorResponse(_faker.System.DirectoryPath());
}
/// <summary>
/// Creates a list of <see cref="PathSeparatorResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<PathSeparatorResponse> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="CheckPathExistsQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckPathExistsQueryHandlerTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IPathService _mockPathService;
private readonly CheckPathExistsQueryHandler _sut;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="CheckPathExistsQueryHandlerTests"/> class.
/// </summary>
public CheckPathExistsQueryHandlerTests()
{
_mockPathService = Substitute.For<IPathService>();
_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<string>()).Returns(false);
// Act
PathExistsResponse result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.Exists.Should().BeFalse();
_mockPathService.Received(1).Exists(Arg.Any<string>());
}
[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
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="CheckPathExistsQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckPathExistsQueryValidatorTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly CheckPathExistsQueryValidator _validator;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="CheckPathExistsQueryValidatorTests"/> class.
/// </summary>
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<CheckPathExistsQuery> 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<CheckPathExistsQuery> 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<CheckPathExistsQuery> 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<CheckPathExistsQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="CheckPathExistsQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckPathExistsQueryFixture
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid query to check if paths exist.
/// </summary>
/// <returns>The created query.</returns>
public static CheckPathExistsQuery CreateCheckPathExistsQuery()
{
return new Faker<CheckPathExistsQuery>()
.CustomInstantiator(f => new CheckPathExistsQuery(
default!
))
.RuleFor(x => x.Path, f => f.System.FilePath());
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetPathParentQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathParentQueryFixture
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid query to check if paths exist.
/// </summary>
/// <returns>The created query.</returns>
public static GetPathParentQuery CreateGetPathParentQuery()
{
return new Faker<GetPathParentQuery>()
.CustomInstantiator(f => new GetPathParentQuery(
default!
))
.RuleFor(x => x.Path, f => f.System.FilePath());
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetPathParentQueryHandler"/> class.
/// </summary>
[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<IPathService>();
_mockMapper = Substitute.For<IMapper>();
_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<PathSegment> pathSegments = _pathSegmentFixture.CreateMany();
IEnumerable<PathSegmentResponse> pathSegmentResponses = _pathSegmentResponseFixture.CreateMany(pathSegments.Count());
_mockPathService.GoUpOneLevel(query.Path)
.Returns(ErrorOrFactory.From(pathSegments));
_mockMapper.Map<IEnumerable<PathSegmentResponse>>(Arg.Is<IEnumerable<PathSegment>>(p => p == pathSegments))
.Returns(pathSegmentResponses);
// Act
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<PathSegmentResponse>>();
result.Value.Should().BeEquivalentTo(pathSegmentResponses);
_mockPathService.Received(1).GoUpOneLevel(query.Path);
_mockMapper.Received(1).Map<IEnumerable<PathSegmentResponse>>(Arg.Is<IEnumerable<PathSegment>>(p => p == pathSegments));
}
[Fact]
public async Task Handle_WhenPathServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetPathParentQuery query = _fixture.Create<GetPathParentQuery>();
Error error = Error.Failure("PathService.Error", "An error occurred");
_mockPathService.GoUpOneLevel(query.Path)
.Returns(error);
// Act
ErrorOr<IEnumerable<PathSegmentResponse>> 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<IEnumerable<PathSegmentResponse>>(Arg.Any<IEnumerable<PathSegment>>());
}
[Fact]
public async Task Handle_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
GetPathParentQuery query = _fixture.Create<GetPathParentQuery>();
ErrorOr<IEnumerable<PathSegment>> emptyList = ErrorOrFactory.From(Enumerable.Empty<PathSegment>());
_mockPathService.GoUpOneLevel(query.Path)
.Returns(emptyList);
_mockMapper.Map<IEnumerable<PathSegmentResponse>>(Arg.Is<IEnumerable<PathSegment>>(p => !p.Any()))
.Returns([]);
// Act
ErrorOr<IEnumerable<PathSegmentResponse>> 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<IEnumerable<PathSegmentResponse>>(Arg.Is<IEnumerable<PathSegment>>(p => !p.Any()));
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetPathParentQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathParentQueryValidatorTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly GetPathParentQueryValidator _validator;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetPathParentQueryValidatorTests"/> class.
/// </summary>
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<GetPathParentQuery> 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<GetPathParentQuery> 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<GetPathParentQuery> 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<GetPathParentQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetPathRootQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathRootQueryFixture
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid query to check if paths exist.
/// </summary>
/// <returns>The created query.</returns>
public static GetPathRootQuery CreateGetPathRootQuery()
{
return new Faker<GetPathRootQuery>()
.CustomInstantiator(f => new GetPathRootQuery(
default!
))
.RuleFor(x => x.Path, f => f.System.FilePath());
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetPathRootQueryHandler"/> class.
/// </summary>
[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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetPathRootQueryHandlerTests"/> class.
/// </summary>
public GetPathRootQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockPathService = Substitute.For<IPathService>();
_mockMapper = Substitute.For<IMapper>();
_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<PathSegmentResponse>(Arg.Is<PathSegment>(p => p == pathSegment))
.Returns(pathSegmentResponse);
// Act
ErrorOr<PathSegmentResponse> 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<PathSegmentResponse>(Arg.Is<PathSegment>(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<PathSegmentResponse> 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<PathSegmentResponse>(Arg.Any<PathSegment>());
}
[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<PathSegmentResponse>(Arg.Is<PathSegment>(p => p == rootPathSegment))
.Returns(rootResponse);
// Act
ErrorOr<PathSegmentResponse> 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<PathSegmentResponse>(Arg.Is<PathSegment>(p => p == rootPathSegment));
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetPathRootQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathRootQueryValidatorTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly GetPathRootQueryValidator _validator;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetPathRootQueryValidatorTests"/> class.
/// </summary>
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<GetPathRootQuery> 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<GetPathRootQuery> 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<GetPathRootQuery> 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<GetPathRootQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetPathSeparatorQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathSeparatorQueryHandlerTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IPathService _mockPathService;
private readonly GetPathSeparatorQueryHandler _sut;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="GetPathSeparatorQueryHandlerTests"/> class.
/// </summary>
public GetPathSeparatorQueryHandlerTests()
{
_mockPathService = Substitute.For<IPathService>();
_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<Task> act = async () => await _sut.Handle(query, cts.Token);
// Assert
await act.Should().NotThrowAsync();
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="ValidatePathQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidatePathQueryFixure
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid query to check if paths exist.
/// </summary>
/// <returns>The created query.</returns>
public static ValidatePathQuery CreateValidatePathQuery()
{
return new Faker<ValidatePathQuery>()
.CustomInstantiator(f => new ValidatePathQuery(
default!
))
.RuleFor(x => x.Path, f => f.System.FilePath());
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="ValidatePathQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidatePathQueryHandlerTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IPathService _mockPathService;
private readonly ValidatePathQueryHandler _sut;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="ValidatePathQueryHandlerTests"/> class.
/// </summary>
public ValidatePathQueryHandlerTests()
{
_mockPathService = Substitute.For<IPathService>();
_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<string>()).Returns(false);
// Act
PathValidResponse result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsValid.Should().BeFalse();
_mockPathService.Received(1).IsValidPath(Arg.Any<string>());
}
[Fact]
public async Task Handle_WhenCalledWithEmptyPath_ShouldReturnFalseResponse()
{
// Arrange
ValidatePathQuery query = new(string.Empty);
_mockPathService.IsValidPath(Arg.Any<string>()).Returns(false);
// Act
PathValidResponse result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsValid.Should().BeFalse();
_mockPathService.Received(1).IsValidPath(Arg.Any<string>());
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="ValidatePathQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidatePathQueryValidatorTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly ValidatePathQueryValidator _validator;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="ValidatePathQueryValidatorTests"/> class.
/// </summary>
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<ValidatePathQuery> 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<ValidatePathQuery> 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<ValidatePathQuery> 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<ValidatePathQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="ThumbnailResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThumbnailResponseFixture
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid query to get a thumbnail.
/// </summary>
/// <returns>The created query.</returns>
public static ThumbnailResponse CreateThumbnailResponse()
{
return new Faker<ThumbnailResponse>()
.CustomInstantiator(f => new ThumbnailResponse(
default,
default!
))
.RuleFor(x => x.Type, f => f.PickRandom<ImageType>())
.RuleFor(x => x.Bytes, f => f.Random.Bytes(20));
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetThumbnailQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThumbnailQueryFixture
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid query to get a thumbnail.
/// </summary>
/// <returns>The created query.</returns>
public static GetThumbnailQuery CreateGetThumbnailQuery()
{
return new Faker<GetThumbnailQuery>()
.CustomInstantiator(f => new GetThumbnailQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.Quality, f => f.Random.Int());
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetThumbnailQueryHandler"/> class.
/// </summary>
[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<IThumbnailService>();
_mockMapper = Substitute.For<IMapper>();
_sut = new GetThumbnailQueryHandler(_mockThumbnailService, _mockMapper);
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public async Task Handle_WhenCalledWithValidQuery_ShouldReturnSuccessResult()
{
// Arrange
GetThumbnailQuery query = _fixture.Create<GetThumbnailQuery>();
Thumbnail thumbnail = _fixture.Create<Thumbnail>();
ThumbnailResponse thumbnailResponse = ThumbnailResponseFixture.CreateThumbnailResponse();
_mockThumbnailService.GetThumbnailAsync(query.Path, query.Quality, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(thumbnail));
_mockMapper.Map<ThumbnailResponse>(Arg.Is<Thumbnail>(t => t == thumbnail))
.Returns(thumbnailResponse);
// Act
ErrorOr<ThumbnailResponse> 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<CancellationToken>());
_mockMapper.Received(1).Map<ThumbnailResponse>(Arg.Is<Thumbnail>(t => t == thumbnail));
}
[Fact]
public async Task Handle_WhenThumbnailServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetThumbnailQuery query = _fixture.Create<GetThumbnailQuery>();
Error error = Error.Failure("ThumbnailService.Error", "An error occurred");
_mockThumbnailService.GetThumbnailAsync(query.Path, query.Quality, Arg.Any<CancellationToken>())
.Returns(error);
// Act
ErrorOr<ThumbnailResponse> 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<CancellationToken>());
_mockMapper.DidNotReceive().Map<ThumbnailResponse>(Arg.Any<Thumbnail>());
}
[Fact]
public async Task Handle_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetThumbnailQuery query = _fixture.Create<GetThumbnailQuery>();
CancellationTokenSource cts = new();
cts.Cancel();
_mockThumbnailService.GetThumbnailAsync(query.Path, query.Quality, cts.Token)
.Returns(Task.FromCanceled<ErrorOr<Thumbnail>>(cts.Token));
// Act & Assert
await Assert.ThrowsAsync<TaskCanceledException>(() => _sut.Handle(query, cts.Token).AsTask());
await _mockThumbnailService.Received(1).GetThumbnailAsync(query.Path, query.Quality, cts.Token);
_mockMapper.DidNotReceive().Map<ThumbnailResponse>(Arg.Any<Thumbnail>());
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="UnitOfWork"/> class.
/// Contains unit tests for the <see cref="AddBookCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddBookCommandValidatorTests
@@ -1894,4 +1894,4 @@ public class AddBookCommandValidatorTests
result.ShouldNotHaveValidationErrorFor(x => x.Ratings[0].VoteCount);
}
#endregion
}
}