Merge pull request #23 from BinaryAlley/refactor/add-file-system-presentation-api-integration-tests

Adds Presentation Api layer integration tests for file system browser…
This commit is contained in:
BinaryAlley authored and GitHub committed 2024-10-12 09:31:08 +03:00
commit 959cff08fe
20 files changed
+2182 -24

No files matched your search

@@ -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());
});
@@ -49,7 +49,7 @@ public class DirectoriesController : ApiController
[FromQuery] bool includeFiles, [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<IEnumerable<FileSystemTreeNodeResponse>> 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<IEnumerable<DirectoryResponse>> 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)
{
@@ -48,7 +48,7 @@ public class FilesController : ApiController
[FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<IEnumerable<FileResponse>> 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)
{
+1 -1
View File
@@ -54,4 +54,4 @@ public class Program
await app.RunAsync().ConfigureAwait(false);
}
#endregion
}
}
@@ -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<Program>(ServiceLifetime.Singleton);
@@ -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;
/// <summary>
/// Custom JSON converter for the <see cref="Book"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookJsonConverter : JsonConverter<Book>
{
#region ===================================================================== METHODS ===================================================================================
@@ -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<Program>, IDisposable
{
builder.ConfigureServices(services =>
{
// remove existing DbContext configuration
ServiceDescriptor? descriptor = services.SingleOrDefault(serviceDescriptor => serviceDescriptor.ServiceType == typeof(DbContextOptions<LuminaDbContext>));
if (descriptor is not null)
services.Remove(descriptor);
// add SQLite DbContext configuration
services.AddDbContext<LuminaDbContext>(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<Program>, IDisposable
base.Dispose();
}
#endregion
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="DirectoriesController"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DirectoriesControllerTests : IClassFixture<LuminaApiFactory>
{
#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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="DirectoriesControllerTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<FileSystemTreeNodeResponse> 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<FileSystemTreeNodeResponse>(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<FileSystemTreeNodeResponse> 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<FileSystemTreeNodeResponse>(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<FileSystemTreeNodeResponse> 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<FileSystemTreeNodeResponse>(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<FileSystemTreeNodeResponse> 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<FileSystemTreeNodeResponse>(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<FileSystemTreeNodeResponse> 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<FileSystemTreeNodeResponse>(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<FileSystemTreeNodeResponse> 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<FileSystemTreeNodeResponse>(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<FileSystemTreeNodeResponse> 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<FileSystemTreeNodeResponse>(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<DirectoryResponse> 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<DirectoryResponse>(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<DirectoryResponse> 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<DirectoryResponse>(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<DirectoryResponse> 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<DirectoryResponse>(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
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="DrivesController"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DrivesControllerTests : IClassFixture<LuminaApiFactory>
{
#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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="DrivesControllerTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<FileSystemTreeNodeResponse> 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<FileSystemTreeNodeResponse>(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
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="FileSystemController"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemControllerTests : IClassFixture<LuminaApiFactory>
{
#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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemControllerTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<FileSystemTypeResponse>(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<FileSystemTypeResponse>(content1, _jsonOptions);
FileSystemTypeResponse? result2 = JsonSerializer.Deserialize<FileSystemTypeResponse>(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<Task> act = async () => await _client.GetAsync("/api/v1.0/file-system/get-type", cts.Token);
// Assert
await act.Should().NotThrowAsync();
}
#endregion
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="FilesController"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FilesControllerTests : IClassFixture<LuminaApiFactory>
{
#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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="FilesControllerTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<FileSystemTreeNodeResponse> 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<FileSystemTreeNodeResponse>(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<FileSystemTreeNodeResponse> 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<FileSystemTreeNodeResponse>(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<FileSystemTreeNodeResponse> 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<FileSystemTreeNodeResponse>(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<FileResponse> 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<FileResponse>(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<FileResponse> 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<FileResponse>(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<FileResponse> 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<FileResponse>(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
}
@@ -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;
/// <summary>
/// Fixture class for creating and managing a file system structure for integration testing purposes.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemStructureFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly string _rootPath;
private readonly Faker _faker = new();
#endregion
#region ===================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemStructureFixture"/> class.
/// </summary>
public FileSystemStructureFixture()
{
_rootPath = Path.Combine(AppContext.BaseDirectory, "TestFileSystemStructure_" + Guid.NewGuid());
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// 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.
/// </summary>
/// <returns>The path to the root directory of the created file system structure.</returns>
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;
}
/// <summary>
/// Sets the hidden attribute for a file or directory.
/// </summary>
/// <param name="path">The path to the file or directory.</param>
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;
}
/// <summary>
/// Deletes the file system structure created for testing purposes.
/// </summary>
public void CleanupFileSystemStructure()
{
if (Directory.Exists(_rootPath))
Directory.Delete(_rootPath, recursive: true);
}
#endregion
}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Responses.FileManagement;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures;
/// <summary>
/// Fixture class for the <see cref="FileSystemTreeNodeResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemTreeNodeResponseFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker = new();
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a single <see cref="FileSystemTreeNodeResponse"/> with a nested structure.
/// </summary>
/// <param name="currentDepth">The current depth in the tree structure. Default is 0 (root level).</param>
/// <param name="maxDepth">The maximum depth of the tree structure. Default is 2.</param>
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
/// <returns>A <see cref="FileSystemTreeNodeResponse"/> with a nested structure.</returns>
public FileSystemTreeNodeResponse Create(int currentDepth = 0, int maxDepth = 2, int maxChildren = 3)
{
FileSystemTreeNodeResponse response = new()
{
Path = _faker.System.FilePath(),
Name = _faker.System.FileName(),
ItemType = FileSystemItemType.Directory,
IsExpanded = _faker.Random.Bool(),
ChildrenLoaded = true,
Children = []
};
if (currentDepth < maxDepth)
{
int childCount = _faker.Random.Int(1, maxChildren);
for (int i = 0; i < childCount; i++)
response.Children.Add(Create(currentDepth + 1, maxDepth, maxChildren));
}
return response;
}
/// <summary>
/// Creates a list of <see cref="FileSystemTreeNodeResponse"/> objects, each with a nested structure.
/// </summary>
/// <param name="count">The number of root-level nodes to create. Default is 2.</param>
/// <param name="maxDepth">The maximum depth of the tree structure for each root node. Default is 2.</param>
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
/// <returns>A list of <see cref="FileSystemTreeNodeResponse"/> objects with nested structures.</returns>
public List<FileSystemTreeNodeResponse> CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3)
{
return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList();
}
#endregion
}
@@ -0,0 +1,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;
/// <summary>
/// Fixture class for creating and managing a test image for integration testing purposes.
/// </summary>
[ExcludeFromCodeCoverage]
public class TestImageFixture : IDisposable
{
#region ==================================================================== PROPERTIES =================================================================================
/// <summary>
/// Gets the path of the created test image.
/// </summary>
public string ImagePath { get; }
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="TestImageFixture"/> class.
/// </summary>
public TestImageFixture()
{
ImagePath = Path.Combine(Path.GetTempPath(), $"TestImage_{Guid.NewGuid()}.jpg");
CreateTestImage();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a test image file.
/// </summary>
private void CreateTestImage()
{
using (Image image = new Image<Rgba32>(100, 100))
image.Save(ImagePath, new JpegEncoder());
}
/// <summary>
/// Disposes the fixture, ensuring the test image is deleted.
/// </summary>
public void Dispose()
{
if (File.Exists(ImagePath))
File.Delete(ImagePath);
}
#endregion
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="PathController"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PathControllerTests : IClassFixture<LuminaApiFactory>
{
#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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="PathControllerTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<PathSegmentResponse>(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<ProblemDetails>(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<ValidationProblemDetails>(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<Task> 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<Task> 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<TaskCanceledException>();
}
[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<PathSeparatorResponse>(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<PathSeparatorResponse>(content1, _jsonOptions);
PathSeparatorResponse? result2 = JsonSerializer.Deserialize<PathSeparatorResponse>(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<Task> 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<Task> 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<TaskCanceledException>();
}
[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<PathSegmentResponse>? result = JsonSerializer.Deserialize<IEnumerable<PathSegmentResponse>>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Should().NotBeEmpty();
List<string> 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<ProblemDetails>(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<ProblemDetails>(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<ValidationProblemDetails>(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<Task> 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<Task> 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<TaskCanceledException>();
}
[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<PathSegmentResponse>(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<ValidationProblemDetails>(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<Task> 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<Task> 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<TaskCanceledException>();
}
[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<PathSegmentResponse>? result = JsonSerializer.Deserialize<IEnumerable<PathSegmentResponse>>(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<ValidationProblemDetails>(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<ProblemDetails>(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<Task> 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<TaskCanceledException>();
}
[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<PathValidResponse>(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<PathValidResponse>(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<PathValidResponse>(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<Task> 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<TaskCanceledException>();
}
[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<PathExistsResponse>(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<PathExistsResponse>(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<PathExistsResponse>(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<PathExistsResponse>(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<Task> 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<TaskCanceledException>();
}
#endregion
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="ThumbnailsController"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThumbnailsControllerTests : IClassFixture<LuminaApiFactory>, IClassFixture<TestImageFixture>
{
#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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="ThumbnailsControllerTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
/// <param name="imageFixture">Fixture for creating and managing test images.</param>
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<ProblemDetails>(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<ValidationProblemDetails>(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<ValidationProblemDetails>(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<Task> 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<TaskCanceledException>();
}
#endregion
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="BooksController"/> class.
@@ -1616,4 +1616,4 @@ public class BooksControllerTests : IClassFixture<LuminaApiFactory>
bookResponse.Should().NotBeNull();
}
#endregion
}
}
@@ -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<GetFileSystemQuery>(), Arg.Any<CancellationToken>())
.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<GetFileSystemQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedResponse);