Removes unused file system API endpoints

This commit is contained in:
BinaryAlley committed 2025-01-02 14:56:45 +02:00
1 parent 8c579cd4bd
commit 532322eab2
35 files changed
-3111

No files matched your search

@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="GetDirectoryTreeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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);
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDirectoryTreeEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
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<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(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<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(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<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(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<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_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<Task> 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<Task> 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<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="GetTreeDirectoriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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);
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetTreeDirectoriesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
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<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(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<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(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<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_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<Task> 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<Task> 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<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <c>/directories/get-directory-tree</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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");
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <c>/directories/get-tree-directories</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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");
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetDirectoryTreeRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeRequestMappingTests
{
private readonly IFixture _fixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeRequestMappingTests"/> class.
/// </summary>
public GetDirectoryTreeRequestMappingTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void ToQuery_WhenMappingGetDirectoryTreeRequest_ShouldMapCorrectly()
{
// Arrange
GetDirectoryTreeRequest request = _fixture.Create<GetDirectoryTreeRequest>();
// 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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetTreeDirectoriesRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesRequestMappingTests
{
private readonly IFixture _fixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesRequestMappingTests"/> class.
/// </summary>
public GetTreeDirectoriesRequestMappingTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void ToQuery_WhenMappingGetTreeDirectoriesRequest_ShouldMapCorrectly()
{
// Arrange
GetTreeDirectoriesRequest request = _fixture.Create<GetTreeDirectoriesRequest>();
// Act
GetTreeDirectoriesQuery result = request.ToQuery();
// Assert
result.Should().NotBeNull();
result.Path.Should().Be(request.Path);
result.IncludeHiddenElements.Should().Be(request.IncludeHiddenElements);
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetDirectoryTreeQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeQueryFixture
{
/// <summary>
/// Creates a random valid query to get directory tree.
/// </summary>
/// <param name="includeFiles">Whether to include file system files or not.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query to get directory tree.</returns>
public static GetDirectoryTreeQuery CreateGetDirectoryTreeQuery(bool includeFiles = false, bool includeHiddenElements = false)
{
return new Faker<GetDirectoryTreeQuery>()
.CustomInstantiator(f => new GetDirectoryTreeQuery(
default!,
default,
default
))
.RuleFor(x => x.Path, f => f.System.DirectoryPath())
.RuleFor(x => x.IncludeFiles, f => includeFiles)
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetDirectoryTreeQueryHandler"/> class.
/// </summary>
[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;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeQueryHandlerTests"/> class.
/// </summary>
public GetDirectoryTreeQueryHandlerTests()
{
_mockDriveService = Substitute.For<IDriveService>();
_mockDirectoryService = Substitute.For<IDirectoryService>();
_mockFileService = Substitute.For<IFileService>();
_mockPathService = Substitute.For<IPathService>();
_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<FileSystemItem> drives =
[
WindowsRootItem.Create(drivePath, "C:").Value
];
// Ensure the first path segment matches the drive path
PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
List<PathSegment> otherPathSegments = _pathSegmentFixture.CreateMany(2);
IEnumerable<PathSegment> pathSegments = new[] { firstPathSegment }.Concat(otherPathSegments);
IEnumerable<Directory> subdirectories = _directoryFixture.CreateMany(2);
IEnumerable<File> files = _fileFixture.CreateMany(2);
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments));
_mockPathService.CombinePath(Arg.Is<string>(x => true), Arg.Is<string>(y => true)).Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories));
_mockFileService.GetFiles(Arg.Any<string>(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(files));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().NotBeEmpty();
result.Value.First().Children.Should().NotBeEmpty();
_mockDriveService.Received(1).GetDrives();
_mockPathService.Received(1).ParsePath(query.Path!);
_mockDirectoryService.Received(1).GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements);
_mockFileService.Received(0).GetFiles(Arg.Any<string>(), query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryAndIncludeFiles_ShouldReturnSuccessResult()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(true, true);
// Create a drive that matches what the implementation expects
string drivePath = "C:\\";
IEnumerable<FileSystemItem> drives =
[
WindowsRootItem.Create(drivePath, "C:").Value
];
// Ensure the first path segment matches the drive path
PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
List<PathSegment> otherPathSegments = _pathSegmentFixture.CreateMany(2);
IEnumerable<PathSegment> pathSegments = new[] { firstPathSegment }.Concat(otherPathSegments);
IEnumerable<Directory> subdirectories = _directoryFixture.CreateMany(2);
IEnumerable<File> files = _fileFixture.CreateMany(2);
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments));
_mockPathService.CombinePath(Arg.Is<string>(x => true), Arg.Is<string>(y => true)).Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories));
_mockFileService.GetFiles(Arg.Any<string>(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(files));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().NotBeEmpty();
result.Value.First().Children.Should().NotBeEmpty();
_mockDriveService.Received(1).GetDrives();
_mockPathService.Received(1).ParsePath(query.Path!);
_mockDirectoryService.Received(1).GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements);
_mockFileService.Received(1).GetFiles(Arg.Any<string>(), query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenGetDrivesReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
Error error = Error.Failure("DriveService.Error", "An error occurred");
_mockDriveService.GetDrives().Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockDriveService.Received(1).GetDrives();
}
[Fact]
public async Task Handle_WhenParsePathReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
IEnumerable<FileSystemItem> drives =
[
WindowsRootItem.Create("C:\\", "Local Disk").Value
];
Error error = Error.Failure("PathService.Error", "An error occurred");
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockDriveService.Received(1).GetDrives();
_mockPathService.Received(1).ParsePath(query.Path!);
}
[Fact]
public async Task Handle_WhenCombinePathReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
IEnumerable<FileSystemItem> drives =
[
WindowsRootItem.Create("C:\\", "C:").Value
];
PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
IEnumerable<PathSegment> pathSegments = new[] { firstPathSegment }.Concat(_pathSegmentFixture.CreateMany(2));
Error error = Error.Failure("PathService.Error", "An error occurred");
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments));
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>()).Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockDriveService.Received(1).GetDrives();
_mockPathService.Received(1).ParsePath(query.Path!);
_mockPathService.Received(1).CombinePath(Arg.Any<string>(), Arg.Any<string>());
}
[Fact]
public async Task Handle_WhenGetSubdirectoriesReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
IEnumerable<FileSystemItem> drives =
[
WindowsRootItem.Create("C:\\", "C:").Value
];
PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
IEnumerable<PathSegment> pathSegments = new[] { firstPathSegment }.Concat(_pathSegmentFixture.CreateMany(2));
Error error = Error.Failure("DirectoryService.Error", "An error occurred");
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments));
_mockPathService.CombinePath(Arg.Is<string>(x => true), Arg.Is<string>(y => true)).Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements).Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockDriveService.Received(1).GetDrives();
_mockPathService.Received(1).ParsePath(query.Path!);
_mockDirectoryService.Received(1).GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenGetFilesReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(true);
IEnumerable<FileSystemItem> drives =
[
WindowsRootItem.Create("C:\\", "C:").Value
];
PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
IEnumerable<PathSegment> pathSegments = new[] { firstPathSegment }.Concat(_pathSegmentFixture.CreateMany(2));
IEnumerable<Directory> subdirectories = _directoryFixture.CreateMany(2);
Error error = Error.Failure("FileService.Error", "An error occurred");
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments));
_mockPathService.CombinePath(Arg.Is<string>(x => true), Arg.Is<string>(y => true)).Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories));
_mockFileService.GetFiles(Arg.Any<string>(), query.IncludeHiddenElements).Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockDriveService.Received(1).GetDrives();
_mockPathService.Received(1).ParsePath(query.Path!);
_mockDirectoryService.Received(1).GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements);
_mockFileService.Received(1).GetFiles(Arg.Any<string>(), query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenPathOnlyContainsRoot_ShouldReturnOnlyRootNode()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { Path = "C:" };
IEnumerable<FileSystemItem> drives = [WindowsRootItem.Create("C:\\", "C:").Value];
PathSegment rootSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From((IEnumerable<PathSegment>)[rootSegment]));
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), Arg.Any<bool>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<Directory>()));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(1);
result.Value.First().Name.Should().Be("C:");
result.Value.First().Children.Should().BeEmpty();
}
[Fact]
public async Task Handle_WhenPathHasManySegments_ShouldCreateCorrectTreeStructure()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
IEnumerable<FileSystemItem> drives = [WindowsRootItem.Create("C:\\", "C:").Value];
List<PathSegment> pathSegments =
[
_pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true),
_pathSegmentFixture.CreatePathSegment(name: "Users"),
_pathSegmentFixture.CreatePathSegment(name: "Username"),
_pathSegmentFixture.CreatePathSegment(name: "Documents"),
_pathSegmentFixture.CreatePathSegment(name: "Projects"),
_pathSegmentFixture.CreatePathSegment(name: "MyProject")
];
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From((IEnumerable<PathSegment>)pathSegments));
_mockPathService.Exists(Arg.Any<string>(), Arg.Any<bool>()).Returns(true);
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), Arg.Any<bool>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<Directory>()));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(1);
FileSystemTreeNodeResponse root = result.Value.First();
root.Name.Should().Be("C:");
root.Children.Should().HaveCount(1);
root.Children.First().Name.Should().Be("Users");
root.Children.First().Children.First().Name.Should().Be("Username");
root.Children.First().Children.First().Children.First().Name.Should().Be("Documents");
root.Children.First().Children.First().Children.First().Children.First().Name.Should().Be("Projects");
root.Children.First().Children.First().Children.First().Children.First().Children.First().Name.Should().Be("MyProject");
}
[Fact]
public async Task Handle_WhenPathContainsSpecialCharacters_ShouldHandleCorrectly()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
IEnumerable<FileSystemItem> drives = [WindowsRootItem.Create("C:\\", "C:").Value];
List<PathSegment> pathSegments =
[
_pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true),
_pathSegmentFixture.CreatePathSegment(name: "Program Files"),
_pathSegmentFixture.CreatePathSegment(name: "My Awesome App!"),
_pathSegmentFixture.CreatePathSegment(name: "Data Files")
];
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.Exists(Arg.Any<string>(), Arg.Any<bool>()).Returns(true);
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From((IEnumerable<PathSegment>)pathSegments));
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), Arg.Any<bool>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<Directory>()));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(1);
FileSystemTreeNodeResponse root = result.Value.First();
root.Children.First().Name.Should().Be("Program Files");
root.Children.First().Children.First().Name.Should().Be("My Awesome App!");
}
[Fact]
public async Task Handle_WhenIncludeHiddenElementsIsFalse_ShouldNotIncludeHiddenItems()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(includeHiddenElements: false);
IEnumerable<FileSystemItem> drives = [WindowsRootItem.Create("C:\\", "C:").Value];
PathSegment rootSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From((IEnumerable<PathSegment>)[rootSegment]));
IEnumerable<Directory> visibleDirectories = _directoryFixture.CreateMany(2);
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), false).Returns(ErrorOrFactory.From(visibleDirectories));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.First().Children.Should().HaveCount(2);
_mockDirectoryService.Received(1).GetSubdirectories(Arg.Any<string>(), false);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetDirectoryTreeQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeQueryValidatorTests
{
private readonly GetDirectoryTreeQueryValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeQueryValidatorTests"/> class.
/// </summary>
public GetDirectoryTreeQueryValidatorTests()
{
_validator = new GetDirectoryTreeQueryValidator();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { Path = null! };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { Path = string.Empty };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { Path = " " };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { Path = "/valid/path" };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { IncludeHiddenElements = true };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { IncludeHiddenElements = false };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
[Fact]
public void Validate_WhenIncludeFilesIsTrue_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { IncludeFiles = true };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeFiles);
}
[Fact]
public void Validate_WhenIncludeFilesIsFalse_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { IncludeFiles = false };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeFiles);
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetTreeDirectoriesQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesQueryFixture
{
/// <summary>
/// Creates a random valid query to get tree directories.
/// </summary>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query to get tree directory.</returns>
public static GetTreeDirectoriesQuery CreateGetTreeDirectoryQuery(bool includeHiddenElements = false)
{
return new Faker<GetTreeDirectoriesQuery>()
.CustomInstantiator(f => new GetTreeDirectoriesQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.DirectoryPath())
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetTreeDirectoriesQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesQueryHandlerTests
{
private readonly IFixture _fixture;
private readonly IDirectoryService _mockDirectoryService;
private readonly GetTreeDirectoriesQueryHandler _sut;
private readonly DirectoryFixture _directoryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesQueryHandlerTests"/> class.
/// </summary>
public GetTreeDirectoriesQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockDirectoryService = Substitute.For<IDirectoryService>();
_sut = new GetTreeDirectoriesQueryHandler(_mockDirectoryService);
_directoryFixture = new DirectoryFixture();
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryWithoutFilesIncluded_ShouldReturnSuccessResult()
{
// Arrange
GetTreeDirectoriesQuery getDirectoriesQuery = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(false);
IEnumerable<Directory> directories = _directoryFixture.CreateMany();
_mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(directories));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
result.Value.Should().HaveCount(directories.Count());
List<FileSystemTreeNodeResponse> resultList = result.Value.ToList();
List<Directory> 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<Directory> directories = _directoryFixture.CreateManyNested();
_mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(directories));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
result.Value.Should().HaveCount(directories.Count());
List<FileSystemTreeNodeResponse> resultList = result.Value.ToList();
List<Directory> 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<FileSystemTreeNodeResponse> childResponses = [.. response.Children];
List<FileSystemItem> 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<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenDirectoryServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
GetTreeDirectoriesQuery query = _fixture.Create<GetTreeDirectoriesQuery>();
ErrorOr<IEnumerable<Directory>> emptyList = ErrorOrFactory.From(Enumerable.Empty<Directory>());
_mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements)
.Returns(emptyList);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEmpty();
_mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenCalledWithNestedDirectories_ShouldReturnCorrectlyNestedResponse()
{
// Arrange
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(true);
IEnumerable<Directory> nestedDirectories = _directoryFixture.CreateManyNested(2, 2, 2);
_mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(nestedDirectories));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
result.Value.Should().HaveCount(2); // top level directories
List<FileSystemTreeNodeResponse> resultList = result.Value.ToList();
List<Directory> 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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetTreeDirectoriesQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesQueryValidatorTests
{
private readonly GetTreeDirectoriesQueryValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesQueryValidatorTests"/> class.
/// </summary>
public GetTreeDirectoriesQueryValidatorTests()
{
_validator = new GetTreeDirectoriesQueryValidator();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery();
query = query with { Path = null! };
// Act
TestValidationResult<GetTreeDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery();
query = query with { Path = string.Empty };
// Act
TestValidationResult<GetTreeDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery();
query = query with { Path = " " };
// Act
TestValidationResult<GetTreeDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery();
query = query with { Path = "/valid/path" };
// Act
TestValidationResult<GetTreeDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
{
// Arrange
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery();
query = query with { IncludeHiddenElements = true };
// Act
TestValidationResult<GetTreeDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
{
// Arrange
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery();
query = query with { IncludeHiddenElements = false };
// Act
TestValidationResult<GetTreeDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetDirectoryTreeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeEndpointTests
{
private readonly IFixture _fixture;
private readonly ISender _mockSender;
private readonly GetDirectoryTreeEndpoint _sut;
private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeEndpointTests"/> class.
/// </summary>
public GetDirectoryTreeEndpointTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockSender = Substitute.For<ISender>();
_sut = Factory.Create<GetDirectoryTreeEndpoint>(_mockSender);
_fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture();
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses()
{
// Arrange
GetDirectoryTreeRequest request = _fixture.Create<GetDirectoryTreeRequest>();
CancellationToken cancellationToken = CancellationToken.None;
List<FileSystemTreeNodeResponse> expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5);
_mockSender.Send(Arg.Any<GetDirectoryTreeQuery>(), Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
IEnumerable<FileSystemTreeNodeResponse> actualResponses = result.Should().BeOfType<Ok<IEnumerable<FileSystemTreeNodeResponse>>>().Subject.Value!;
actualResponses.Should().BeEquivalentTo(expectedResponses);
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetDirectoryTreeRequest request = _fixture.Create<GetDirectoryTreeRequest>();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("Directory.NotFound", "The requested directory was not found.");
_mockSender.Send(Arg.Any<GetDirectoryTreeQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
result.Should().BeOfType<ProblemHttpResult>();
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound);
problemDetails.ContentType.Should().Be("application/problem+json");
problemDetails.ProblemDetails.Should().BeOfType<Microsoft.AspNetCore.Mvc.ProblemDetails>();
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<GetDirectoryTreeRequest>();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid.");
_mockSender.Send(Arg.Any<GetDirectoryTreeQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
result.Should().BeOfType<ProblemHttpResult>();
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails.ContentType.Should().Be("application/problem+json");
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails;
validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity);
validationProblemDetails.Title.Should().Be("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<GetDirectoryTreeRequest>();
CancellationToken cancellationToken = CancellationToken.None;
_mockSender.Send(Arg.Any<GetDirectoryTreeQuery>(), Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<FileSystemTreeNodeResponse>()));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockSender.Received(1).Send(
Arg.Is<GetDirectoryTreeQuery>(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<GetDirectoryTreeRequest>();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockSender.Send(Arg.Any<GetDirectoryTreeQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>(Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5).AsEnumerable());
}, callInfo.Arg<CancellationToken>())));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="GetTreeDirectoriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesEndpointTests
{
private readonly IFixture _fixture;
private readonly ISender _mockSender;
private readonly GetTreeDirectoriesEndpoint _sut;
private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesEndpointTests"/> class.
/// </summary>
public GetTreeDirectoriesEndpointTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockSender = Substitute.For<ISender>();
_sut = Factory.Create<GetTreeDirectoriesEndpoint>(_mockSender);
_fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture();
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses()
{
// Arrange
GetTreeDirectoriesRequest request = _fixture.Create<GetTreeDirectoriesRequest>();
CancellationToken cancellationToken = CancellationToken.None;
List<FileSystemTreeNodeResponse> expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5);
_mockSender.Send(Arg.Any<GetTreeDirectoriesQuery>(), Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
IEnumerable<FileSystemTreeNodeResponse> actualResponses = result.Should().BeOfType<Ok<IEnumerable<FileSystemTreeNodeResponse>>>().Subject.Value!;
actualResponses.Should().BeEquivalentTo(expectedResponses);
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetTreeDirectoriesRequest request = _fixture.Create<GetTreeDirectoriesRequest>();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("Directory.NotFound", "The requested directory was not found.");
_mockSender.Send(Arg.Any<GetTreeDirectoriesQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
result.Should().BeOfType<ProblemHttpResult>();
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound);
problemDetails.ContentType.Should().Be("application/problem+json");
problemDetails.ProblemDetails.Should().BeOfType<Microsoft.AspNetCore.Mvc.ProblemDetails>();
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<GetTreeDirectoriesRequest>();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid.");
_mockSender.Send(Arg.Any<GetTreeDirectoriesQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
result.Should().BeOfType<ProblemHttpResult>();
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails.ContentType.Should().Be("application/problem+json");
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails;
validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity);
validationProblemDetails.Title.Should().Be("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<GetTreeDirectoriesRequest>();
CancellationToken cancellationToken = CancellationToken.None;
_mockSender.Send(Arg.Any<GetTreeDirectoriesQuery>(), Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<FileSystemTreeNodeResponse>()));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockSender.Received(1).Send(
Arg.Is<GetTreeDirectoriesQuery>(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetTreeDirectoriesRequest request = _fixture.Create<GetTreeDirectoriesRequest>();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockSender.Send(Arg.Any<GetTreeDirectoriesQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>(Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5).AsEnumerable());
}, callInfo.Arg<CancellationToken>())));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}