From 532322eab2678137da439b1f6e604426ccbb64fc Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 2 Jan 2025 14:56:45 +0200 Subject: [PATCH] Removes unused file system API endpoints --- .../file-system-management/Api.Directories.md | 120 ----- .../directories/GetDirectoryTree.http | 2 - .../directories/GetTreeDirectories.http | 2 - .../GetDirectoryTreeRequestMapping.cs | 22 - .../GetTreeDirectoriesRequestMapping.cs | 22 - .../Files/GetTreeFilesRequestMapping.cs | 1 - .../GetDirectoryTree/GetDirectoryTreeQuery.cs | 22 - .../GetDirectoryTreeQueryHandler.cs | 180 -------- .../GetDirectoryTreeQueryValidator.cs | 20 - .../GetTreeDirectoriesQuery.cs | 20 - .../GetTreeDirectoriesQueryHandler.cs | 44 -- .../GetTreeDirectoriesQueryValidator.cs | 20 - .../Directories/GetDirectoryTreeRequest.cs | 19 - .../Directories/GetTreeDirectoriesRequest.cs | 17 - .../ApiRoutes.Directories.cs | 2 - .../GetDirectoryTreeEndpoint.cs | 56 --- .../GetDirectoryTreeEndpointSummary.cs | 189 -------- .../GetTreeDirectoriesEndpoint.cs | 55 --- .../GetTreeDirectoriesEndpointSummary.cs | 107 ----- .../DirectoriesController.cs | 30 -- src/Lumina.sln | 2 - .../GetDirectoryTreeEndpointTests.cs | 430 ------------------ .../GetTreeDirectoriesEndpointTests.cs | 266 ----------- .../GetDirectoryTreeEndpointTests.cs | 52 --- .../GetTreeDirectoriesEndpointTests.cs | 52 --- .../GetDirectoryTreeRequestMappingTests.cs | 44 -- .../GetTreeDirectoriesRequestMappingTests.cs | 43 -- .../Fixtures/GetDirectoryTreeQueryFixture.cs | 33 -- .../GetDirectoryTreeQueryHandlerTests.cs | 383 ---------------- .../GetDirectoryTreeQueryValidatorTests.cs | 141 ------ .../GetTreeDirectoriesQueryFixture.cs | 30 -- .../GetTreeDirectoriesQueryHandlerTests.cs | 232 ---------- .../GetTreeDirectoriesQueryValidatorTests.cs | 113 ----- .../GetDirectoryTreeEndpointTests.cs | 170 ------- .../GetTreeDirectoriesEndpointTests.cs | 170 ------- 35 files changed, 3111 deletions(-) delete mode 100644 docs/technical/requests/file-system-management/directories/GetDirectoryTree.http delete mode 100644 docs/technical/requests/file-system-management/directories/GetTreeDirectories.http delete mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMapping.cs delete mode 100644 src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMapping.cs delete mode 100644 src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQuery.cs delete mode 100644 src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs delete mode 100644 src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidator.cs delete mode 100644 src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQuery.cs delete mode 100644 src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs delete mode 100644 src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidator.cs delete mode 100644 src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoryTreeRequest.cs delete mode 100644 src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetTreeDirectoriesRequest.cs delete mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpoint.cs delete mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpointSummary.cs delete mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpoint.cs delete mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpointSummary.cs delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs delete mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs delete mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMappingTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMappingTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/Fixtures/GetDirectoryTreeQueryFixture.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandlerTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidatorTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/Fixtures/GetTreeDirectoriesQueryFixture.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidatorTests.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs delete mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs diff --git a/docs/technical/api/file-system-management/Api.Directories.md b/docs/technical/api/file-system-management/Api.Directories.md index d457f758..a6bfd480 100644 --- a/docs/technical/api/file-system-management/Api.Directories.md +++ b/docs/technical/api/file-system-management/Api.Directories.md @@ -6,12 +6,6 @@ - [Get Directories](#get-directories) - [Get Directories Request](#get-directories-request) - [Get Directories Response](#get-directories-response) - - [Get Directory Tree](#get-directory-tree) - - [Get Directory Tree Request](#get-directory-tree-request) - - [Get Directory Tree Response](#get-directory-tree-response) - - [Get Tree Directories](#get-tree-directories) - - [Get Tree Directories Request](#get-tree-directories-request) - - [Get Tree Directories Response](#get-tree-directories-response) ## File System Management @@ -49,117 +43,3 @@ GET api/v1/directories/get-directories?path=C%3A%5CUsers%5C&includeHiddenElement } ] ``` - -#### Get Directory Tree - -##### Get Directory Tree Request - -```js -GET api/v1/directories/get-directory-tree?path=C%3A%5CUsers%5C&includeFiles=true&includeHiddenElements=true -``` - -##### Get Directory Tree Response - -```js -200 Ok -``` - -```json -[ - { - "Path": "/", - "Name": "The Lord of the Rings - The Fellowship of the Ring (2001)", - "ItemType": "Root", - "IsExpanded": true, - "ChildrenLoaded": true, - "Children": [ - { - "Path": "/media/", - "Name": "media", - "ItemType": "Directory", - "IsExpanded": true, - "ChildrenLoaded": true, - "Children": [ - { - "Path": "/media/movies/", - "Name": "movies", - "ItemType": "Directory", - "IsExpanded": true, - "ChildrenLoaded": true, - "Children": [ - { - "Path": "/media/movies/The Lord of the Rings - The Fellowship of the Ring (2001)/", - "Name": "The Lord of the Rings - The Fellowship of the Ring (2001)", - "ItemType": "Directory", - "IsExpanded": true, - "ChildrenLoaded": true, - "Children": [ - { - "Path": "/media/movies/The Lord of the Rings - The Fellowship of the Ring (2001)/Extras/", - "Name": "Extras", - "ItemType": "Directory", - "IsExpanded": false, - "ChildrenLoaded": false, - "Children": [] - }, - { - "Path": "/media/movies/The Matrix (1999)/The Matrix.mkv", - "Name": "The Matrix.mkv", - "ItemType": "File", - "IsExpanded": false, - "ChildrenLoaded": false, - "Children": [] - }, - { - "Path": "/media/movies/The Matrix (1999)/The Matrix.en.srt", - "Name": "The Matrix.en.srt", - "ItemType": "File", - "IsExpanded": false, - "ChildrenLoaded": false, - "Children": [] - } - ] - } - ] - } - ] - } - ] - } -] -``` - -#### Get Tree Directories - -##### Get Tree Directories Request - -```js -GET api/v1/directories/get-tree-directories?path=C%3A%5CUsers%5C&includeHiddenElements=true -``` - -##### Get Tree Directories Response - -```js -200 Ok -``` - -```json -[ - { - "Path": "/media/movies/The Matrix (1999)/", - "Name": "The Matrix (1999)", - "ItemType": "Directory", - "IsExpanded": false, - "ChildrenLoaded": false, - "Children": [] - }, - { - "Path": "/media/movies/The Lord of the Rings - The Fellowship of the Ring (2001)/", - "Name": "The Lord of the Rings - The Fellowship of the Ring (2001)", - "ItemType": "Directory", - "IsExpanded": false, - "ChildrenLoaded": false, - "Children": [] - } -] -``` diff --git a/docs/technical/requests/file-system-management/directories/GetDirectoryTree.http b/docs/technical/requests/file-system-management/directories/GetDirectoryTree.http deleted file mode 100644 index b7b7403e..00000000 --- a/docs/technical/requests/file-system-management/directories/GetDirectoryTree.http +++ /dev/null @@ -1,2 +0,0 @@ -GET {{host}}/api/v1/directories/get-directory-tree?path=C%3A%5CUsers%5C&includeFiles=true&includeHiddenElements=true -Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/file-system-management/directories/GetTreeDirectories.http b/docs/technical/requests/file-system-management/directories/GetTreeDirectories.http deleted file mode 100644 index 1ef389c8..00000000 --- a/docs/technical/requests/file-system-management/directories/GetTreeDirectories.http +++ /dev/null @@ -1,2 +0,0 @@ -GET {{host}}/api/v1/directories/get-tree-directories?path=C%3A%5CUsers%5C&includeHiddenElements=true -Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMapping.cs deleted file mode 100644 index 8326966b..00000000 --- a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMapping.cs +++ /dev/null @@ -1,22 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; -using Lumina.Contracts.Requests.FileSystemManagement.Directories; -#endregion - -namespace Lumina.Application.Common.Mapping.FileSystemManagement.Directories; - -/// -/// Extension methods for converting . -/// -public static class GetDirectoryTreeRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The converted query. - public static GetDirectoryTreeQuery ToQuery(this GetDirectoryTreeRequest request) - { - return new GetDirectoryTreeQuery(request.Path, request.IncludeFiles, request.IncludeHiddenElements); - } -} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMapping.cs deleted file mode 100644 index ba826c6a..00000000 --- a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMapping.cs +++ /dev/null @@ -1,22 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; -using Lumina.Contracts.Requests.FileSystemManagement.Directories; -#endregion - -namespace Lumina.Application.Common.Mapping.FileSystemManagement.Directories; - -/// -/// Extension methods for converting . -/// -public static class GetTreeDirectoriesRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The converted query. - public static GetTreeDirectoriesQuery ToQuery(this GetTreeDirectoriesRequest request) - { - return new GetTreeDirectoriesQuery(request.Path, request.IncludeHiddenElements); - } -} diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMapping.cs index 1ab64057..0581cee4 100644 --- a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMapping.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles; using Lumina.Contracts.Requests.FileSystemManagement.Files; #endregion diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQuery.cs deleted file mode 100644 index 2692a771..00000000 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQuery.cs +++ /dev/null @@ -1,22 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Mediator; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; - -/// -/// Query for retrieving the tree of directories of a path. -/// -/// The path for which to retrieve the tree of directories. -/// Whether to include files in the directory tree or not. -/// Whether to include hidden files and directories or not. -[DebuggerDisplay("Path: {Path}")] -public record GetDirectoryTreeQuery( - string? Path, - bool IncludeFiles, - bool IncludeHiddenElements -) : IRequest>>; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs deleted file mode 100644 index 76052b5d..00000000 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandler.cs +++ /dev/null @@ -1,180 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Domain.Common.Enums.FileSystem; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Mediator; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; - -/// -/// Handler for the query to get a directory tree. -/// -public class GetDirectoryTreeQueryHandler : IRequestHandler>> -{ - private readonly IDirectoryService _directoryService; - private readonly IFileService _fileService; - private readonly IPathService _pathService; - private readonly IDriveService _driveService; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for handling file system drives. - /// Injected service for handling directories. - /// Injected service for handling files. - /// Injected service for handling file system paths. - public GetDirectoryTreeQueryHandler(IDriveService driveService, IDirectoryService directoryService, IFileService fileService, IPathService pathService) - { - _directoryService = directoryService; - _fileService = fileService; - _pathService = pathService; - _driveService = driveService; - } - - /// - /// Gets the tree of expanded directories leading up to the requested path, with the additional list of drives, and children of the last child directory. - /// - /// - /// An containing either a collection of , or an error message. - /// - public async ValueTask>> Handle(GetDirectoryTreeQuery request, CancellationToken cancellationToken) - { - List result = []; - // retrieve the list of drives - ErrorOr> getDrivesResult = GetDrives(); - if (getDrivesResult.IsError) - return getDrivesResult.Errors; - result.AddRange(getDrivesResult.Value); - - ErrorOr> pathPartsResults = _pathService.ParsePath(request.Path!); - if (pathPartsResults.IsError) - return pathPartsResults.Errors; - - List pathParts = pathPartsResults.Value.ToList(); - - ErrorOr> buildDirectoryTreeResult = BuildDirectoryTree(result, pathParts, out FileSystemTreeNodeResponse? currentNode, request.IncludeHiddenElements); - if (buildDirectoryTreeResult.IsError) - return buildDirectoryTreeResult.Errors; - - // add subdirectories of the last directory node - ErrorOr loadChildrenResult = LoadChildren(currentNode, request.IncludeFiles, request.IncludeHiddenElements); - if (loadChildrenResult.IsError) - return loadChildrenResult.Errors; - return await ValueTask.FromResult(result); - } - - /// - /// Gets the root drives (on Windows), or an empty list on Unix-based systems. - /// - /// - /// An containing a list of , or an error message. - /// - private ErrorOr> GetDrives() - { - ErrorOr> getDrivesResult = _driveService.GetDrives(); - if (getDrivesResult.IsError) - return getDrivesResult.Errors; - return ErrorOrFactory.From(getDrivesResult.Value.ToTreeNodeResponses()); - } - - /// - /// Builds the tree of directories based on the parsed path parts. - /// - /// The list of available drives. - /// The list of parsed path segments (directories). - /// Whether to include hidden file system elements or not. - /// - /// An containing a list of representing the directory tree, or an error message. - /// - private ErrorOr> BuildDirectoryTree(List drives, List pathParts, out FileSystemTreeNodeResponse currentNode, bool includeHiddenElements = true) - { - // find the root drive that matches the first part of the path - FileSystemTreeNodeResponse drive = drives.First(drive => drive.Name.Contains(pathParts[0].Name)); - drive.IsExpanded = true; - currentNode = drive; - string currentPath = pathParts[0].Name; - - // traverse the remaining path parts to build the tree structure - for (int i = 1; i < pathParts.Count; i++) - { - ErrorOr combinedPathResult = _pathService.CombinePath(currentPath, pathParts[i].Name); - if (combinedPathResult.IsError) - return combinedPathResult.Errors; - if (_pathService.Exists(combinedPathResult.Value, includeHiddenElements)) - { - - currentPath = combinedPathResult.Value; - // create a new node for the directory and add it as a child of the current node - FileSystemTreeNodeResponse newNode = new() - { - Path = currentPath, - Name = pathParts[i].Name, - ItemType = FileSystemItemType.Directory, - IsExpanded = true - }; - currentNode.Children.Add(newNode); - currentNode = newNode; // move to the new node - } - } - return new List { drive }; - } - - /// - /// Loads the child directories and files of the specified directory node. - /// - /// The directory node to load children for. - /// Whether to include files in the directories or not. - /// A result indicating a successful operation, or an error message. - private ErrorOr LoadChildren(FileSystemTreeNodeResponse node, bool includeFiles, bool includeHiddenElements) - { - // get subdirectories under the current node's path - ErrorOr> getSubDirectoriesResult = _directoryService.GetSubdirectories(node.Path, includeHiddenElements); - if (getSubDirectoriesResult.IsError) - return getSubDirectoriesResult.Errors; - // add each subdirectory as a child node of the current directory - foreach (Directory subDirectory in getSubDirectoriesResult.Value ?? []) - { - FileSystemTreeNodeResponse subDirNode = new() - { - Name = subDirectory.Name, - Path = subDirectory.Id.Path, - ItemType = FileSystemItemType.Directory, - IsExpanded = false, - ChildrenLoaded = false - }; - node.Children.Add(subDirNode); - } - if (includeFiles) - { - // get files under the current node's path - ErrorOr> getFilesResult = _fileService.GetFiles(node.Path, includeHiddenElements); - if (getFilesResult.IsError) - return getFilesResult.Errors; - // add each file as a child node of the current directory - foreach (File file in getFilesResult.Value) - { - FileSystemTreeNodeResponse fileNode = new() - { - Name = file.Name, - Path = file.Id.Path, - ItemType = FileSystemItemType.File, - IsExpanded = false, - ChildrenLoaded = true - }; - node.Children.Add(fileNode); - } - } - node.ChildrenLoaded = true; - return Result.Success; - } -} diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidator.cs deleted file mode 100644 index 13229211..00000000 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidator.cs +++ /dev/null @@ -1,20 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentValidation; -using Lumina.Domain.Common.Errors; -#endregion - -namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; - -/// -/// Validates the needed validation rules for . -/// -public class GetDirectoryTreeQueryValidator : AbstractValidator -{ - /// - /// Initializes a new instance of the class. - /// - public GetDirectoryTreeQueryValidator() - { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); - } -} \ No newline at end of file diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQuery.cs deleted file mode 100644 index 3157cce9..00000000 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQuery.cs +++ /dev/null @@ -1,20 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Mediator; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; - -/// -/// Query for retrieving the list of directories at a path. -/// -/// The path for which to retrieve the list of directories. -/// Whether to include hidden directories or not. -[DebuggerDisplay("Path: {Path}")] -public record GetTreeDirectoriesQuery( - string? Path, - bool IncludeHiddenElements -) : IRequest>>; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs deleted file mode 100644 index 5733c577..00000000 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandler.cs +++ /dev/null @@ -1,44 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Mediator; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; - -/// -/// Handler for the query to get all directories. -/// -public class GetTreeDirectoriesQueryHandler : IRequestHandler>> -{ - private readonly IDirectoryService _directoryService; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for handling directories. - public GetTreeDirectoriesQueryHandler(IDirectoryService directoryService) - { - _directoryService = directoryService; - } - - /// - /// Gets the list of directories at the specified path. - /// - /// The query containing the requested path. - /// Cancellation token that can be used to stop the execution. - /// - /// An containing either a collection of , or an error message. - /// - public ValueTask>> Handle(GetTreeDirectoriesQuery request, CancellationToken cancellationToken) - { - ErrorOr> getSubdirectoriesResult = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements); - return ValueTask.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors)); - } -} diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidator.cs deleted file mode 100644 index 42963faa..00000000 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidator.cs +++ /dev/null @@ -1,20 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentValidation; -using Lumina.Domain.Common.Errors; -#endregion - -namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; - -/// -/// Validates the needed validation rules for . -/// -public class GetTreeDirectoriesQueryValidator : AbstractValidator -{ - /// - /// Initializes a new instance of the class. - /// - public GetTreeDirectoriesQueryValidator() - { - RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); - } -} \ No newline at end of file diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoryTreeRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoryTreeRequest.cs deleted file mode 100644 index a6414176..00000000 --- a/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoryTreeRequest.cs +++ /dev/null @@ -1,19 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.Requests.FileSystemManagement.Directories; - -/// -/// Represents a request to get the tree of directories that make up a file system path. -/// -/// The file system path for which to get the directory tree. Required. -/// Whether to include files along the directories or not. Optional. -/// Whether to include hidden file system elements or not. Optional. -[DebuggerDisplay("Path: {Path}")] -public record GetDirectoryTreeRequest( - string? Path, - bool IncludeFiles, - bool IncludeHiddenElements -); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetTreeDirectoriesRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetTreeDirectoriesRequest.cs deleted file mode 100644 index 0a5e1f10..00000000 --- a/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetTreeDirectoriesRequest.cs +++ /dev/null @@ -1,17 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.Requests.FileSystemManagement.Directories; - -/// -/// Represents a request to get the directories of a file system path. -/// -/// The file system path for which to get the directory tree. Required. -/// Whether to include hidden file system elements or not. Optional. -[DebuggerDisplay("Path: {Path}")] -public record GetTreeDirectoriesRequest( - string? Path, - bool IncludeHiddenElements -); diff --git a/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Directories.cs b/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Directories.cs index 827b8f62..6292274a 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Directories.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/FileSystemManagement/ApiRoutes.Directories.cs @@ -10,8 +10,6 @@ public static partial class ApiRoutes /// public static class Directories { - public const string GET_DIRECTORY_TREE = "/directories/get-directory-tree"; - public const string GET_TREE_DIRECTORIES = "/directories/get-tree-directories"; public const string GET_DIRECTORIES = "/directories/get-directories"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpoint.cs deleted file mode 100644 index f613131e..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpoint.cs +++ /dev/null @@ -1,56 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using FastEndpoints; -using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; -using Lumina.Contracts.Requests.FileSystemManagement.Directories; -using Lumina.Contracts.Requests.FileSystemManagement.Path; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; -using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectoryTree; - -/// -/// API endpoint for the /directories/get-directory-tree route. -/// -public class GetDirectoryTreeEndpoint : BaseEndpoint -{ - private readonly ISender _sender; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for mediating commands and queries. - public GetDirectoryTreeEndpoint(ISender sender) - { - _sender = sender; - } - - /// - /// Configures the API endpoint. - /// - public override void Configure() - { - Verbs(Http.GET); - Routes(ApiRoutes.Directories.GET_DIRECTORY_TREE); - Version(1); - DontCatchExceptions(); - } - - /// - /// Gets the tree of expanded directories leading up to the path stored in , with the additional list of drives, and children of the last child directory. - /// - /// The request containing the file system path for for which to get the directory tree. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(GetDirectoryTreeRequest request, CancellationToken cancellationToken) - { - ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.Ok(success), Problem); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpointSummary.cs deleted file mode 100644 index f47ca07b..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTree/GetDirectoryTreeEndpointSummary.cs +++ /dev/null @@ -1,189 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Contracts.Requests.FileSystemManagement.Directories; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Domain.Common.Enums.FileSystem; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectoryTree; - -/// -/// Class used for providing a textual description for the API endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class GetDirectoryTreeEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public GetDirectoryTreeEndpointSummary() - { - Summary = "Retrieves the directory tree structure for a specified file system path."; - Description = "Returns a hierarchical view of the directory tree, with options to include files and hidden elements."; - - ExampleRequest = new GetDirectoryTreeRequest( - Path: "/media/movies/", - IncludeFiles: true, - IncludeHiddenElements: true - ); - RequestExamples.Add(new RequestExample(new GetDirectoryTreeRequest( - Path: "/media/movies/", - IncludeFiles: false, - IncludeHiddenElements: false - ))); - RequestExamples.Add(new RequestExample(new GetDirectoryTreeRequest( - Path: "/media/movies/", - IncludeFiles: true, - IncludeHiddenElements: false - ))); - RequestExamples.Add(new RequestExample(new GetDirectoryTreeRequest( - Path: "/media/movies/", - IncludeFiles: false, - IncludeHiddenElements: true - ))); - - RequestParam(r => r.Path, "The file system path for which to get the directory tree. Required."); - RequestParam(r => r.IncludeFiles, "Whether to include files along the directories or not. Optional."); - RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); - - Response(200, "The directory tree structure for the specified path.", - example: new FileSystemTreeNodeResponse[] { - new() - { - Path = "/", - Name = "The Lord of the Rings - The Fellowship of the Ring (2001)", - ItemType = FileSystemItemType.Root, - IsExpanded = true, - ChildrenLoaded = true, - Children = - [ - new() - { - Path = "/media/", - Name = "media", - ItemType = FileSystemItemType.Directory, - IsExpanded = true, - ChildrenLoaded = true, - Children = - [ - new() - { - Path = "/media/movies/", - Name = "movies", - ItemType = FileSystemItemType.Directory, - IsExpanded = true, - ChildrenLoaded = true, - Children = - [ - new() - { - Path = "/media/movies/The Lord of the Rings - The Fellowship of the Ring (2001)/", - Name = "The Lord of the Rings - The Fellowship of the Ring (2001)", - ItemType = FileSystemItemType.Directory, - IsExpanded = true, - ChildrenLoaded = true, - Children = - [ - new() - { - Path = "/media/movies/The Lord of the Rings - The Fellowship of the Ring (2001)/Extras/", - Name = "Extras", - ItemType = FileSystemItemType.Directory, - IsExpanded = false, - ChildrenLoaded = false, - Children = [] - }, - new() - { - Path = "/media/movies/The Matrix (1999)/The Matrix.mkv", - Name = "The Matrix.mkv", - ItemType = FileSystemItemType.File, - IsExpanded = false, - ChildrenLoaded = false, - Children = [] - }, - new() - { - Path = "/media/movies/The Matrix (1999)/The Matrix.en.srt", - Name = "The Matrix.en.srt", - ItemType = FileSystemItemType.File, - IsExpanded = false, - ChildrenLoaded = false, - Children = [] - } - ] - }, - ] - }, - ] - }, - ] - }, - }); - - Response(401, "Authentication required.", "application/problem+json", - example: new[] - { - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "You are not authorized", - instance = "/api/v1/directories/get-directory-tree" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", - instance = "/api/v1/directories/get-directory-tree" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token is invalid", - instance = "/api/v1/directories/get-directory-tree" - } - } - ); - - Response(403, "The request failed because the provided path does not exist, or the current user doesn't have permission to access it.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", - title = "General.Failure", - status = 403, - detail = "UnauthorizedAccess", - instance = "/api/v1/directories/get-directory-tree", - traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" - } - ); - - Response(422, "The request did not pass validation checks.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc4918#section-11.2", - title = "General.Validation", - status = 422, - detail = "OneOrMoreValidationErrorsOccurred", - instance = "/api/v1/directories/get-directory-tree", - errors = new Dictionary - { - { - "General.Validation", new[] - { - "PathCannotBeEmpty" - } - } - }, - traceId = "00-839f81e411d7eb91ed5aa91e56b00bbb-7c8bd5dfabdaf2dc-00" - } - ); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpoint.cs deleted file mode 100644 index 3ead407a..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpoint.cs +++ /dev/null @@ -1,55 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using FastEndpoints; -using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; -using Lumina.Contracts.Requests.FileSystemManagement.Directories; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Presentation.Api.Common.Routes.FileSystemManagement; -using Lumina.Presentation.Api.Core.Endpoints.Common; -using Mediator; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetTreeDirectories; - -/// -/// API endpoint for the /directories/get-tree-directories route. -/// -public class GetTreeDirectoriesEndpoint : BaseEndpoint -{ - private readonly ISender _sender; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for mediating commands and queries. - public GetTreeDirectoriesEndpoint(ISender sender) - { - _sender = sender; - } - - /// - /// Configures the API endpoint. - /// - public override void Configure() - { - Verbs(Http.GET); - Routes(ApiRoutes.Directories.GET_TREE_DIRECTORIES); - Version(1); - DontCatchExceptions(); - } - - /// - /// Gets the directories of the path stored in . - /// - /// The request containing the file system path for which to get the directories. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(GetTreeDirectoriesRequest request, CancellationToken cancellationToken) - { - ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.Ok(success), Problem); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpointSummary.cs deleted file mode 100644 index a5cb1344..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectories/GetTreeDirectoriesEndpointSummary.cs +++ /dev/null @@ -1,107 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Contracts.Requests.FileSystemManagement.Directories; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Domain.Common.Enums.FileSystem; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetTreeDirectories; - -/// -/// Class used for providing a textual description for the API endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class GetTreeDirectoriesEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public GetTreeDirectoriesEndpointSummary() - { - Summary = "Retrieves the directory tree structure for the specified file system path."; - Description = "Returns the directory tree structure, with an option to include hidden file system elements."; - - ExampleRequest = new GetTreeDirectoriesRequest( - Path: "/media/movies/", - IncludeHiddenElements: true - ); - RequestExamples.Add(new RequestExample(new GetTreeDirectoriesRequest( - Path: "/media/movies/", - IncludeHiddenElements: false - ))); - - RequestParam(r => r.Path, "The file system path for which to get the directory tree. Required."); - RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); - - Response(200, "The directory tree structure is returned.", - example: new FileSystemTreeNodeResponse[] { - new() { Path = "/media/movies/The Matrix (1999)/", Name = "The Matrix (1999)", ItemType = FileSystemItemType.Directory, IsExpanded = false, ChildrenLoaded = false, Children = [] }, - new() { Path = "/media/movies/The Lord of the Rings - The Fellowship of the Ring (2001)/", Name = "The Lord of the Rings - The Fellowship of the Ring (2001)", ItemType = FileSystemItemType.Directory, IsExpanded = false, ChildrenLoaded = false, Children = [] }, - }); - - Response(401, "Authentication required.", "application/problem+json", - example: new[] - { - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "You are not authorized", - instance = "/api/v1/directories/get-tree-directories" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", - instance = "/api/v1/directories/get-tree-directories" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token is invalid", - instance = "/api/v1/directories/get-tree-directories" - } - } - ); - - Response(403, "The request failed because the provided path does not exist, or the current user doesn't have permission to access it.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", - title = "General.Failure", - status = 403, - detail = "UnauthorizedAccess", - instance = "/api/v1/directories/get-tree-directories", - traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" - } - ); - - Response(422, "The request did not pass validation checks.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc4918#section-11.2", - title = "General.Validation", - status = 422, - detail = "OneOrMoreValidationErrorsOccurred", - instance = "/api/v1/directories/get-tree-directories", - errors = new Dictionary - { - { - "General.Validation", new[] - { - "PathCannotBeEmpty" - } - } - }, - traceId = "00-839f81e411d7eb91ed5aa91e56b00bbb-7c8bd5dfabdaf2dc-00" - } - ); - } -} diff --git a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs index add2a4d1..d81b169d 100644 --- a/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs +++ b/src/Lumina.Presentation.Web/Controllers/FileSystemManagement/DirectoriesController.cs @@ -42,34 +42,4 @@ public class DirectoriesController : Controller $"directories/get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false); return Json(new { success = true, data = response }); } - - /// - /// Gets the directories of . - /// - /// The path for which to get the directories. - /// Whether to include hidden file system elements or not. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-tree-directories")] - public async Task GetTreeDirectories([FromQuery] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) - { - // TODO: check if it's really used - IEnumerable response = await _apiHttpClient.GetAsync( - $"directories/get-tree-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } - - /// - /// Gets the tree of expanded directories leading up to , with the additional list of drives, and children of the last child directory. - /// - /// The path for which to get the directory tree. - /// Whether to include hidden file system elements or not. - /// Cancellation token that can be used to stop the execution. - [HttpGet("api-get-directory-tree")] - public async Task GetDirectoryTree([FromQuery] string path, [FromQuery] bool includeFiles, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken) - { - // TODO: check if it's really used - FileSystemTreeNodeModel[] response = await _apiHttpClient.GetAsync( - $"directories/get-directory-tree?path={Uri.EscapeDataString(path)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = response }); - } } diff --git a/src/Lumina.sln b/src/Lumina.sln index 45de3430..3f10d232 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -126,8 +126,6 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "directories", "directories", "{FBD8915E-DFE2-4C16-8B47-64383AB0719D}" ProjectSection(SolutionItems) = preProject ..\docs\technical\requests\file-system-management\directories\GetDirectories.http = ..\docs\technical\requests\file-system-management\directories\GetDirectories.http - ..\docs\technical\requests\file-system-management\directories\GetDirectoryTree.http = ..\docs\technical\requests\file-system-management\directories\GetDirectoryTree.http - ..\docs\technical\requests\file-system-management\directories\GetTreeDirectories.http = ..\docs\technical\requests\file-system-management\directories\GetTreeDirectories.http EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "drives", "drives", "{DB498346-5F46-49FC-B2E9-8239C56791FF}" diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs deleted file mode 100644 index 4692aa83..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs +++ /dev/null @@ -1,430 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Domain.Common.Enums.FileSystem; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures; -using Microsoft.AspNetCore.Http; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Runtime.InteropServices; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Directories; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetDirectoryTreeEndpointTests : IClassFixture, IAsyncLifetime -{ - private HttpClient _client; - private readonly AuthenticatedLuminaApiFactory _apiFactory; - private readonly JsonSerializerOptions _jsonOptions = new() - { - ReferenceHandler = ReferenceHandler.Preserve, - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public GetDirectoryTreeEndpointTests(AuthenticatedLuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - _apiFactory = apiFactory; - } - - /// - /// Initializes authenticated API client. - /// - public async Task InitializeAsync() - { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); - } - - [Fact] - public async Task ExecuteAsync_WhenCalledWithValidPathAndIncludeFilesAndNotIncludeHiddenElements_ShouldReturnDirectoryTreeWithFilesAndNotHiddenElements() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - - bool includeFiles = true; - bool includeHiddenElements = false; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - string content = await response.Content.ReadAsStringAsync(); - List? treeNodes = JsonSerializer.Deserialize>(content, _jsonOptions); - - treeNodes.Should().NotBeNull(); - treeNodes!.Should().NotBeEmpty(); - - string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - if (s_isUnix) // on UNIX, the leading slash is considered "the drive", the root location - add it! - pathSegments = ["/", .. pathSegments]; - // recursively validate the tree structure - void ValidateNode(FileSystemTreeNodeResponse node, int depth) - { - // ensure the current node's name and path match the expected segment - string expectedSegment = pathSegments[depth]; - - if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':' - && !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar)) - expectedSegment += System.IO.Path.DirectorySeparatorChar; - - node.Name.Should().Be(expectedSegment); - - string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); - if (expectedPath.StartsWith("//")) - expectedPath = expectedPath[1..]; - if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar)) - expectedPath += System.IO.Path.DirectorySeparatorChar; - node.Path.Should().EndWith(expectedPath); - - // if the node is a drive or directory, check its children recursively - if (node.ItemType is FileSystemItemType.Root or FileSystemItemType.Directory) - { - node.Children.Should().NotBeNull(); - foreach (FileSystemTreeNodeResponse childNode in node.Children) - { - if (childNode.ItemType != FileSystemItemType.File) // go deeper one level, if the iterated node's children is also a directory - ValidateNode(childNode, depth + 1); - else if (childNode.ItemType is FileSystemItemType.File) - { - childNode.Children.Should().BeEmpty(); // files should not have children - childNode.Name.Should().Be("TestFile_2.txt"); - } - } - } - } - FileSystemTreeNodeResponse rootNode = treeNodes!.Where(node => testPath.StartsWith(node.Name)).First(); - ValidateNode(rootNode, 0); - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task ExecuteAsync_WhenCalledWithValidPathAndIncludeFilesAndWithIncludeHiddenElements_ShouldReturnDirectoryTreeWithFilesAndHiddenElements() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - - bool includeFiles = true; - bool includeHiddenElements = true; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - string content = await response.Content.ReadAsStringAsync(); - List? treeNodes = JsonSerializer.Deserialize>(content, _jsonOptions); - - treeNodes.Should().NotBeNull(); - treeNodes!.Should().NotBeEmpty(); - - string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - if (s_isUnix) // on UNIX, the leading slash is considered "the drive", the root location - add it! - pathSegments = ["/", .. pathSegments]; - - // recursively validate the tree structure - void ValidateNode(FileSystemTreeNodeResponse node, int depth) - { - // ensure the current node's name and path match the expected segment - string expectedSegment = pathSegments[depth]; - - if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':' - && !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar)) - expectedSegment += System.IO.Path.DirectorySeparatorChar; - - node.Name.Should().Be(expectedSegment); - - string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); - if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar)) - expectedPath += System.IO.Path.DirectorySeparatorChar; - if (expectedPath.StartsWith("//")) - expectedPath = expectedPath[1..]; - node.Path.Should().EndWith(expectedPath); - - // if the node is a drive or directory, check its children recursively - if (node.ItemType is FileSystemItemType.Root or FileSystemItemType.Directory) - { - node.Children.Should().NotBeNull(); - foreach (FileSystemTreeNodeResponse childNode in node.Children) - { - if (childNode.ItemType != FileSystemItemType.File) // go deeper one level, if the iterated node's children is also a directory - ValidateNode(childNode, depth + 1); - else if (childNode.ItemType is FileSystemItemType.File) - { - childNode.Children.Should().BeEmpty(); // files should not have children - childNode.Name.Should().BeOneOf((s_isUnix ? "." : string.Empty) + "TestFile_1.txt", "TestFile_2.txt"); - } - } - } - } - FileSystemTreeNodeResponse rootNode = treeNodes!.Where(node => testPath.StartsWith(node.Name)).First(); - ValidateNode(rootNode, 0); - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeFilesAndNotIncludeHiddenElements_ShouldReturnDirectoryTreeWithoutFiles() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - - bool includeFiles = false; - bool includeHiddenElements = false; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - string content = await response.Content.ReadAsStringAsync(); - List? treeNodes = JsonSerializer.Deserialize>(content, _jsonOptions); - - treeNodes.Should().NotBeNull(); - treeNodes!.Should().NotBeEmpty(); - - // there should not be a File node - treeNodes.Should().AllSatisfy(node => node.ItemType.Should().BeOneOf(FileSystemItemType.Directory, FileSystemItemType.Root)); - - string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - if (s_isUnix) // on UNIX, the leading slash is considered "the drive", the root location - add it! - pathSegments = ["/", .. pathSegments]; - - // recursively validate the tree structure - void ValidateNode(FileSystemTreeNodeResponse node, int depth) - { - // ensure the current node's name and path match the expected segment - string expectedSegment = pathSegments[depth]; - - if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':' - && !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar)) - expectedSegment += System.IO.Path.DirectorySeparatorChar; - - node.Name.Should().Be(expectedSegment); - - string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); - if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar)) - expectedPath += System.IO.Path.DirectorySeparatorChar; - if (expectedPath.StartsWith("//")) - expectedPath = expectedPath[1..]; - node.Path.Should().EndWith(expectedPath); - - node.Children.Should().NotBeNull(); - foreach (FileSystemTreeNodeResponse childNode in node.Children) - ValidateNode(childNode, depth + 1); - } - FileSystemTreeNodeResponse rootNode = treeNodes!.Where(node => testPath.StartsWith(node.Name)).First(); - ValidateNode(rootNode, 0); - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeFilesAndIncludeHiddenElements_ShouldReturnDirectoryTreeWithoutFiles() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - - bool includeFiles = false; - bool includeHiddenElements = true; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - string content = await response.Content.ReadAsStringAsync(); - List? treeNodes = JsonSerializer.Deserialize>(content, _jsonOptions); - - treeNodes.Should().NotBeNull(); - treeNodes!.Should().NotBeEmpty(); - - // there should not be a File node - treeNodes.Should().AllSatisfy(node => node.ItemType.Should().BeOneOf(FileSystemItemType.Directory, FileSystemItemType.Root)); - - string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - if (s_isUnix) // on UNIX, the leading slash is considered "the drive", the root location - add it! - pathSegments = ["/", .. pathSegments]; - - // recursively validate the tree structure - void ValidateNode(FileSystemTreeNodeResponse node, int depth) - { - // ensure the current node's name and path match the expected segment - string expectedSegment = pathSegments[depth]; - - if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':' - && !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar)) - expectedSegment += System.IO.Path.DirectorySeparatorChar; - - node.Name.Should().Be(expectedSegment); - - string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); - if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar)) - expectedPath += System.IO.Path.DirectorySeparatorChar; - if (expectedPath.StartsWith("//")) - expectedPath = expectedPath[1..]; - node.Path.Should().EndWith(expectedPath); - - node.Children.Should().NotBeNull(); - foreach (FileSystemTreeNodeResponse childNode in node.Children) - ValidateNode(childNode, depth + 1); - } - FileSystemTreeNodeResponse rootNode = treeNodes!.Where(node => testPath.StartsWith(node.Name)).First(); - ValidateNode(rootNode, 0); - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnValidationProblemResult() - { - // Arrange - string invalidPath = "invalid:path"; - string encodedPath = Uri.EscapeDataString(invalidPath); - bool includeFiles = false; - bool includeHiddenElements = true; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(encodedPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); - response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); - string content = await response.Content.ReadAsStringAsync(); - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); - problemDetails["title"].GetString().Should().Be("General.Validation"); - problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-directory-tree"); - problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred"); - problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); - problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); - - Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); - errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["InvalidPath"]); - } - - [Fact] - public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult() - { - // Arrange - string emptyPath = ""; - string encodedPath = Uri.EscapeDataString(emptyPath); - bool includeFiles = false; - bool includeHiddenElements = true; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(encodedPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); - response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); - string content = await response.Content.ReadAsStringAsync(); - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); - problemDetails["title"].GetString().Should().Be("General.Validation"); - problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-directory-tree"); - problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred"); - problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); - problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); - - Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); - errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]); - } - - [Fact] - public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() - { - // Arrange - string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); - string encodedPath = Uri.EscapeDataString(testPath); - bool includeFiles = false; - bool includeHiddenElements = true; - using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); - - // Act - Func act = async () => await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(encodedPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cts.Token); - - // Assert - await act.Should().NotThrowAsync(); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() - { - // Arrange - string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); - string encodedPath = Uri.EscapeDataString(testPath); - bool includeFiles = false; - bool includeHiddenElements = true; - using CancellationTokenSource cts = new(); - - // Act - Func act = async () => - { - cts.Cancel(); // Cancel the token immediately - await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(encodedPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cts.Token); - }; - - // Assert - await act.Should().ThrowAsync(); - } - - /// - /// Disposes API factory resources. - /// - public Task DisposeAsync() - { - _apiFactory.Dispose(); - return Task.CompletedTask; - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs deleted file mode 100644 index 52539919..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs +++ /dev/null @@ -1,266 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Domain.Common.Enums.FileSystem; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures; -using Microsoft.AspNetCore.Http; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Runtime.InteropServices; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Directories; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetTreeDirectoriesEndpointTests : IClassFixture, IAsyncLifetime -{ - private HttpClient _client; - private readonly AuthenticatedLuminaApiFactory _apiFactory; - private readonly JsonSerializerOptions _jsonOptions = new() - { - ReferenceHandler = ReferenceHandler.Preserve, - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public GetTreeDirectoriesEndpointTests(AuthenticatedLuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - _apiFactory = apiFactory; - } - - /// - /// Initializes authenticated API client. - /// - public async Task InitializeAsync() - { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); - } - - [Fact] - public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnTreeDirectoriesWithoutHiddenElements() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; - string encodedPath = Uri.EscapeDataString(testPath); - bool includeHiddenElements = false; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - string content = await response.Content.ReadAsStringAsync(); - List? treeNodes = JsonSerializer.Deserialize>(content, _jsonOptions); - - treeNodes.Should().NotBeNull(); - treeNodes!.Should().NotBeEmpty(); - - string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - - - FileSystemTreeNodeResponse firstNode = treeNodes!.First(); - firstNode.Name.Should().Be("NestedDirectory_3"); - firstNode.Path.Should().Be(System.IO.Path.Combine(testPath, "NestedDirectory_3" + System.IO.Path.DirectorySeparatorChar)); - firstNode.ItemType.Should().Be(FileSystemItemType.Directory); - treeNodes.Should().AllSatisfy(n => n.ItemType.Should().Be(FileSystemItemType.Directory)); - treeNodes!.Count.Should().Be(1); // only directories - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnNoTreeDirectories() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; - testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child - string encodedPath = Uri.EscapeDataString(testPath); - bool includeHiddenElements = false; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - string content = await response.Content.ReadAsStringAsync(); - List? treeNodes = JsonSerializer.Deserialize>(content, _jsonOptions); - - treeNodes.Should().NotBeNull(); - treeNodes!.Should().BeEmpty(); - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task ExecuteAsync_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnTreeDirectoriesWithHiddenElements() - { - // Arrange - FileSystemStructureFixture fileSystemFixture = new(); - string testPath = fileSystemFixture.CreateFileSystemStructure(); - testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; - testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child - string encodedPath = Uri.EscapeDataString(testPath); - bool includeHiddenElements = true; - try - { - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.EnsureSuccessStatusCode(); - response.StatusCode.Should().Be(HttpStatusCode.OK); - - string content = await response.Content.ReadAsStringAsync(); - List? treeNodes = JsonSerializer.Deserialize>(content, _jsonOptions); - - treeNodes.Should().NotBeNull(); - treeNodes!.Should().NotBeEmpty(); - - string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); - - - FileSystemTreeNodeResponse firstNode = treeNodes!.First(); - firstNode.Name.Should().Be((s_isUnix ? "." : string.Empty) + "NestedDirectory_2"); - firstNode.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isUnix ? "." : string.Empty) + "NestedDirectory_2" + System.IO.Path.DirectorySeparatorChar)); - firstNode.ItemType.Should().Be(FileSystemItemType.Directory); - treeNodes.Should().AllSatisfy(n => n.ItemType.Should().Be(FileSystemItemType.Directory)); - treeNodes!.Count.Should().Be(1); // only directories - } - finally - { - fileSystemFixture.CleanupFileSystemStructure(); - } - } - - [Fact] - public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult() - { - // Arrange - string invalidPath = "invalid:path"; - string encodedPath = Uri.EscapeDataString(invalidPath); - bool includeHiddenElements = true; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.Forbidden); - string content = await response.Content.ReadAsStringAsync(); - - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden); - problemDetails["title"].GetString().Should().Be("General.Failure"); - problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-tree-directories"); - problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess"); - problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4"); - problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); - } - - [Fact] - public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult() - { - // Arrange - string emptyPath = ""; - string encodedPath = Uri.EscapeDataString(emptyPath); - bool includeHiddenElements = true; - - // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); - response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); - string content = await response.Content.ReadAsStringAsync(); - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); - problemDetails["title"].GetString().Should().Be("General.Validation"); - problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-tree-directories"); - problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred"); - problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); - problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); - - Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); - errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]); - } - - [Fact] - public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() - { - // Arrange - string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); - string encodedPath = Uri.EscapeDataString(testPath); - bool includeHiddenElements = true; - using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); - - // Act - Func act = async () => await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token); - - // Assert - await act.Should().NotThrowAsync(); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() - { - // Arrange - string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); - string encodedPath = Uri.EscapeDataString(testPath); - bool includeHiddenElements = true; - using CancellationTokenSource cts = new(); - - // Act - Func act = async () => - { - cts.Cancel(); // Cancel the token immediately - await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token); - }; - - // Assert - await act.Should().ThrowAsync(); - } - - /// - /// Disposes API factory resources. - /// - public Task DisposeAsync() - { - _apiFactory.Dispose(); - return Task.CompletedTask; - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs deleted file mode 100644 index c68c9431..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs +++ /dev/null @@ -1,52 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Presentation.Api.SecurityTests.Common.Setup; -using Microsoft.AspNetCore.Http; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Text.Json; -#endregion - -namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.FileSystemManagement.Directories; - -/// -/// Contains security tests for the /directories/get-directory-tree route. -/// -[ExcludeFromCodeCoverage] -public class GetDirectoryTreeEndpointTests : IClassFixture -{ - private readonly HttpClient _client; - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public GetDirectoryTreeEndpointTests(LuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - } - - [Fact] - public async Task GetDirectoryTree_WhenUnauthorized_ShouldReturnUnauthorizedResult() - { - // Act - HttpResponseMessage response = await _client.GetAsync("/api/v1/directories/get-directory-tree"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); - - string content = await response.Content.ReadAsStringAsync(); - - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status401Unauthorized); - problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7235#section-3.1"); - problemDetails["title"].GetString().Should().Be("Unauthorized"); - problemDetails["instance"].GetProperty("value").GetString().Should().Be("/api/v1/directories/get-directory-tree"); - problemDetails["detail"].GetString().Should().Be("Authentication failed"); - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs deleted file mode 100644 index 95522397..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs +++ /dev/null @@ -1,52 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Presentation.Api.SecurityTests.Common.Setup; -using Microsoft.AspNetCore.Http; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Text.Json; -#endregion - -namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.FileSystemManagement.Directories; - -/// -/// Contains security tests for the /directories/get-tree-directories route. -/// -[ExcludeFromCodeCoverage] -public class GetTreeDirectoriesEndpointTests : IClassFixture -{ - private readonly HttpClient _client; - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public GetTreeDirectoriesEndpointTests(LuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - } - - [Fact] - public async Task GetTreeDirectories_WhenUnauthorized_ShouldReturnUnauthorizedResult() - { - // Act - HttpResponseMessage response = await _client.GetAsync("/api/v1/directories/get-tree-directories"); - - // Assert - response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); - - string content = await response.Content.ReadAsStringAsync(); - - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status401Unauthorized); - problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7235#section-3.1"); - problemDetails["title"].GetString().Should().Be("Unauthorized"); - problemDetails["instance"].GetProperty("value").GetString().Should().Be("/api/v1/directories/get-tree-directories"); - problemDetails["detail"].GetString().Should().Be("Authentication failed"); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMappingTests.cs deleted file mode 100644 index 7520a091..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoryTreeRequestMappingTests.cs +++ /dev/null @@ -1,44 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; -using FluentAssertions; -using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; -using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; -using Lumina.Contracts.Requests.FileSystemManagement.Directories; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Directories; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetDirectoryTreeRequestMappingTests -{ - private readonly IFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public GetDirectoryTreeRequestMappingTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - } - - [Fact] - public void ToQuery_WhenMappingGetDirectoryTreeRequest_ShouldMapCorrectly() - { - // Arrange - GetDirectoryTreeRequest request = _fixture.Create(); - - // Act - GetDirectoryTreeQuery result = request.ToQuery(); - - // Assert - result.Should().NotBeNull(); - result.Path.Should().Be(request.Path); - result.IncludeFiles.Should().Be(request.IncludeFiles); - result.IncludeHiddenElements.Should().Be(request.IncludeHiddenElements); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMappingTests.cs deleted file mode 100644 index 4f249fc1..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetTreeDirectoriesRequestMappingTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; -using FluentAssertions; -using Lumina.Application.Common.Mapping.FileSystemManagement.Directories; -using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; -using Lumina.Contracts.Requests.FileSystemManagement.Directories; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Directories; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetTreeDirectoriesRequestMappingTests -{ - private readonly IFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public GetTreeDirectoriesRequestMappingTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - } - - [Fact] - public void ToQuery_WhenMappingGetTreeDirectoriesRequest_ShouldMapCorrectly() - { - // Arrange - GetTreeDirectoriesRequest request = _fixture.Create(); - - // Act - GetTreeDirectoriesQuery result = request.ToQuery(); - - // Assert - result.Should().NotBeNull(); - result.Path.Should().Be(request.Path); - result.IncludeHiddenElements.Should().Be(request.IncludeHiddenElements); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/Fixtures/GetDirectoryTreeQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/Fixtures/GetDirectoryTreeQueryFixture.cs deleted file mode 100644 index 44a8f634..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/Fixtures/GetDirectoryTreeQueryFixture.cs +++ /dev/null @@ -1,33 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class GetDirectoryTreeQueryFixture -{ - /// - /// Creates a random valid query to get directory tree. - /// - /// Whether to include file system files or not. - /// Whether to include hidden file system elements or not. - /// The created query to get directory tree. - public static GetDirectoryTreeQuery CreateGetDirectoryTreeQuery(bool includeFiles = false, bool includeHiddenElements = false) - { - return new Faker() - .CustomInstantiator(f => new GetDirectoryTreeQuery( - default!, - default, - default - )) - .RuleFor(x => x.Path, f => f.System.DirectoryPath()) - .RuleFor(x => x.IncludeFiles, f => includeFiles) - .RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandlerTests.cs deleted file mode 100644 index e3cf4fc5..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryHandlerTests.cs +++ /dev/null @@ -1,383 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using ErrorOr; -using FluentAssertions; -using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree.Fixtures; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.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.FileSystemManagement.Directories.Queries.GetDirectoryTree; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetDirectoryTreeQueryHandlerTests -{ - private readonly IDriveService _mockDriveService; - private readonly IDirectoryService _mockDirectoryService; - private readonly IFileService _mockFileService; - private readonly IPathService _mockPathService; - private readonly GetDirectoryTreeQueryHandler _sut; - private readonly DirectoryFixture _directoryFixture; - private readonly PathSegmentFixture _pathSegmentFixture; - private readonly FileFixture _fileFixture; - - /// - /// Initializes a new instance of the class. - /// - public GetDirectoryTreeQueryHandlerTests() - { - _mockDriveService = Substitute.For(); - _mockDirectoryService = Substitute.For(); - _mockFileService = Substitute.For(); - _mockPathService = Substitute.For(); - _sut = new GetDirectoryTreeQueryHandler(_mockDriveService, _mockDirectoryService, _mockFileService, _mockPathService); - _directoryFixture = new DirectoryFixture(); - _pathSegmentFixture = new PathSegmentFixture(); - _fileFixture = new FileFixture(); - } - - [Fact] - public async Task Handle_WhenCalledWithValidQueryAndNoIncludeFiles_ShouldReturnSuccessResult() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(false, true); - - // Create a drive that matches what the implementation expects - string drivePath = "C:\\"; - IEnumerable drives = - [ - WindowsRootItem.Create(drivePath, "C:").Value - ]; - - // Ensure the first path segment matches the drive path - PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true); - List otherPathSegments = _pathSegmentFixture.CreateMany(2); - IEnumerable pathSegments = new[] { firstPathSegment }.Concat(otherPathSegments); - - IEnumerable subdirectories = _directoryFixture.CreateMany(2); - IEnumerable files = _fileFixture.CreateMany(2); - - _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments)); - _mockPathService.CombinePath(Arg.Is(x => true), Arg.Is(y => true)).Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); - _mockDirectoryService.GetSubdirectories(Arg.Any(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories)); - _mockFileService.GetFiles(Arg.Any(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(files)); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeFalse(); - result.Value.Should().NotBeEmpty(); - result.Value.First().Children.Should().NotBeEmpty(); - _mockDriveService.Received(1).GetDrives(); - _mockPathService.Received(1).ParsePath(query.Path!); - _mockDirectoryService.Received(1).GetSubdirectories(Arg.Any(), query.IncludeHiddenElements); - _mockFileService.Received(0).GetFiles(Arg.Any(), query.IncludeHiddenElements); - } - - [Fact] - public async Task Handle_WhenCalledWithValidQueryAndIncludeFiles_ShouldReturnSuccessResult() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(true, true); - - // Create a drive that matches what the implementation expects - string drivePath = "C:\\"; - IEnumerable drives = - [ - WindowsRootItem.Create(drivePath, "C:").Value - ]; - - // Ensure the first path segment matches the drive path - PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true); - List otherPathSegments = _pathSegmentFixture.CreateMany(2); - IEnumerable pathSegments = new[] { firstPathSegment }.Concat(otherPathSegments); - - IEnumerable subdirectories = _directoryFixture.CreateMany(2); - IEnumerable files = _fileFixture.CreateMany(2); - - _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments)); - _mockPathService.CombinePath(Arg.Is(x => true), Arg.Is(y => true)).Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); - _mockDirectoryService.GetSubdirectories(Arg.Any(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories)); - _mockFileService.GetFiles(Arg.Any(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(files)); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeFalse(); - result.Value.Should().NotBeEmpty(); - result.Value.First().Children.Should().NotBeEmpty(); - _mockDriveService.Received(1).GetDrives(); - _mockPathService.Received(1).ParsePath(query.Path!); - _mockDirectoryService.Received(1).GetSubdirectories(Arg.Any(), query.IncludeHiddenElements); - _mockFileService.Received(1).GetFiles(Arg.Any(), query.IncludeHiddenElements); - } - - [Fact] - public async Task Handle_WhenGetDrivesReturnsError_ShouldReturnFailureResult() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); - Error error = Error.Failure("DriveService.Error", "An error occurred"); - _mockDriveService.GetDrives().Returns(error); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(error); - _mockDriveService.Received(1).GetDrives(); - } - - [Fact] - public async Task Handle_WhenParsePathReturnsError_ShouldReturnFailureResult() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); - IEnumerable drives = - [ - WindowsRootItem.Create("C:\\", "Local Disk").Value - ]; - Error error = Error.Failure("PathService.Error", "An error occurred"); - - _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path!).Returns(error); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(error); - _mockDriveService.Received(1).GetDrives(); - _mockPathService.Received(1).ParsePath(query.Path!); - } - - [Fact] - public async Task Handle_WhenCombinePathReturnsError_ShouldReturnFailureResult() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); - IEnumerable drives = - [ - WindowsRootItem.Create("C:\\", "C:").Value - ]; - PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true); - IEnumerable pathSegments = new[] { firstPathSegment }.Concat(_pathSegmentFixture.CreateMany(2)); - Error error = Error.Failure("PathService.Error", "An error occurred"); - - _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments)); - _mockPathService.CombinePath(Arg.Any(), Arg.Any()).Returns(error); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(error); - _mockDriveService.Received(1).GetDrives(); - _mockPathService.Received(1).ParsePath(query.Path!); - _mockPathService.Received(1).CombinePath(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task Handle_WhenGetSubdirectoriesReturnsError_ShouldReturnFailureResult() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); - IEnumerable drives = - [ - WindowsRootItem.Create("C:\\", "C:").Value - ]; - PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true); - IEnumerable pathSegments = new[] { firstPathSegment }.Concat(_pathSegmentFixture.CreateMany(2)); - Error error = Error.Failure("DirectoryService.Error", "An error occurred"); - - _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments)); - _mockPathService.CombinePath(Arg.Is(x => true), Arg.Is(y => true)).Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); - _mockDirectoryService.GetSubdirectories(Arg.Any(), query.IncludeHiddenElements).Returns(error); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(error); - _mockDriveService.Received(1).GetDrives(); - _mockPathService.Received(1).ParsePath(query.Path!); - _mockDirectoryService.Received(1).GetSubdirectories(Arg.Any(), query.IncludeHiddenElements); - } - - [Fact] - public async Task Handle_WhenGetFilesReturnsError_ShouldReturnFailureResult() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(true); - IEnumerable drives = - [ - WindowsRootItem.Create("C:\\", "C:").Value - ]; - PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true); - IEnumerable pathSegments = new[] { firstPathSegment }.Concat(_pathSegmentFixture.CreateMany(2)); - IEnumerable subdirectories = _directoryFixture.CreateMany(2); - Error error = Error.Failure("FileService.Error", "An error occurred"); - - _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments)); - _mockPathService.CombinePath(Arg.Is(x => true), Arg.Is(y => true)).Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); - _mockDirectoryService.GetSubdirectories(Arg.Any(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories)); - _mockFileService.GetFiles(Arg.Any(), query.IncludeHiddenElements).Returns(error); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(error); - _mockDriveService.Received(1).GetDrives(); - _mockPathService.Received(1).ParsePath(query.Path!); - _mockDirectoryService.Received(1).GetSubdirectories(Arg.Any(), query.IncludeHiddenElements); - _mockFileService.Received(1).GetFiles(Arg.Any(), query.IncludeHiddenElements); - } - - [Fact] - public async Task Handle_WhenPathOnlyContainsRoot_ShouldReturnOnlyRootNode() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); - query = query with { Path = "C:" }; - IEnumerable drives = [WindowsRootItem.Create("C:\\", "C:").Value]; - PathSegment rootSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true); - - _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From((IEnumerable)[rootSegment])); - _mockDirectoryService.GetSubdirectories(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeFalse(); - result.Value.Should().HaveCount(1); - result.Value.First().Name.Should().Be("C:"); - result.Value.First().Children.Should().BeEmpty(); - } - - [Fact] - public async Task Handle_WhenPathHasManySegments_ShouldCreateCorrectTreeStructure() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); - IEnumerable drives = [WindowsRootItem.Create("C:\\", "C:").Value]; - List pathSegments = - [ - _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true), - _pathSegmentFixture.CreatePathSegment(name: "Users"), - _pathSegmentFixture.CreatePathSegment(name: "Username"), - _pathSegmentFixture.CreatePathSegment(name: "Documents"), - _pathSegmentFixture.CreatePathSegment(name: "Projects"), - _pathSegmentFixture.CreatePathSegment(name: "MyProject") - ]; - - _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From((IEnumerable)pathSegments)); - _mockPathService.Exists(Arg.Any(), Arg.Any()).Returns(true); - _mockPathService.CombinePath(Arg.Any(), Arg.Any()) - .Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); - - _mockDirectoryService.GetSubdirectories(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeFalse(); - result.Value.Should().HaveCount(1); - FileSystemTreeNodeResponse root = result.Value.First(); - root.Name.Should().Be("C:"); - root.Children.Should().HaveCount(1); - root.Children.First().Name.Should().Be("Users"); - root.Children.First().Children.First().Name.Should().Be("Username"); - root.Children.First().Children.First().Children.First().Name.Should().Be("Documents"); - root.Children.First().Children.First().Children.First().Children.First().Name.Should().Be("Projects"); - root.Children.First().Children.First().Children.First().Children.First().Children.First().Name.Should().Be("MyProject"); - } - - [Fact] - public async Task Handle_WhenPathContainsSpecialCharacters_ShouldHandleCorrectly() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); - IEnumerable drives = [WindowsRootItem.Create("C:\\", "C:").Value]; - List pathSegments = - [ - _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true), - _pathSegmentFixture.CreatePathSegment(name: "Program Files"), - _pathSegmentFixture.CreatePathSegment(name: "My Awesome App!"), - _pathSegmentFixture.CreatePathSegment(name: "Data Files") - ]; - - _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.Exists(Arg.Any(), Arg.Any()).Returns(true); - _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From((IEnumerable)pathSegments)); - _mockPathService.CombinePath(Arg.Any(), Arg.Any()) - .Returns(callInfo => $"{callInfo.ArgAt(0)}\\{callInfo.ArgAt(1)}"); - _mockDirectoryService.GetSubdirectories(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeFalse(); - result.Value.Should().HaveCount(1); - FileSystemTreeNodeResponse root = result.Value.First(); - root.Children.First().Name.Should().Be("Program Files"); - root.Children.First().Children.First().Name.Should().Be("My Awesome App!"); - } - - [Fact] - public async Task Handle_WhenIncludeHiddenElementsIsFalse_ShouldNotIncludeHiddenItems() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(includeHiddenElements: false); - IEnumerable drives = [WindowsRootItem.Create("C:\\", "C:").Value]; - PathSegment rootSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true); - - _mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives)); - _mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From((IEnumerable)[rootSegment])); - - IEnumerable visibleDirectories = _directoryFixture.CreateMany(2); - _mockDirectoryService.GetSubdirectories(Arg.Any(), false).Returns(ErrorOrFactory.From(visibleDirectories)); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeFalse(); - result.Value.First().Children.Should().HaveCount(2); - _mockDirectoryService.Received(1).GetSubdirectories(Arg.Any(), false); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidatorTests.cs deleted file mode 100644 index f5743282..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectoryTree/GetDirectoryTreeQueryValidatorTests.cs +++ /dev/null @@ -1,141 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; -using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree.Fixtures; -using Lumina.Domain.Common.Errors; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetDirectoryTreeQueryValidatorTests -{ - private readonly GetDirectoryTreeQueryValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public GetDirectoryTreeQueryValidatorTests() - { - _validator = new GetDirectoryTreeQueryValidator(); - } - - [Fact] - public void Validate_WhenPathIsNull_ShouldHaveValidationError() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); - query = query with { Path = null! }; - - // Act - TestValidationResult result = _validator.TestValidate(query); - - // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); - } - - [Fact] - public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); - query = query with { Path = string.Empty }; - - // Act - TestValidationResult result = _validator.TestValidate(query); - - // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); - } - - [Fact] - public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); - query = query with { Path = " " }; - - // Act - TestValidationResult result = _validator.TestValidate(query); - - // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); - } - - [Fact] - public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); - query = query with { Path = "/valid/path" }; - - // Act - TestValidationResult result = _validator.TestValidate(query); - - // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Path); - } - - [Fact] - public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); - query = query with { IncludeHiddenElements = true }; - - // Act - TestValidationResult result = _validator.TestValidate(query); - - // Assert - result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); - } - - [Fact] - public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); - query = query with { IncludeHiddenElements = false }; - - // Act - TestValidationResult result = _validator.TestValidate(query); - - // Assert - result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); - } - - [Fact] - public void Validate_WhenIncludeFilesIsTrue_ShouldNotHaveValidationError() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); - query = query with { IncludeFiles = true }; - - // Act - TestValidationResult result = _validator.TestValidate(query); - - // Assert - result.ShouldNotHaveValidationErrorFor(x => x.IncludeFiles); - } - - [Fact] - public void Validate_WhenIncludeFilesIsFalse_ShouldNotHaveValidationError() - { - // Arrange - GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(); - query = query with { IncludeFiles = false }; - - // Act - TestValidationResult result = _validator.TestValidate(query); - - // Assert - result.ShouldNotHaveValidationErrorFor(x => x.IncludeFiles); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/Fixtures/GetTreeDirectoriesQueryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/Fixtures/GetTreeDirectoriesQueryFixture.cs deleted file mode 100644 index d076de03..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/Fixtures/GetTreeDirectoriesQueryFixture.cs +++ /dev/null @@ -1,30 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories.Fixtures; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class GetTreeDirectoriesQueryFixture -{ - /// - /// Creates a random valid query to get tree directories. - /// - /// Whether to include hidden file system elements or not. - /// The created query to get tree directory. - public static GetTreeDirectoriesQuery CreateGetTreeDirectoryQuery(bool includeHiddenElements = false) - { - return new Faker() - .CustomInstantiator(f => new GetTreeDirectoriesQuery( - default!, - default - )) - .RuleFor(x => x.Path, f => f.System.DirectoryPath()) - .RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs deleted file mode 100644 index 82010e94..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryHandlerTests.cs +++ /dev/null @@ -1,232 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; -using ErrorOr; -using FluentAssertions; -using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories.Fixtures; -using Lumina.Domain.Common.Enums.FileSystem; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; -using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; -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.FileSystemManagement.Directories.Queries.GetTreeDirectories; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetTreeDirectoriesQueryHandlerTests -{ - private readonly IFixture _fixture; - private readonly IDirectoryService _mockDirectoryService; - private readonly GetTreeDirectoriesQueryHandler _sut; - private readonly DirectoryFixture _directoryFixture; - - /// - /// Initializes a new instance of the class. - /// - public GetTreeDirectoriesQueryHandlerTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _mockDirectoryService = Substitute.For(); - _sut = new GetTreeDirectoriesQueryHandler(_mockDirectoryService); - _directoryFixture = new DirectoryFixture(); - } - - [Fact] - public async Task Handle_WhenCalledWithValidQueryWithoutFilesIncluded_ShouldReturnSuccessResult() - { - // Arrange - GetTreeDirectoriesQuery getDirectoriesQuery = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(false); - - IEnumerable directories = _directoryFixture.CreateMany(); - - _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements) - .Returns(ErrorOrFactory.From(directories)); - - // Act - ErrorOr> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None); - - // Assert - result.IsError.Should().BeFalse(); - result.Value.Should().BeAssignableTo>(); - result.Value.Should().HaveCount(directories.Count()); - - List resultList = result.Value.ToList(); - List directoriesList = directories.ToList(); - - for (int i = 0; i < resultList.Count; i++) - { - resultList[i].Path.Should().Be(directoriesList[i].Id.Path); - resultList[i].Name.Should().Be(directoriesList[i].Name); - resultList[i].ItemType.Should().Be(FileSystemItemType.Directory); - resultList[i].IsExpanded.Should().BeFalse(); - resultList[i].ChildrenLoaded.Should().BeFalse(); - resultList[i].Children.Should().BeEmpty(); - } - - _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements); - } - - [Fact] - public async Task Handle_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult() - { - // Arrange - GetTreeDirectoriesQuery getDirectoriesQuery = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(true); - - IEnumerable directories = _directoryFixture.CreateManyNested(); - - _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements) - .Returns(ErrorOrFactory.From(directories)); - - // Act - ErrorOr> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None); - - // Assert - result.IsError.Should().BeFalse(); - result.Value.Should().BeAssignableTo>(); - result.Value.Should().HaveCount(directories.Count()); - - List resultList = result.Value.ToList(); - List directoriesList = directories.ToList(); - - for (int i = 0; i < resultList.Count; i++) - { - FileSystemTreeNodeResponse response = resultList[i]; - Directory directory = directoriesList[i]; - - response.Path.Should().Be(directory.Id.Path); - response.Name.Should().Be(directory.Name); - response.ItemType.Should().Be(FileSystemItemType.Directory); - response.IsExpanded.Should().BeFalse(); - response.ChildrenLoaded.Should().BeFalse(); - response.Children.Should().HaveCount(directory.Items.Count); - - List childResponses = [.. response.Children]; - List directoryItems = [.. directory.Items]; - - for (int j = 0; j < childResponses.Count; j++) - { - FileSystemTreeNodeResponse childResponse = childResponses[j]; - FileSystemItem item = directoryItems[j]; - - childResponse.Path.Should().Be(item.Id.Path); - childResponse.Name.Should().Be(item.Name); - childResponse.ItemType.Should().Be(item.Type); - childResponse.IsExpanded.Should().BeFalse(); - childResponse.ChildrenLoaded.Should().BeFalse(); - - if (item is Directory) - childResponse.Children.Should().NotBeNull(); - else - childResponse.Children.Should().BeEmpty(); - } - } - _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements); - } - - [Fact] - public async Task Handle_WhenDirectoryServiceReturnsError_ShouldReturnFailureResult() - { - // Arrange - GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(); - Error error = Error.Failure("DirectoryService.Error", "An error occurred"); - _mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements) - .Returns(error); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeTrue(); - result.FirstError.Should().Be(error); - _mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements); - } - - [Fact] - public async Task Handle_WhenDirectoryServiceReturnsEmptyList_ShouldReturnEmptySuccessResult() - { - // Arrange - GetTreeDirectoriesQuery query = _fixture.Create(); - ErrorOr> emptyList = ErrorOrFactory.From(Enumerable.Empty()); - _mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements) - .Returns(emptyList); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeFalse(); - result.Value.Should().BeEmpty(); - _mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements); - } - - [Fact] - public async Task Handle_WhenCalledWithNestedDirectories_ShouldReturnCorrectlyNestedResponse() - { - // Arrange - GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(true); - IEnumerable nestedDirectories = _directoryFixture.CreateManyNested(2, 2, 2); - - _mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements) - .Returns(ErrorOrFactory.From(nestedDirectories)); - - // Act - ErrorOr> result = await _sut.Handle(query, CancellationToken.None); - - // Assert - result.IsError.Should().BeFalse(); - result.Value.Should().BeAssignableTo>(); - result.Value.Should().HaveCount(2); // top level directories - - List resultList = result.Value.ToList(); - List directoriesList = nestedDirectories.ToList(); - - for (int i = 0; i < resultList.Count; i++) - { - FileSystemTreeNodeResponse response = resultList[i]; - Directory directory = directoriesList[i]; - - response.Path.Should().Be(directory.Id.Path); - response.Name.Should().Be(directory.Name); - response.ItemType.Should().Be(FileSystemItemType.Directory); - response.IsExpanded.Should().BeFalse(); - response.ChildrenLoaded.Should().BeFalse(); - response.Children.Should().HaveCount(directory.Items.Count); - - // check first level of children - for (int j = 0; j < response.Children.Count; j++) - { - FileSystemTreeNodeResponse childResponse = response.Children[j]; - FileSystemItem childItem = directory.Items.ElementAt(j); - - childResponse.Path.Should().Be(childItem.Id.Path); - childResponse.Name.Should().Be(childItem.Name); - childResponse.ItemType.Should().Be(childItem.Type); - childResponse.IsExpanded.Should().BeFalse(); - childResponse.ChildrenLoaded.Should().BeFalse(); - - if (childItem is Directory dir) - { - childResponse.Children.Should().NotBeNull(); - childResponse.Children.Should().HaveCount(dir.Items.Count); - } - else - childResponse.Children.Should().BeEmpty(); - } - } - - result.Value.Any(r => r.Children.Count != 0).Should().BeTrue(); - _mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidatorTests.cs deleted file mode 100644 index e421513d..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetTreeDirectories/GetTreeDirectoriesQueryValidatorTests.cs +++ /dev/null @@ -1,113 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentValidation.TestHelper; -using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; -using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories.Fixtures; -using Lumina.Domain.Common.Errors; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetTreeDirectoriesQueryValidatorTests -{ - private readonly GetTreeDirectoriesQueryValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - public GetTreeDirectoriesQueryValidatorTests() - { - _validator = new GetTreeDirectoriesQueryValidator(); - } - - [Fact] - public void Validate_WhenPathIsNull_ShouldHaveValidationError() - { - // Arrange - GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(); - query = query with { Path = null! }; - - // Act - TestValidationResult result = _validator.TestValidate(query); - - // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); - } - - [Fact] - public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() - { - // Arrange - GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(); - query = query with { Path = string.Empty }; - - // Act - TestValidationResult result = _validator.TestValidate(query); - - // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); - } - - [Fact] - public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() - { - // Arrange - GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(); - query = query with { Path = " " }; - - // Act - TestValidationResult result = _validator.TestValidate(query); - - // Assert - result.ShouldHaveValidationErrorFor(x => x.Path) - .WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description); - } - - [Fact] - public void Validate_WhenPathIsValid_ShouldNotHaveValidationError() - { - // Arrange - GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(); - query = query with { Path = "/valid/path" }; - - // Act - TestValidationResult result = _validator.TestValidate(query); - - // Assert - result.ShouldNotHaveValidationErrorFor(x => x.Path); - } - - [Fact] - public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() - { - // Arrange - GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(); - query = query with { IncludeHiddenElements = true }; - - // Act - TestValidationResult result = _validator.TestValidate(query); - - // Assert - result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); - } - - [Fact] - public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() - { - // Arrange - GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(); - query = query with { IncludeHiddenElements = false }; - - // Act - TestValidationResult result = _validator.TestValidate(query); - - // Assert - result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs deleted file mode 100644 index 7bc15455..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs +++ /dev/null @@ -1,170 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; -using ErrorOr; -using FastEndpoints; -using FluentAssertions; -using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree; -using Lumina.Contracts.Requests.FileSystemManagement.Directories; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectoryTree; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; -using Mediator; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.HttpResults; -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.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Directories; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetDirectoryTreeEndpointTests -{ - private readonly IFixture _fixture; - private readonly ISender _mockSender; - private readonly GetDirectoryTreeEndpoint _sut; - private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; - - /// - /// Initializes a new instance of the class. - /// - public GetDirectoryTreeEndpointTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); - _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses() - { - // Arrange - GetDirectoryTreeRequest request = _fixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - IEnumerable actualResponses = result.Should().BeOfType>>().Subject.Value!; - actualResponses.Should().BeEquivalentTo(expectedResponses); - } - - [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() - { - // Arrange - GetDirectoryTreeRequest request = _fixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("Directory.NotFound", "The requested directory was not found."); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - result.Should().BeOfType(); - ProblemHttpResult problemDetails = (ProblemHttpResult)result; - problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound); - problemDetails.ContentType.Should().Be("application/problem+json"); - problemDetails.ProblemDetails.Should().BeOfType(); - - problemDetails.ProblemDetails.Title.Should().Be("Directory.NotFound"); - problemDetails.ProblemDetails.Detail.Should().Be("The requested directory was not found."); - problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound); - problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); - problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull(); - } - - [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() - { - // Arrange - GetDirectoryTreeRequest request = _fixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - result.Should().BeOfType(); - ProblemHttpResult problemDetails = (ProblemHttpResult)result; - problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); - problemDetails.ContentType.Should().Be("application/problem+json"); - problemDetails.ProblemDetails.Should().BeOfType(); - HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; - validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); - validationProblemDetails.Title.Should().Be("General.Validation"); - validationProblemDetails.Detail.Should().Be("OneOrMoreValidationErrorsOccurred"); - validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); - validationProblemDetails.Errors.Should().ContainSingle() - .Which.Should().BeEquivalentTo(new - { - Key = "Path.Invalid", - Value = new[] { "The provided path is invalid." } - }); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetDirectoryTreeQueryToMediator() - { - // Arrange - GetDirectoryTreeRequest request = _fixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockSender.Received(1).Send( - Arg.Is(q => q.Path == request.Path && q.IncludeFiles == request.IncludeFiles && q.IncludeHiddenElements == request.IncludeHiddenElements), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - GetDirectoryTreeRequest request = _fixture.Create(); - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>>(Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5).AsEnumerable()); - }, callInfo.Arg()))); - - // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs deleted file mode 100644 index 5dfe109e..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs +++ /dev/null @@ -1,170 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; -using ErrorOr; -using FastEndpoints; -using FluentAssertions; -using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories; -using Lumina.Contracts.Requests.FileSystemManagement.Directories; -using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetTreeDirectories; -using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures; -using Mediator; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.HttpResults; -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.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Directories; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetTreeDirectoriesEndpointTests -{ - private readonly IFixture _fixture; - private readonly ISender _mockSender; - private readonly GetTreeDirectoriesEndpoint _sut; - private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; - - /// - /// Initializes a new instance of the class. - /// - public GetTreeDirectoriesEndpointTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - _mockSender = Substitute.For(); - _sut = Factory.Create(_mockSender); - _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses() - { - // Arrange - GetTreeDirectoriesRequest request = _fixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - IEnumerable actualResponses = result.Should().BeOfType>>().Subject.Value!; - actualResponses.Should().BeEquivalentTo(expectedResponses); - } - - [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult() - { - // Arrange - GetTreeDirectoriesRequest request = _fixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("Directory.NotFound", "The requested directory was not found."); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - result.Should().BeOfType(); - ProblemHttpResult problemDetails = (ProblemHttpResult)result; - problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound); - problemDetails.ContentType.Should().Be("application/problem+json"); - problemDetails.ProblemDetails.Should().BeOfType(); - - problemDetails.ProblemDetails.Title.Should().Be("Directory.NotFound"); - problemDetails.ProblemDetails.Detail.Should().Be("The requested directory was not found."); - problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound); - problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); - problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull(); - } - - [Fact] - public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult() - { - // Arrange - GetTreeDirectoriesRequest request = _fixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - result.Should().BeOfType(); - ProblemHttpResult problemDetails = (ProblemHttpResult)result; - problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity); - problemDetails.ContentType.Should().Be("application/problem+json"); - problemDetails.ProblemDetails.Should().BeOfType(); - HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails; - validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity); - validationProblemDetails.Title.Should().Be("General.Validation"); - validationProblemDetails.Detail.Should().Be("OneOrMoreValidationErrorsOccurred"); - validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); - validationProblemDetails.Errors.Should().ContainSingle() - .Which.Should().BeEquivalentTo(new - { - Key = "Path.Invalid", - Value = new[] { "The provided path is invalid." } - }); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetTreeDirectoriesQueryToMediator() - { - // Arrange - GetTreeDirectoriesRequest request = _fixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(ErrorOrFactory.From(Enumerable.Empty())); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockSender.Received(1).Send( - Arg.Is(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - GetTreeDirectoriesRequest request = _fixture.Create(); - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask>>(Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5).AsEnumerable()); - }, callInfo.Arg()))); - - // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } -}