diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index e2f35781..dc8e0701 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -37,6 +37,8 @@ public static class PresentationApiLayerServices // add services to the container services.AddControllers().AddJsonOptions(options => { + options.JsonSerializerOptions.MaxDepth = 256; + options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); options.JsonSerializerOptions.Converters.Add(new OptionalJsonConverterFactory()); }); diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs index c9cbc22b..a615096a 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs @@ -49,7 +49,7 @@ public class DirectoriesController : ApiController [FromQuery] bool includeFiles, [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) { ErrorOr> result = await _mediator.Send(new GetDirectoryTreeQuery(path, includeFiles, includeHiddenElements), cancellationToken).ConfigureAwait(false); - if (!result.IsError && result.Value is not null) + if (!result.IsError) { foreach (FileSystemTreeNodeResponse treeNode in result.Value) { @@ -71,7 +71,7 @@ public class DirectoriesController : ApiController [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) { ErrorOr> result = await _mediator.Send(new GetTreeDirectoriesQuery(path,includeHiddenElements), cancellationToken).ConfigureAwait(false); - if (!result.IsError && result.Value is not null) + if (!result.IsError) { foreach (FileSystemTreeNodeResponse directory in result.Value) { @@ -93,7 +93,7 @@ public class DirectoriesController : ApiController [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) { ErrorOr> result = await _mediator.Send(new GetDirectoriesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false); - if (!result.IsError && result.Value is not null) + if (!result.IsError) { foreach (DirectoryResponse directory in result.Value) { diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs index f91c83c4..bfac0867 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs @@ -48,7 +48,7 @@ public class FilesController : ApiController [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) { ErrorOr> result = await _mediator.Send(new GetTreeFilesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false); - if (!result.IsError && result.Value is not null) + if (!result.IsError) { foreach (FileSystemTreeNodeResponse file in result.Value) { @@ -70,7 +70,7 @@ public class FilesController : ApiController [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) { ErrorOr> result = await _mediator.Send(new GetFilesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false); - if (!result.IsError && result.Value is not null) + if (!result.IsError) { foreach (FileResponse file in result.Value) { diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index c6d64a92..78281cec 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -54,4 +54,4 @@ public class Program await app.RunAsync().ConfigureAwait(false); } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 12316dae..cc0331ff 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -32,7 +32,12 @@ public static class PresentationWebLayerServices public static IServiceCollection AddPresentationWebLayerServices(this IServiceCollection services) { services.AddControllersWithViews(options => options.Filters.Add(typeof(ApiExceptionFilter))) - .AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter())); + .AddJsonOptions(options => + { + options.JsonSerializerOptions.MaxDepth = 256; + options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures + options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); + }); // scan the current assembly for validators and register them to the DI container services.AddValidatorsFromAssemblyContaining(ServiceLifetime.Singleton); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs index 75b1d169..7d775853 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs @@ -8,6 +8,7 @@ using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.E using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; @@ -18,6 +19,7 @@ namespace Lumina.Presentation.Api.IntegrationTests.Common.Converters; /// /// Custom JSON converter for the class. /// +[ExcludeFromCodeCoverage] public class BookJsonConverter : JsonConverter { #region ===================================================================== METHODS =================================================================================== diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs index 755a2419..34078ed4 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.DataAccess.Core.UoW; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; @@ -8,6 +8,8 @@ using Microsoft.Extensions.DependencyInjection; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; #endregion namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; @@ -42,10 +44,13 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable { builder.ConfigureServices(services => { + // remove existing DbContext configuration ServiceDescriptor? descriptor = services.SingleOrDefault(serviceDescriptor => serviceDescriptor.ServiceType == typeof(DbContextOptions)); if (descriptor is not null) services.Remove(descriptor); + // add SQLite DbContext configuration services.AddDbContext(options => options.UseSqlite(_connection)); + // build service provider and ensure database is created ServiceProvider servicePreovider = services.BuildServiceProvider(); using (IServiceScope scope = servicePreovider.CreateScope()) { @@ -65,4 +70,4 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable base.Dispose(); } #endregion -} \ No newline at end of file +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/DirectoriesControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/DirectoriesControllerTests.cs new file mode 100644 index 00000000..77df7b0b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/DirectoriesControllerTests.cs @@ -0,0 +1,645 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +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.Controllers.FileManagement; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DirectoriesControllerTests : IClassFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public DirectoriesControllerTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task GetDirectoryTree_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); + + List treeNodes = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + FileSystemTreeNodeResponse? node = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (node is not null) + treeNodes.Add(node); + } + } + } + treeNodes.Should().NotBeNull(); + treeNodes!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it! + pathSegments = new string[] { "/" }.Concat(pathSegments).ToArray(); + // 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(Path.DirectorySeparatorChar)) + expectedSegment += Path.DirectorySeparatorChar; + + node.Name.Should().Be(expectedSegment); + + string expectedPath = string.Join(Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); + if (expectedPath.StartsWith("//")) + expectedPath = expectedPath.Substring(1); + if (!expectedPath.EndsWith(Path.DirectorySeparatorChar)) + expectedPath += 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.First(); + ValidateNode(rootNode, 0); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task GetDirectoryTree_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); + + List treeNodes = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + FileSystemTreeNodeResponse? node = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (node is not null) + treeNodes.Add(node); + } + } + } + treeNodes.Should().NotBeNull(); + treeNodes!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it! + pathSegments = new string[] { "/" }.Concat(pathSegments).ToArray(); + + // 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(Path.DirectorySeparatorChar)) + expectedSegment += Path.DirectorySeparatorChar; + + node.Name.Should().Be(expectedSegment); + + string expectedPath = string.Join(Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); + if (!expectedPath.EndsWith(Path.DirectorySeparatorChar)) + expectedPath += Path.DirectorySeparatorChar; + if (expectedPath.StartsWith("//")) + expectedPath = expectedPath.Substring(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_isLinux ? "." : string.Empty) + "TestFile_1.txt", "TestFile_2.txt"); + } + } + } + } + FileSystemTreeNodeResponse rootNode = treeNodes.First(); + ValidateNode(rootNode, 0); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task GetDirectoryTree_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); + + List treeNodes = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + FileSystemTreeNodeResponse? node = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (node is not null) + treeNodes.Add(node); + } + } + } + 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(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it! + pathSegments = new string[] { "/" }.Concat(pathSegments).ToArray(); + + // 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(Path.DirectorySeparatorChar)) + expectedSegment += Path.DirectorySeparatorChar; + + node.Name.Should().Be(expectedSegment); + + string expectedPath = string.Join(Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); + if (!expectedPath.EndsWith(Path.DirectorySeparatorChar)) + expectedPath += Path.DirectorySeparatorChar; + if (expectedPath.StartsWith("//")) + expectedPath = expectedPath.Substring(1); + node.Path.Should().EndWith(expectedPath); + + node.Children.Should().NotBeNull(); + foreach (FileSystemTreeNodeResponse childNode in node.Children) + ValidateNode(childNode, depth + 1); + } + FileSystemTreeNodeResponse rootNode = treeNodes.First(); + ValidateNode(rootNode, 0); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task GetDirectoryTree_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); + + List treeNodes = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + FileSystemTreeNodeResponse? node = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (node is not null) + treeNodes.Add(node); + } + } + } + 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(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it! + pathSegments = new string[] { "/" }.Concat(pathSegments).ToArray(); + + // 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(Path.DirectorySeparatorChar)) + expectedSegment += Path.DirectorySeparatorChar; + + node.Name.Should().Be(expectedSegment); + + string expectedPath = string.Join(Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1)); + if (!expectedPath.EndsWith(Path.DirectorySeparatorChar)) + expectedPath += Path.DirectorySeparatorChar; + if (expectedPath.StartsWith("//")) + expectedPath = expectedPath.Substring(1); + node.Path.Should().EndWith(expectedPath); + + node.Children.Should().NotBeNull(); + foreach (FileSystemTreeNodeResponse childNode in node.Children) + ValidateNode(childNode, depth + 1); + } + FileSystemTreeNodeResponse rootNode = treeNodes.First(); + ValidateNode(rootNode, 0); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task GetTreeDirectories_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnTreeDirectoriesWithoutHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = Path.GetDirectoryName(testPath) ?? testPath; + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + List treeNodes = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + FileSystemTreeNodeResponse? node = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (node is not null) + treeNodes.Add(node); + } + } + } + treeNodes.Should().NotBeNull(); + treeNodes!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + + + FileSystemTreeNodeResponse firstNode = treeNodes.First(); + firstNode.Name.Should().Be("NestedDirectory_3"); + firstNode.Path.Should().Be(Path.Combine(testPath, "NestedDirectory_3" + 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 GetTreeDirectories_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoTreeDirectories() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = Path.GetDirectoryName(testPath) ?? testPath; + testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + List treeNodes = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + FileSystemTreeNodeResponse? node = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (node is not null) + treeNodes.Add(node); + } + } + } + treeNodes.Should().NotBeNull(); + treeNodes!.Should().BeEmpty(); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task GetTreeDirectories_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnTreeDirectoriesWithHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = Path.GetDirectoryName(testPath) ?? testPath; + testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + bool includeHiddenElements = true; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + List treeNodes = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + FileSystemTreeNodeResponse? node = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (node is not null) + treeNodes.Add(node); + } + } + } + treeNodes.Should().NotBeNull(); + treeNodes!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + + + FileSystemTreeNodeResponse firstNode = treeNodes.First(); + firstNode.Name.Should().Be((s_isLinux ? "." : string.Empty) + "NestedDirectory_2"); + firstNode.Path.Should().Be(Path.Combine(testPath, (s_isLinux ? "." : string.Empty) + "NestedDirectory_2" + 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 GetDirectories_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnDirectoriesWithoutHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = Path.GetDirectoryName(testPath) ?? testPath; + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + List directories = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + DirectoryResponse? directory = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (directory is not null) + directories.Add(directory); + } + } + } + directories.Should().NotBeNull(); + directories!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + + + DirectoryResponse firstDirectory = directories.First(); + firstDirectory.Name.Should().Be("NestedDirectory_3"); + firstDirectory.Path.Should().Be(Path.Combine(testPath, "NestedDirectory_3" + Path.DirectorySeparatorChar)); + directories.Count.Should().Be(1); // only directories + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task GetDirectories_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoDirectories() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = Path.GetDirectoryName(testPath) ?? testPath; + testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + List directories = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + DirectoryResponse? directory = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (directory is not null) + directories.Add(directory); + } + } + } + directories.Should().NotBeNull(); + directories!.Should().BeEmpty(); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task GetDirectories_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnDirectoriesWithHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = Path.GetDirectoryName(testPath) ?? testPath; + testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + bool includeHiddenElements = true; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + List directories = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + DirectoryResponse? directory = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (directory is not null) + directories.Add(directory); + } + } + } + directories.Should().NotBeNull(); + directories!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + + + DirectoryResponse firstDirectory = directories.First(); + firstDirectory.Name.Should().Be((s_isLinux ? "." : string.Empty) + "NestedDirectory_2"); + firstDirectory.Path.Should().Be(Path.Combine(testPath, (s_isLinux ? "." : string.Empty) + "NestedDirectory_2" + Path.DirectorySeparatorChar)); + directories.Count.Should().Be(1); // only directories + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + #endregion +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/DrivesControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/DrivesControllerTests.cs new file mode 100644 index 00000000..9ea1891d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/DrivesControllerTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +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.Controllers.FileManagement; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DrivesControllerTests : IClassFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public DrivesControllerTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + + [Fact] + public async Task GetDrives_WhenCalled_ShouldReturnDrives() + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/drives/get-drives"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + List drives = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + FileSystemTreeNodeResponse? drive = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (drive is not null) + drives.Add(drive); + } + } + } + drives.Should().NotBeNull(); + drives.Should().NotBeEmpty(); + + FileSystemTreeNodeResponse firstDrive = drives.First(); + firstDrive.Name.Should().Be(s_isLinux ? "/" : "C:\\"); + firstDrive.Path.Should().Be(s_isLinux ? "/" : "C:\\"); + firstDrive.ItemType.Should().Be(FileSystemItemType.Root); + drives.Count.Should().BeGreaterThanOrEqualTo(1); + } + #endregion +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs new file mode 100644 index 00000000..c1c43cf5 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemControllerTests : IClassFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public FileSystemControllerTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task GetType_WhenCalled_ShouldReturnOkResultWithFileSystemTypeResponse() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1.0/file-system/get-type"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + FileSystemTypeResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.PlatformType.Should().BeOneOf(PlatformType.Unix, PlatformType.Windows); + } + + [Fact] + public async Task GetType_WhenCalledMultipleTimes_ShouldReturnConsistentResults() + { + // Act + HttpResponseMessage response1 = await _client.GetAsync("/api/v1.0/file-system/get-type"); + HttpResponseMessage response2 = await _client.GetAsync("/api/v1.0/file-system/get-type"); + + // Assert + response1.StatusCode.Should().Be(HttpStatusCode.OK); + response2.StatusCode.Should().Be(HttpStatusCode.OK); + + string content1 = await response1.Content.ReadAsStringAsync(); + string content2 = await response2.Content.ReadAsStringAsync(); + + FileSystemTypeResponse? result1 = JsonSerializer.Deserialize(content1, _jsonOptions); + FileSystemTypeResponse? result2 = JsonSerializer.Deserialize(content2, _jsonOptions); + + result1.Should().NotBeNull(); + result2.Should().NotBeNull(); + result1.Should().BeEquivalentTo(result2); + } + + [Fact] + public async Task GetType_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act + Func act = async () => await _client.GetAsync("/api/v1.0/file-system/get-type", cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + #endregion +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/FilesControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/FilesControllerTests.cs new file mode 100644 index 00000000..0011b252 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/FilesControllerTests.cs @@ -0,0 +1,335 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +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.Controllers.FileManagement; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FilesControllerTests : IClassFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public FilesControllerTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task GetTreeFiles_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnTreeFilesWithoutHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = Path.GetDirectoryName(testPath) ?? testPath; + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + List files = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + FileSystemTreeNodeResponse? file = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (file is not null) + files.Add(file); + } + } + } + files.Should().NotBeNull(); + files!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + + + FileSystemTreeNodeResponse firstDirectory = files.First(); + firstDirectory.Name.Should().Be("TestFile_2.txt"); + firstDirectory.Path.Should().Be(Path.Combine(testPath, "TestFile_2.txt")); + files.Count.Should().Be(1); // only files + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task GetTreeFiles_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoTreeFiles() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = Path.GetDirectoryName(testPath) ?? testPath; + testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + List files = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + FileSystemTreeNodeResponse? file = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (file is not null) + files.Add(file); + } + } + } + files.Should().NotBeNull(); + FileSystemTreeNodeResponse firstDirectory = files.First(); + firstDirectory.Name.Should().Be("TestFile_2.txt"); + firstDirectory.Path.Should().Be(Path.Combine(testPath, "TestFile_2.txt")); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task GetTreeFiles_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnTreeFilesWithHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = Path.GetDirectoryName(testPath) ?? testPath; + testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + bool includeHiddenElements = true; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + List files = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + FileSystemTreeNodeResponse? file = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (file is not null) + files.Add(file); + } + } + } + files.Should().NotBeNull(); + files!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + + FileSystemTreeNodeResponse firstDirectory = files.First(); + firstDirectory.Name.Should().Be((s_isLinux ? "." : string.Empty) + "TestFile_1.txt"); + firstDirectory.Path.Should().Be(Path.Combine(testPath, (s_isLinux ? "." : string.Empty) + "TestFile_1.txt")); + FileSystemTreeNodeResponse secondDirectory = files.Last(); + secondDirectory.Name.Should().Be("TestFile_2.txt"); + secondDirectory.Path.Should().Be(Path.Combine(testPath, "TestFile_2.txt")); + files.Count.Should().Be(2); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task GetFiles_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnFilesWithoutHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = Path.GetDirectoryName(testPath) ?? testPath; + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + List files = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + FileResponse? file = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (file is not null) + files.Add(file); + } + } + } + files.Should().NotBeNull(); + files!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + + + FileResponse firstDirectory = files.First(); + firstDirectory.Name.Should().Be("TestFile_2.txt"); + firstDirectory.Path.Should().Be(Path.Combine(testPath, "TestFile_2.txt")); + files.Count.Should().Be(1); // only files + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task GetFiles_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoFiles() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = Path.GetDirectoryName(testPath) ?? testPath; + testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + bool includeHiddenElements = false; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + List files = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + FileResponse? file = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (file is not null) + files.Add(file); + } + } + } + files.Should().NotBeNull(); + FileResponse firstDirectory = files.First(); + firstDirectory.Name.Should().Be("TestFile_2.txt"); + firstDirectory.Path.Should().Be(Path.Combine(testPath, "TestFile_2.txt")); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + + [Fact] + public async Task GetFiles_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnFilesWithHiddenElements() + { + // Arrange + FileSystemStructureFixture fileSystemFixture = new(); + string testPath = fileSystemFixture.CreateFileSystemStructure(); + testPath = Path.GetDirectoryName(testPath) ?? testPath; + testPath = Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child + bool includeHiddenElements = true; + try + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + List files = []; + + using (Stream stream = await response.Content.ReadAsStreamAsync()) + { + using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream)) + { + foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray()) + { + FileResponse? file = JsonSerializer.Deserialize(element.GetRawText(), _jsonOptions); + if (file is not null) + files.Add(file); + } + } + } + files.Should().NotBeNull(); + files!.Should().NotBeEmpty(); + + string[] pathSegments = testPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + + FileResponse firstDirectory = files.First(); + firstDirectory.Name.Should().Be( (s_isLinux ? "." : string.Empty) + "TestFile_1.txt"); + firstDirectory.Path.Should().Be(Path.Combine(testPath, (s_isLinux ? "." : string.Empty) + "TestFile_1.txt")); + FileResponse secondDirectory = files.Last(); + secondDirectory.Name.Should().Be("TestFile_2.txt"); + secondDirectory.Path.Should().Be(Path.Combine(testPath, "TestFile_2.txt")); + files.Count.Should().Be(2); + } + finally + { + fileSystemFixture.CleanupFileSystemStructure(); + } + } + #endregion +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/FileSystemStructureFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/FileSystemStructureFixture.cs new file mode 100644 index 00000000..7dff3a76 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/FileSystemStructureFixture.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures; + +/// +/// Fixture class for creating and managing a file system structure for integration testing purposes. +/// +[ExcludeFromCodeCoverage] +public class FileSystemStructureFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly string _rootPath; + private readonly Faker _faker = new(); + #endregion + + #region ===================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public FileSystemStructureFixture() + { + _rootPath = Path.Combine(AppContext.BaseDirectory, "TestFileSystemStructure_" + Guid.NewGuid()); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + + /// + /// Creates a file system structure with three nested directories, each containing two text files. + /// Makes the second nested directory and the first file in each directory hidden. + /// + /// The path to the root directory of the created file system structure. + public string CreateFileSystemStructure() + { + // create the root directory + Directory.CreateDirectory(_rootPath); + string currentPath = _rootPath; + for (int i = 1; i <= 3; i++) + { + // create a nested subdirectory + currentPath = Path.Combine(currentPath, $"NestedDirectory_{i}"); + Directory.CreateDirectory(currentPath); + + // create two text files in the current directory + for (int j = 1; j <= 2; j++) + { + string filePath = Path.Combine(currentPath, $"TestFile_{j}.txt"); + File.WriteAllText(filePath, _faker.Lorem.Paragraph()); + // make the first file in each directory hidden + if (j == 1) + SetHidden(filePath); + } + // make the second nested directory hidden + if (i == 2) + currentPath = SetHidden(currentPath); + } + return currentPath; + } + + /// + /// Sets the hidden attribute for a file or directory. + /// + /// The path to the file or directory. + private static string SetHidden(string path) + { + if (OperatingSystem.IsWindows()) + File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden); + else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) + { + // On Unix-like systems, rename the file/directory to start with a dot + string directory = Path.GetDirectoryName(path)!; + string name = Path.GetFileName(path); + string newPath = Path.Combine(directory, "." + name); + if (Directory.Exists(path)) + Directory.Move(path, newPath); + else if (File.Exists(path)) + File.Move(path, newPath); + path = newPath; + } + return path; + } + + /// + /// Deletes the file system structure created for testing purposes. + /// + public void CleanupFileSystemStructure() + { + if (Directory.Exists(_rootPath)) + Directory.Delete(_rootPath, recursive: true); + } + #endregion +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs new file mode 100644 index 00000000..70d1b3f1 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemTreeNodeResponseFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker = new(); + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a single with a nested structure. + /// + /// The current depth in the tree structure. Default is 0 (root level). + /// The maximum depth of the tree structure. Default is 2. + /// The maximum number of children for each node. Default is 3. + /// A with a nested structure. + public FileSystemTreeNodeResponse Create(int currentDepth = 0, int maxDepth = 2, int maxChildren = 3) + { + FileSystemTreeNodeResponse response = new() + { + Path = _faker.System.FilePath(), + Name = _faker.System.FileName(), + ItemType = FileSystemItemType.Directory, + IsExpanded = _faker.Random.Bool(), + ChildrenLoaded = true, + Children = [] + }; + if (currentDepth < maxDepth) + { + int childCount = _faker.Random.Int(1, maxChildren); + for (int i = 0; i < childCount; i++) + response.Children.Add(Create(currentDepth + 1, maxDepth, maxChildren)); + } + return response; + } + + /// + /// Creates a list of objects, each with a nested structure. + /// + /// The number of root-level nodes to create. Default is 2. + /// The maximum depth of the tree structure for each root node. Default is 2. + /// The maximum number of children for each node. Default is 3. + /// A list of objects with nested structures. + public List CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3) + { + return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList(); + } + #endregion +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/TestImageFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/TestImageFixture.cs new file mode 100644 index 00000000..a6b64320 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/Fixtures/TestImageFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats.Jpeg; +using SixLabors.ImageSharp.PixelFormats; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures; + +/// +/// Fixture class for creating and managing a test image for integration testing purposes. +/// +[ExcludeFromCodeCoverage] +public class TestImageFixture : IDisposable +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets the path of the created test image. + /// + public string ImagePath { get; } + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public TestImageFixture() + { + ImagePath = Path.Combine(Path.GetTempPath(), $"TestImage_{Guid.NewGuid()}.jpg"); + CreateTestImage(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a test image file. + /// + private void CreateTestImage() + { + using (Image image = new Image(100, 100)) + image.Save(ImagePath, new JpegEncoder()); + } + + /// + /// Disposes the fixture, ensuring the test image is deleted. + /// + public void Dispose() + { + if (File.Exists(ImagePath)) + File.Delete(ImagePath); + } + #endregion +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/PathControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/PathControllerTests.cs new file mode 100644 index 00000000..119d9fb6 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/PathControllerTests.cs @@ -0,0 +1,640 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Presentation.Api.Core.Controllers.FileManagement; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +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.Controllers.FileManagement; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PathControllerTests : IClassFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public PathControllerTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task GetPathRoot_WhenCalledWithValidPath_ShouldReturnOkResultWithPathSegmentResponse() + { + // Arrange + string testPath = System.IO.Path.GetTempPath(); + string encodedPath = Uri.EscapeDataString(testPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/get-path-root?path={encodedPath}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathSegmentResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Path.Should().NotBeNullOrEmpty(); + } + + [Fact] + public async Task GetPathRoot_WhenCalledWithInvalidPath_ShouldReturnProblemDetails() + { + // Arrange + string invalidPath = "invalid:path"; + string encodedPath = Uri.EscapeDataString(invalidPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/get-path-root?path={encodedPath}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + string content = await response.Content.ReadAsStringAsync(); + ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + } + + [Fact] + public async Task GetPathRoot_WhenCalledWithEmptyPath_ShouldReturnBadRequestWithValidationError() + { + // Arrange + string emptyPath = ""; + string encodedPath = Uri.EscapeDataString(emptyPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/get-path-root?path={encodedPath}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + string content = await response.Content.ReadAsStringAsync(); + ValidationProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!.Title.Should().Be("One or more validation errors occurred."); + problemDetails.Errors["General.Validation"].Should().BeEquivalentTo("PathCannotBeEmpty"); + } + + [Fact] + public async Task GetPathRoot_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + string testPath = System.IO.Path.GetTempPath(); + string encodedPath = Uri.EscapeDataString(testPath); + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act + Func act = async () => await _client.GetAsync($"/api/v1.0/path/get-path-root?path={encodedPath}", cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task GetPathRoot_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string testPath = System.IO.Path.GetTempPath(); + string encodedPath = Uri.EscapeDataString(testPath); + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1.0/path/get-path-root?path={encodedPath}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task GetPathSeparator_WhenCalled_ShouldReturnOkResultWithPathSeparatorResponse() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1.0/path/get-path-separator"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathSeparatorResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Separator.Should().BeOneOf("/", "\\"); + } + + [Fact] + public async Task GetPathSeparator_WhenCalledMultipleTimes_ShouldReturnConsistentResults() + { + // Act + HttpResponseMessage response1 = await _client.GetAsync("/api/v1.0/path/get-path-separator"); + HttpResponseMessage response2 = await _client.GetAsync("/api/v1.0/path/get-path-separator"); + + // Assert + response1.StatusCode.Should().Be(HttpStatusCode.OK); + response2.StatusCode.Should().Be(HttpStatusCode.OK); + + string content1 = await response1.Content.ReadAsStringAsync(); + string content2 = await response2.Content.ReadAsStringAsync(); + + PathSeparatorResponse? result1 = JsonSerializer.Deserialize(content1, _jsonOptions); + PathSeparatorResponse? result2 = JsonSerializer.Deserialize(content2, _jsonOptions); + + result1.Should().NotBeNull(); + result2.Should().NotBeNull(); + result1.Should().BeEquivalentTo(result2); + } + + [Fact] + public async Task GetPathSeparator_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act + Func act = async () => await _client.GetAsync("/api/v1.0/path/get-path-separator", cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task GetPathSeparator_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync("/api/v1.0/path/get-path-separator", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task GetPathParent_WhenCalledWithValidPath_ShouldReturnOkResultWithPathSegmentResponses() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory", "testFile.txt"); + string encodedPath = Uri.EscapeDataString(testPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/get-path-parent?path={encodedPath}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + IEnumerable? result = JsonSerializer.Deserialize>(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Should().NotBeEmpty(); + + List hierarchy = []; + string path = System.IO.Path.GetDirectoryName(testPath)!; + while (!string.IsNullOrEmpty(path)) + { + string segment = s_isLinux && path == Path.DirectorySeparatorChar.ToString() ? path : System.IO.Path.GetFileName(path); + if (string.IsNullOrEmpty(segment)) + { + hierarchy.Add(System.IO.Path.GetPathRoot(path)!.TrimEnd(System.IO.Path.DirectorySeparatorChar)); + break; + } + hierarchy.Add(segment); + path = System.IO.Path.GetDirectoryName(path)!; + } + hierarchy.Reverse(); + + result!.Select(r => r.Path).Should().BeEquivalentTo(hierarchy, options => options.WithStrictOrdering()); + } + + [Fact] + public async Task GetPathParent_WhenCalledWithRootPath_ShouldReturnOkResultWithEmptyList() + { + // Arrange + string rootPath = System.IO.Path.GetPathRoot(System.IO.Path.GetTempPath())!; + string encodedPath = Uri.EscapeDataString(rootPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/get-path-parent?path={encodedPath}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + string content = await response.Content.ReadAsStringAsync(); + ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!.Title.Should().Be("Failure"); + JsonElement jsonElement = (JsonElement)problemDetails!.Extensions["errors"]!; + string?[] errors = jsonElement.EnumerateArray() + .Select(element => element.GetString()) + .ToArray(); + errors.Should().BeEquivalentTo(["CannotNavigateUp"]); + + } + + [Fact] + public async Task GetPathParent_WhenCalledWithInvalidPath_ShouldReturnBadRequest() + { + // Arrange + string invalidPath = "invalid:path"; + string encodedPath = Uri.EscapeDataString(invalidPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/get-path-parent?path={encodedPath}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + string content = await response.Content.ReadAsStringAsync(); + ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + } + + [Fact] + public async Task GetPathParent_WhenCalledWithEmptyPath_ShouldReturnBadRequestWithValidationError() + { + // Arrange + string emptyPath = ""; + string encodedPath = Uri.EscapeDataString(emptyPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/get-path-parent?path={encodedPath}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + string content = await response.Content.ReadAsStringAsync(); + ValidationProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!.Title.Should().Be("One or more validation errors occurred."); + problemDetails.Errors["General.Validation"].Should().BeEquivalentTo("PathCannotBeEmpty"); + } + + [Fact] + public async Task GetPathParent_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act + Func act = async () => await _client.GetAsync($"/api/v1.0/path/get-path-parent?path={encodedPath}", cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task GetPathParent_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1.0/path/get-path-parent?path={encodedPath}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task CombinePath_WhenCalledWithValidPaths_ShouldReturnOkResultWithCombinedPath() + { + // Arrange + string originalPath = System.IO.Path.GetTempPath(); + string newPath = "testDirectory"; + string expectedPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar)) + expectedPath += System.IO.Path.DirectorySeparatorChar; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathSegmentResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Path.Should().Be(expectedPath); + } + + [Fact] + public async Task CombinePath_WhenCalledWithEmptyPaths_ShouldReturnOkResultWithEmptyPath() + { + // Arrange + string originalPath = ""; + string newPath = ""; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + string content = await response.Content.ReadAsStringAsync(); + ValidationProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!.Title.Should().Be("One or more validation errors occurred."); + problemDetails.Errors["General.Validation"].Should().BeEquivalentTo("PathCannotBeEmpty", "PathCannotBeEmpty"); + } + + [Fact] + public async Task CombinePath_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + string originalPath = "/home/user"; + string newPath = "documents"; + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act + Func act = async () => await _client.GetAsync($"/api/v1.0/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}", cts.Token); + + // Assert + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task CombinePath_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string originalPath = System.IO.Path.GetTempPath(); + string newPath = "testFile.txt"; + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1.0/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task SplitPath_WhenCalledWithValidPath_ShouldReturnOkResultWithSplitSegments() + { + // Arrange + string tempPath = System.IO.Path.GetTempPath(); + string testPath = System.IO.Path.Combine(tempPath, "testFolder", "testFile.txt"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/split?path={Uri.EscapeDataString(testPath)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + IEnumerable? result = JsonSerializer.Deserialize>(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Should().HaveCountGreaterThanOrEqualTo(3); + result!.Select(r => r.Path).Should().Contain(["testFolder", "testFile.txt"]); + } + + [Fact] + public async Task SplitPath_WhenCalledWithEmptyPath_ShouldReturnOkResultWithEmptySegments() + { + // Arrange + string path = ""; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/split?path={Uri.EscapeDataString(path)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + string content = await response.Content.ReadAsStringAsync(); + ValidationProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!.Title.Should().Be("One or more validation errors occurred."); + problemDetails.Errors["General.Validation"].Should().BeEquivalentTo("PathCannotBeEmpty"); + } + + [Fact] + public async Task SplitPath_WhenCalledWithInvalidPath_ShouldReturnProblemDetails() + { + // Arrange + string path = "invalid:path"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/split?path={Uri.EscapeDataString(path)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + string content = await response.Content.ReadAsStringAsync(); + ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!.Title.Should().Be("One or more validation errors occurred."); + } + + [Fact] + public async Task SplitPath_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1.0/path/split?path={encodedPath}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task ValidatePath_WhenCalledWithValidPath_ShouldReturnOkResultWithIsValidTrue() + { + // Arrange + string tempPath = System.IO.Path.GetTempPath(); + string testPath = System.IO.Path.Combine(tempPath, "testFolder", "testFile.txt"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/validate?path={Uri.EscapeDataString(testPath)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathValidResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.IsValid.Should().BeTrue(); + } + + [Fact] + public async Task ValidatePath_WhenCalledWithInvalidPath_ShouldReturnOkResultWithIsValidFalse() + { + // Arrange + string invalidPath = "invalid:path"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/validate?path={Uri.EscapeDataString(invalidPath)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathValidResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.IsValid.Should().BeFalse(); + } + + [Fact] + public async Task ValidatePath_WhenCalledWithEmptyPath_ShouldReturnBadRequest() + { + // Arrange + string path = ""; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/validate?path={Uri.EscapeDataString(path)}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathValidResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.IsValid.Should().BeFalse(); + } + + [Fact] + public async Task ValidatePath_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory"); + string encodedPath = Uri.EscapeDataString(testPath); + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1.0/path/validate?path={encodedPath}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task CheckPathExists_WhenCalledWithExistingPath_ShouldReturnOkResultWithExistsTrue() + { + // Arrange + string tempPath = System.IO.Path.GetTempPath(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/check-path-exists?path={Uri.EscapeDataString(tempPath)}&includeHiddenElements=false"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathExistsResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Exists.Should().BeTrue(); + } + + [Fact] + public async Task CheckPathExists_WhenCalledWithNonExistingPath_ShouldReturnOkResultWithExistsFalse() + { + // Arrange + string nonExistingPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString()); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/check-path-exists?path={Uri.EscapeDataString(nonExistingPath)}&includeHiddenElements=false"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathExistsResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Exists.Should().BeFalse(); + } + + [Fact] + public async Task CheckPathExists_WhenCalledWithEmptyPath_ShouldReturnBadRequest() + { + // Arrange + string path = ""; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements=false"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathExistsResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Exists.Should().BeFalse(); + } + + [Fact] + public async Task CheckPathExists_WhenCalledWithInvalidPath_ShouldReturnBadRequest() + { + // Arrange + string invalidPath = "invalid:path"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/path/check-path-exists?path={Uri.EscapeDataString(invalidPath)}&includeHiddenElements=false"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + string content = await response.Content.ReadAsStringAsync(); + PathExistsResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + result.Should().NotBeNull(); + result!.Exists.Should().BeFalse(); + } + + [Fact] + public async Task CheckPathExists_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + string testPath = System.IO.Path.GetTempPath(); + string encodedPath = Uri.EscapeDataString(testPath); + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1.0/path/check-path-exists?path={encodedPath}&includeHiddenElements=false", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } + #endregion +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/ThumbnailsControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/ThumbnailsControllerTests.cs new file mode 100644 index 00000000..76d37a40 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/FileManagement/ThumbnailsControllerTests.cs @@ -0,0 +1,136 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThumbnailsControllerTests : IClassFixture, IClassFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + ReferenceHandler = ReferenceHandler.Preserve, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testImagePath; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + /// Fixture for creating and managing test images. + public ThumbnailsControllerTests(LuminaApiFactory apiFactory, TestImageFixture imageFixture) + { + _client = apiFactory.CreateClient(); + _testImagePath = imageFixture.ImagePath; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task GetThumbnail_WhenCalledWithValidPathAndQuality_ShouldReturnOkResultWithThumbnail() + { + // Arrange + int quality = 80; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={quality}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.OK); + response.Content.Headers.ContentType!.MediaType.Should().Be("image/jpeg"); + byte[] content = await response.Content.ReadAsByteArrayAsync(); + content.Should().NotBeEmpty(); + } + + [Fact] + public async Task GetThumbnail_WhenCalledWithInvalidPath_ShouldReturnForbidden() + { + // Arrange + string invalidImagePath = "/path/to/nonexistent/image.jpg"; + int quality = 80; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/thumbnails/get-thumbnail?path={Uri.EscapeDataString(invalidImagePath)}&quality={quality}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + string content = await response.Content.ReadAsStringAsync(); + ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + } + + [Fact] + public async Task GetThumbnail_WhenCalledWithEmptyPath_ShouldReturnForbidden() + { + // Arrange + string invalidImagePath = ""; + int quality = 80; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/thumbnails/get-thumbnail?path={Uri.EscapeDataString(invalidImagePath)}&quality={quality}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + string content = await response.Content.ReadAsStringAsync(); + ValidationProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!.Title.Should().Be("One or more validation errors occurred."); + problemDetails.Errors["General.Validation"].Should().BeEquivalentTo("PathCannotBeEmpty"); + } + + [Fact] + public async Task GetThumbnail_WhenCalledWithInvalidQuality_ShouldReturnForbidden() + { + // Arrange + int invalidQuality = -1; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1.0/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={invalidQuality}"); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + string content = await response.Content.ReadAsStringAsync(); + ValidationProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!.Title.Should().Be("One or more validation errors occurred."); + } + + [Fact] + public async Task GetThumbnail_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException() + { + // Arrange + int quality = 80; + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); // Cancel the token immediately + await _client.GetAsync($"/api/v1.0/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={quality}", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } + #endregion +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/BooksControllerTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksControllerTests.cs similarity index 99% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/BooksControllerTests.cs rename to tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksControllerTests.cs index 5280b527..ea89c6f6 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/BooksControllerTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/BooksControllerTests.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Bogus; using FluentAssertions; using Lumina.Contracts.Enums.BookLibrary; @@ -20,7 +20,7 @@ using System.Text.Json; using System.Threading.Tasks; #endregion -namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.Books; +namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.WrittenContentLibrary.BookLibrary.Books; /// /// Contains integration tests for the class. @@ -1616,4 +1616,4 @@ public class BooksControllerTests : IClassFixture bookResponse.Should().NotBeNull(); } #endregion -} \ No newline at end of file +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/Fixtures/AddBookRequestFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/Fixtures/AddBookRequestFixture.cs similarity index 100% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/Fixtures/AddBookRequestFixture.cs rename to tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/Fixtures/AddBookRequestFixture.cs diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/Fixtures/DomainBookFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/Fixtures/DomainBookFixture.cs similarity index 100% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/Books/Fixtures/DomainBookFixture.cs rename to tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Controllers/WrittenContentLibrary/BookLibrary/Books/Fixtures/DomainBookFixture.cs diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs index 4299777d..60d0d2d7 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs @@ -1,24 +1,14 @@ #region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; -using ErrorOr; using FluentAssertions; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; -using Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories; using Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSystem; using Lumina.Contracts.Enums.FileSystem; using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Common.Errors; using Lumina.Presentation.Api.Core.Controllers.FileManagement; -using Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; using Mediator; using Microsoft.AspNetCore.Mvc; using NSubstitute; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -53,7 +43,7 @@ public class FileSystemControllerTests { // Arrange CancellationToken cancellationToken = CancellationToken.None; - FileSystemTypeResponse expectedResponse = new FileSystemTypeResponse(PlatformType.Windows); + FileSystemTypeResponse expectedResponse = new(PlatformType.Windows); _mockMediator.Send(Arg.Any(), Arg.Any()) .Returns(expectedResponse); @@ -73,7 +63,7 @@ public class FileSystemControllerTests { // Arrange CancellationToken cancellationToken = CancellationToken.None; - FileSystemTypeResponse expectedResponse = new FileSystemTypeResponse(platformType); + FileSystemTypeResponse expectedResponse = new(platformType); _mockMediator.Send(Arg.Any(), Arg.Any()) .Returns(expectedResponse);